blob: d2258cc212498def8d9356f87738ea7f53af8652 [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
Richard Smith06f71b52018-08-04 00:57:17 +0000322 /// Get the range of valid index adjustments in the form
323 /// {maximum value that can be subtracted from this pointer,
324 /// maximum value that can be added to this pointer}
325 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
326 if (Invalid || isMostDerivedAnUnsizedArray())
327 return {0, 0};
328
329 // [expr.add]p4: For the purposes of these operators, a pointer to a
330 // nonarray object behaves the same as a pointer to the first element of
331 // an array of length one with the type of the object as its element type.
332 bool IsArray = MostDerivedPathLength == Entries.size() &&
333 MostDerivedIsArrayElement;
334 uint64_t ArrayIndex =
335 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
336 uint64_t ArraySize =
337 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
338 return {ArrayIndex, ArraySize - ArrayIndex};
339 }
340
Richard Smitha8105bc2012-01-06 16:39:00 +0000341 /// Check that this refers to a valid subobject.
342 bool isValidSubobject() const {
343 if (Invalid)
344 return false;
345 return !isOnePastTheEnd();
346 }
347 /// Check that this refers to a valid subobject, and if not, produce a
348 /// relevant diagnostic and set the designator as invalid.
349 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
350
Richard Smith06f71b52018-08-04 00:57:17 +0000351 /// Get the type of the designated object.
352 QualType getType(ASTContext &Ctx) const {
353 assert(!Invalid && "invalid designator has no subobject type");
354 return MostDerivedPathLength == Entries.size()
355 ? MostDerivedType
356 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
357 }
358
Richard Smitha8105bc2012-01-06 16:39:00 +0000359 /// Update this designator to refer to the first element within this array.
360 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000361 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000362 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000363 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000364
365 // This is a most-derived object.
366 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000367 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000368 MostDerivedArraySize = CAT->getSize().getZExtValue();
369 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000370 }
George Burgess IVe3763372016-12-22 02:50:20 +0000371 /// Update this designator to refer to the first element within the array of
372 /// elements of type T. This is an array of unknown size.
373 void addUnsizedArrayUnchecked(QualType ElemTy) {
374 PathEntry Entry;
375 Entry.ArrayIndex = 0;
376 Entries.push_back(Entry);
377
378 MostDerivedType = ElemTy;
379 MostDerivedIsArrayElement = true;
380 // The value in MostDerivedArraySize is undefined in this case. So, set it
381 // to an arbitrary value that's likely to loudly break things if it's
382 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000383 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000384 MostDerivedPathLength = Entries.size();
385 }
Richard Smith96e0c102011-11-04 02:25:55 +0000386 /// Update this designator to refer to the given base or member of this
387 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000388 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000389 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000390 APValue::BaseOrMemberType Value(D, Virtual);
391 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000392 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000393
394 // If this isn't a base class, it's a new most-derived object.
395 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
396 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000397 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000398 MostDerivedArraySize = 0;
399 MostDerivedPathLength = Entries.size();
400 }
Richard Smith96e0c102011-11-04 02:25:55 +0000401 }
Richard Smith66c96992012-02-18 22:04:06 +0000402 /// Update this designator to refer to the given complex component.
403 void addComplexUnchecked(QualType EltTy, bool Imag) {
404 PathEntry Entry;
405 Entry.ArrayIndex = Imag;
406 Entries.push_back(Entry);
407
408 // This is technically a most-derived object, though in practice this
409 // is unlikely to matter.
410 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000411 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000412 MostDerivedArraySize = 2;
413 MostDerivedPathLength = Entries.size();
414 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000415 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000416 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
417 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000418 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000419 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
420 if (Invalid || !N) return;
421 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
422 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000423 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000424 // Can't verify -- trust that the user is doing the right thing (or if
425 // not, trust that the caller will catch the bad behavior).
426 // FIXME: Should we reject if this overflows, at least?
427 Entries.back().ArrayIndex += TruncatedN;
428 return;
429 }
430
431 // [expr.add]p4: For the purposes of these operators, a pointer to a
432 // nonarray object behaves the same as a pointer to the first element of
433 // an array of length one with the type of the object as its element type.
434 bool IsArray = MostDerivedPathLength == Entries.size() &&
435 MostDerivedIsArrayElement;
436 uint64_t ArrayIndex =
437 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
438 uint64_t ArraySize =
439 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
440
441 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
442 // Calculate the actual index in a wide enough type, so we can include
443 // it in the note.
444 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
445 (llvm::APInt&)N += ArrayIndex;
446 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
447 diagnosePointerArithmetic(Info, E, N);
448 setInvalid();
449 return;
450 }
451
452 ArrayIndex += TruncatedN;
453 assert(ArrayIndex <= ArraySize &&
454 "bounds check succeeded for out-of-bounds index");
455
456 if (IsArray)
457 Entries.back().ArrayIndex = ArrayIndex;
458 else
459 IsOnePastTheEnd = (ArrayIndex != 0);
460 }
Richard Smith96e0c102011-11-04 02:25:55 +0000461 };
462
Richard Smith254a73d2011-10-28 22:34:42 +0000463 /// A stack frame in the constexpr call stack.
464 struct CallStackFrame {
465 EvalInfo &Info;
466
467 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000468 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000469
Richard Smithf6f003a2011-12-16 19:06:07 +0000470 /// Callee - The function which was called.
471 const FunctionDecl *Callee;
472
Richard Smithd62306a2011-11-10 06:34:14 +0000473 /// This - The binding for the this pointer in this call, if any.
474 const LValue *This;
475
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000476 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000477 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000478 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000479
Eli Friedman4830ec82012-06-25 21:21:08 +0000480 // Note that we intentionally use std::map here so that references to
481 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000482 typedef std::pair<const void *, unsigned> MapKeyTy;
483 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000484 /// Temporaries - Temporary lvalues materialized within this stack frame.
485 MapTy Temporaries;
486
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000487 /// CallLoc - The location of the call expression for this call.
488 SourceLocation CallLoc;
489
490 /// Index - The call index of this call.
491 unsigned Index;
492
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000493 /// The stack of integers for tracking version numbers for temporaries.
494 SmallVector<unsigned, 2> TempVersionStack = {1};
495 unsigned CurTempVersion = TempVersionStack.back();
496
497 unsigned getTempVersion() const { return TempVersionStack.back(); }
498
499 void pushTempVersion() {
500 TempVersionStack.push_back(++CurTempVersion);
501 }
502
503 void popTempVersion() {
504 TempVersionStack.pop_back();
505 }
506
Faisal Vali051e3a22017-02-16 04:12:21 +0000507 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
508 // on the overall stack usage of deeply-recursing constexpr evaluataions.
509 // (We should cache this map rather than recomputing it repeatedly.)
510 // But let's try this and see how it goes; we can look into caching the map
511 // as a later change.
512
513 /// LambdaCaptureFields - Mapping from captured variables/this to
514 /// corresponding data members in the closure class.
515 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
516 FieldDecl *LambdaThisCaptureField;
517
Richard Smithf6f003a2011-12-16 19:06:07 +0000518 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
519 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000520 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000521 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000522
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000523 // Return the temporary for Key whose version number is Version.
524 APValue *getTemporary(const void *Key, unsigned Version) {
525 MapKeyTy KV(Key, Version);
526 auto LB = Temporaries.lower_bound(KV);
527 if (LB != Temporaries.end() && LB->first == KV)
528 return &LB->second;
529 // Pair (Key,Version) wasn't found in the map. Check that no elements
530 // in the map have 'Key' as their key.
531 assert((LB == Temporaries.end() || LB->first.first != Key) &&
532 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
533 "Element with key 'Key' found in map");
534 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000535 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000536
537 // Return the current temporary for Key in the map.
538 APValue *getCurrentTemporary(const void *Key) {
539 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
540 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
541 return &std::prev(UB)->second;
542 return nullptr;
543 }
544
545 // Return the version number of the current temporary for Key.
546 unsigned getCurrentTemporaryVersion(const void *Key) const {
547 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
548 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
549 return std::prev(UB)->first.second;
550 return 0;
551 }
552
Richard Smith08d6a2c2013-07-24 07:11:57 +0000553 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000554 };
555
Richard Smith852c9db2013-04-20 22:23:05 +0000556 /// Temporarily override 'this'.
557 class ThisOverrideRAII {
558 public:
559 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
560 : Frame(Frame), OldThis(Frame.This) {
561 if (Enable)
562 Frame.This = NewThis;
563 }
564 ~ThisOverrideRAII() {
565 Frame.This = OldThis;
566 }
567 private:
568 CallStackFrame &Frame;
569 const LValue *OldThis;
570 };
571
Richard Smith92b1ce02011-12-12 09:28:41 +0000572 /// A partial diagnostic which we might know in advance that we are not going
573 /// to emit.
574 class OptionalDiagnostic {
575 PartialDiagnostic *Diag;
576
577 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000578 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
579 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000580
581 template<typename T>
582 OptionalDiagnostic &operator<<(const T &v) {
583 if (Diag)
584 *Diag << v;
585 return *this;
586 }
Richard Smithfe800032012-01-31 04:08:20 +0000587
588 OptionalDiagnostic &operator<<(const APSInt &I) {
589 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000590 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000591 I.toString(Buffer);
592 *Diag << StringRef(Buffer.data(), Buffer.size());
593 }
594 return *this;
595 }
596
597 OptionalDiagnostic &operator<<(const APFloat &F) {
598 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000599 // FIXME: Force the precision of the source value down so we don't
600 // print digits which are usually useless (we don't really care here if
601 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000602 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000603 // representation which rounds to the correct value, but it's a bit
604 // tricky to implement.
605 unsigned precision =
606 llvm::APFloat::semanticsPrecision(F.getSemantics());
607 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000608 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000609 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000610 *Diag << StringRef(Buffer.data(), Buffer.size());
611 }
612 return *this;
613 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000614 };
615
Richard Smith08d6a2c2013-07-24 07:11:57 +0000616 /// A cleanup, and a flag indicating whether it is lifetime-extended.
617 class Cleanup {
618 llvm::PointerIntPair<APValue*, 1, bool> Value;
619
620 public:
621 Cleanup(APValue *Val, bool IsLifetimeExtended)
622 : Value(Val, IsLifetimeExtended) {}
623
624 bool isLifetimeExtended() const { return Value.getInt(); }
625 void endLifetime() {
626 *Value.getPointer() = APValue();
627 }
628 };
629
Richard Smithb228a862012-02-15 02:18:13 +0000630 /// EvalInfo - This is a private struct used by the evaluator to capture
631 /// information about a subexpression as it is folded. It retains information
632 /// about the AST context, but also maintains information about the folded
633 /// expression.
634 ///
635 /// If an expression could be evaluated, it is still possible it is not a C
636 /// "integer constant expression" or constant expression. If not, this struct
637 /// captures information about how and why not.
638 ///
639 /// One bit of information passed *into* the request for constant folding
640 /// indicates whether the subexpression is "evaluated" or not according to C
641 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
642 /// evaluate the expression regardless of what the RHS is, but C only allows
643 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000644 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000645 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000646
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000647 /// EvalStatus - Contains information about the evaluation.
648 Expr::EvalStatus &EvalStatus;
649
650 /// CurrentCall - The top of the constexpr call stack.
651 CallStackFrame *CurrentCall;
652
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000653 /// CallStackDepth - The number of calls in the call stack right now.
654 unsigned CallStackDepth;
655
Richard Smithb228a862012-02-15 02:18:13 +0000656 /// NextCallIndex - The next call index to assign.
657 unsigned NextCallIndex;
658
Richard Smitha3d3bd22013-05-08 02:12:03 +0000659 /// StepsLeft - The remaining number of evaluation steps we're permitted
660 /// to perform. This is essentially a limit for the number of statements
661 /// we will evaluate.
662 unsigned StepsLeft;
663
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000664 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000665 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000666 CallStackFrame BottomFrame;
667
Richard Smith08d6a2c2013-07-24 07:11:57 +0000668 /// A stack of values whose lifetimes end at the end of some surrounding
669 /// evaluation frame.
670 llvm::SmallVector<Cleanup, 16> CleanupStack;
671
Richard Smithd62306a2011-11-10 06:34:14 +0000672 /// EvaluatingDecl - This is the declaration whose initializer is being
673 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000674 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000675
676 /// EvaluatingDeclValue - This is the value being constructed for the
677 /// declaration whose initializer is being evaluated, if any.
678 APValue *EvaluatingDeclValue;
679
Erik Pilkington42925492017-10-04 00:18:55 +0000680 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
681 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000682 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
683 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000684
685 /// EvaluatingConstructors - Set of objects that are currently being
686 /// constructed.
687 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
688
689 struct EvaluatingConstructorRAII {
690 EvalInfo &EI;
691 EvaluatingObject Object;
692 bool DidInsert;
693 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
694 : EI(EI), Object(Object) {
695 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
696 }
697 ~EvaluatingConstructorRAII() {
698 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
699 }
700 };
701
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000702 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
703 unsigned Version) {
704 return EvaluatingConstructors.count(
705 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000706 }
707
Richard Smith410306b2016-12-12 02:53:20 +0000708 /// The current array initialization index, if we're performing array
709 /// initialization.
710 uint64_t ArrayInitIndex = -1;
711
Richard Smith357362d2011-12-13 06:39:58 +0000712 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
713 /// notes attached to it will also be stored, otherwise they will not be.
714 bool HasActiveDiagnostic;
715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000716 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000717 /// fold (not just why it's not strictly a constant expression)?
718 bool HasFoldFailureDiagnostic;
719
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000720 /// Whether or not we're currently speculatively evaluating.
George Burgess IV8c892b52016-05-25 22:31:54 +0000721 bool IsSpeculativelyEvaluating;
722
Richard Smith6d4c6582013-11-05 22:18:15 +0000723 enum EvaluationMode {
724 /// Evaluate as a constant expression. Stop if we find that the expression
725 /// is not a constant expression.
726 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000727
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 /// Evaluate as a potential constant expression. Keep going if we hit a
729 /// construct that we can't evaluate yet (because we don't yet know the
730 /// value of something) but stop if we hit something that could never be
731 /// a constant expression.
732 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000733
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 /// Fold the expression to a constant. Stop if we hit a side-effect that
735 /// we can't model.
736 EM_ConstantFold,
737
738 /// Evaluate the expression looking for integer overflow and similar
739 /// issues. Don't worry about side-effects, and try to visit all
740 /// subexpressions.
741 EM_EvaluateForOverflow,
742
743 /// Evaluate in any way we know how. Don't worry about side-effects that
744 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000745 EM_IgnoreSideEffects,
746
747 /// Evaluate as a constant expression. Stop if we find that the expression
748 /// is not a constant expression. Some expressions can be retried in the
749 /// optimizer if we don't constant fold them here, but in an unevaluated
750 /// context we try to fold them immediately since the optimizer never
751 /// gets a chance to look at it.
752 EM_ConstantExpressionUnevaluated,
753
754 /// Evaluate as a potential constant expression. Keep going if we hit a
755 /// construct that we can't evaluate yet (because we don't yet know the
756 /// value of something) but stop if we hit something that could never be
757 /// a constant expression. Some expressions can be retried in the
758 /// optimizer if we don't constant fold them here, but in an unevaluated
759 /// context we try to fold them immediately since the optimizer never
760 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000761 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 } EvalMode;
763
764 /// Are we checking whether the expression is a potential constant
765 /// expression?
766 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000767 return EvalMode == EM_PotentialConstantExpression ||
768 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000769 }
770
771 /// Are we checking an expression for overflow?
772 // FIXME: We should check for any kind of undefined or suspicious behavior
773 // in such constructs, not just overflow.
774 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
775
776 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000777 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000778 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000779 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000780 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
781 EvaluatingDecl((const ValueDecl *)nullptr),
782 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000783 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
784 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000785
Richard Smith7525ff62013-05-09 07:14:00 +0000786 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
787 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000788 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000789 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000790 }
791
David Blaikiebbafb8a2012-03-11 07:00:24 +0000792 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000793
Richard Smith357362d2011-12-13 06:39:58 +0000794 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000795 // Don't perform any constexpr calls (other than the call we're checking)
796 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000797 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000798 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000799 if (NextCallIndex == 0) {
800 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000801 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000802 return false;
803 }
Richard Smith357362d2011-12-13 06:39:58 +0000804 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
805 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000806 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000807 << getLangOpts().ConstexprCallDepth;
808 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000809 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000810
Richard Smithb228a862012-02-15 02:18:13 +0000811 CallStackFrame *getCallFrame(unsigned CallIndex) {
812 assert(CallIndex && "no call index in getCallFrame");
813 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
814 // be null in this loop.
815 CallStackFrame *Frame = CurrentCall;
816 while (Frame->Index > CallIndex)
817 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000818 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000819 }
820
Richard Smitha3d3bd22013-05-08 02:12:03 +0000821 bool nextStep(const Stmt *S) {
822 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000823 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000824 return false;
825 }
826 --StepsLeft;
827 return true;
828 }
829
Richard Smith357362d2011-12-13 06:39:58 +0000830 private:
831 /// Add a diagnostic to the diagnostics list.
832 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
833 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
834 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
835 return EvalStatus.Diag->back().second;
836 }
837
Richard Smithf6f003a2011-12-16 19:06:07 +0000838 /// Add notes containing a call stack to the current point of evaluation.
839 void addCallStack(unsigned Limit);
840
Faisal Valie690b7a2016-07-02 22:34:24 +0000841 private:
842 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
843 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000844
Richard Smith92b1ce02011-12-12 09:28:41 +0000845 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000846 // If we have a prior diagnostic, it will be noting that the expression
847 // isn't a constant expression. This diagnostic is more important,
848 // unless we require this evaluation to produce a constant expression.
849 //
850 // FIXME: We might want to show both diagnostics to the user in
851 // EM_ConstantFold mode.
852 if (!EvalStatus.Diag->empty()) {
853 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000854 case EM_ConstantFold:
855 case EM_IgnoreSideEffects:
856 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000857 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000858 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000859 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000860 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000861 case EM_ConstantExpression:
862 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000863 case EM_ConstantExpressionUnevaluated:
864 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000865 HasActiveDiagnostic = false;
866 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000867 }
868 }
869
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 unsigned CallStackNotes = CallStackDepth - 1;
871 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
872 if (Limit)
873 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000875 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000876
Richard Smith357362d2011-12-13 06:39:58 +0000877 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000878 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000879 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000880 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
881 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000882 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000883 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000884 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000885 }
Richard Smith357362d2011-12-13 06:39:58 +0000886 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000887 return OptionalDiagnostic();
888 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000889 public:
890 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
891 OptionalDiagnostic
892 FFDiag(SourceLocation Loc,
893 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
894 unsigned ExtraNotes = 0) {
895 return Diag(Loc, DiagId, ExtraNotes, false);
896 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000897
Faisal Valie690b7a2016-07-02 22:34:24 +0000898 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000899 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000900 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000901 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000902 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000903 HasActiveDiagnostic = false;
904 return OptionalDiagnostic();
905 }
906
Richard Smith92b1ce02011-12-12 09:28:41 +0000907 /// Diagnose that the evaluation does not produce a C++11 core constant
908 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000909 ///
910 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
911 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000912 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000913 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000914 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000915 // Don't override a previous diagnostic. Don't bother collecting
916 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000917 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000918 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000919 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000920 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000921 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000922 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000923 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
924 = diag::note_invalid_subexpr_in_const_expr,
925 unsigned ExtraNotes = 0) {
926 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
927 }
Richard Smith357362d2011-12-13 06:39:58 +0000928 /// Add a note to a prior diagnostic.
929 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
930 if (!HasActiveDiagnostic)
931 return OptionalDiagnostic();
932 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000933 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000934
935 /// Add a stack of notes to a prior diagnostic.
936 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
937 if (HasActiveDiagnostic) {
938 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
939 Diags.begin(), Diags.end());
940 }
941 }
Richard Smith253c2a32012-01-27 01:14:48 +0000942
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 /// Should we continue evaluation after encountering a side-effect that we
944 /// couldn't model?
945 bool keepEvaluatingAfterSideEffect() {
946 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000947 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000948 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000949 case EM_EvaluateForOverflow:
950 case EM_IgnoreSideEffects:
951 return true;
952
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000954 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000955 case EM_ConstantFold:
956 return false;
957 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000958 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 }
960
961 /// Note that we have had a side-effect, and determine whether we should
962 /// keep evaluating.
963 bool noteSideEffect() {
964 EvalStatus.HasSideEffects = true;
965 return keepEvaluatingAfterSideEffect();
966 }
967
Richard Smithce8eca52015-12-08 03:21:47 +0000968 /// Should we continue evaluation after encountering undefined behavior?
969 bool keepEvaluatingAfterUndefinedBehavior() {
970 switch (EvalMode) {
971 case EM_EvaluateForOverflow:
972 case EM_IgnoreSideEffects:
973 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000974 return true;
975
976 case EM_PotentialConstantExpression:
977 case EM_PotentialConstantExpressionUnevaluated:
978 case EM_ConstantExpression:
979 case EM_ConstantExpressionUnevaluated:
980 return false;
981 }
982 llvm_unreachable("Missed EvalMode case");
983 }
984
985 /// Note that we hit something that was technically undefined behavior, but
986 /// that we can evaluate past it (such as signed overflow or floating-point
987 /// division by zero.)
988 bool noteUndefinedBehavior() {
989 EvalStatus.HasUndefinedBehavior = true;
990 return keepEvaluatingAfterUndefinedBehavior();
991 }
992
Richard Smith253c2a32012-01-27 01:14:48 +0000993 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000994 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000995 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000996 if (!StepsLeft)
997 return false;
998
999 switch (EvalMode) {
1000 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001001 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001002 case EM_EvaluateForOverflow:
1003 return true;
1004
1005 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001006 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001007 case EM_ConstantFold:
1008 case EM_IgnoreSideEffects:
1009 return false;
1010 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001011 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001012 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001013
George Burgess IV8c892b52016-05-25 22:31:54 +00001014 /// Notes that we failed to evaluate an expression that other expressions
1015 /// directly depend on, and determine if we should keep evaluating. This
1016 /// should only be called if we actually intend to keep evaluating.
1017 ///
1018 /// Call noteSideEffect() instead if we may be able to ignore the value that
1019 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1020 ///
1021 /// (Foo(), 1) // use noteSideEffect
1022 /// (Foo() || true) // use noteSideEffect
1023 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001024 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001025 // Failure when evaluating some expression often means there is some
1026 // subexpression whose evaluation was skipped. Therefore, (because we
1027 // don't track whether we skipped an expression when unwinding after an
1028 // evaluation failure) every evaluation failure that bubbles up from a
1029 // subexpression implies that a side-effect has potentially happened. We
1030 // skip setting the HasSideEffects flag to true until we decide to
1031 // continue evaluating after that point, which happens here.
1032 bool KeepGoing = keepEvaluatingAfterFailure();
1033 EvalStatus.HasSideEffects |= KeepGoing;
1034 return KeepGoing;
1035 }
1036
Richard Smith410306b2016-12-12 02:53:20 +00001037 class ArrayInitLoopIndex {
1038 EvalInfo &Info;
1039 uint64_t OuterIndex;
1040
1041 public:
1042 ArrayInitLoopIndex(EvalInfo &Info)
1043 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1044 Info.ArrayInitIndex = 0;
1045 }
1046 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1047
1048 operator uint64_t&() { return Info.ArrayInitIndex; }
1049 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001050 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001051
1052 /// Object used to treat all foldable expressions as constant expressions.
1053 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001054 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001055 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001056 bool HadNoPriorDiags;
1057 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001058
Richard Smith6d4c6582013-11-05 22:18:15 +00001059 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1060 : Info(Info),
1061 Enabled(Enabled),
1062 HadNoPriorDiags(Info.EvalStatus.Diag &&
1063 Info.EvalStatus.Diag->empty() &&
1064 !Info.EvalStatus.HasSideEffects),
1065 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001066 if (Enabled &&
1067 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1068 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001069 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001070 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001071 void keepDiagnostics() { Enabled = false; }
1072 ~FoldConstant() {
1073 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001074 !Info.EvalStatus.HasSideEffects)
1075 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001076 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001077 }
1078 };
Richard Smith17100ba2012-02-16 02:46:34 +00001079
James Y Knight892b09b2018-10-10 02:53:43 +00001080 /// RAII object used to set the current evaluation mode to ignore
1081 /// side-effects.
1082 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001083 EvalInfo &Info;
1084 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001085 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001086 : Info(Info), OldMode(Info.EvalMode) {
1087 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001088 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089 }
1090
James Y Knight892b09b2018-10-10 02:53:43 +00001091 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092 };
1093
George Burgess IV8c892b52016-05-25 22:31:54 +00001094 /// RAII object used to optionally suppress diagnostics and side-effects from
1095 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001096 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001097 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001098 Expr::EvalStatus OldStatus;
1099 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001100
George Burgess IV8c892b52016-05-25 22:31:54 +00001101 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001102 Info = Other.Info;
1103 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001104 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001105 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001106 }
1107
1108 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001109 if (!Info)
1110 return;
1111
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001112 Info->EvalStatus = OldStatus;
1113 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001114 }
1115
Richard Smith17100ba2012-02-16 02:46:34 +00001116 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001117 SpeculativeEvaluationRAII() = default;
1118
1119 SpeculativeEvaluationRAII(
1120 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001121 : Info(&Info), OldStatus(Info.EvalStatus),
1122 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001123 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001124 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001125 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001126
1127 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1128 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1129 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001130 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001131
1132 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1133 maybeRestoreState();
1134 moveFromAndCancel(std::move(Other));
1135 return *this;
1136 }
1137
1138 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001139 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001140
1141 /// RAII object wrapping a full-expression or block scope, and handling
1142 /// the ending of the lifetime of temporaries created within it.
1143 template<bool IsFullExpression>
1144 class ScopeRAII {
1145 EvalInfo &Info;
1146 unsigned OldStackSize;
1147 public:
1148 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001149 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1150 // Push a new temporary version. This is needed to distinguish between
1151 // temporaries created in different iterations of a loop.
1152 Info.CurrentCall->pushTempVersion();
1153 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001154 ~ScopeRAII() {
1155 // Body moved to a static method to encourage the compiler to inline away
1156 // instances of this class.
1157 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001158 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001159 }
1160 private:
1161 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1162 unsigned NewEnd = OldStackSize;
1163 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1164 I != N; ++I) {
1165 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1166 // Full-expression cleanup of a lifetime-extended temporary: nothing
1167 // to do, just move this cleanup to the right place in the stack.
1168 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1169 ++NewEnd;
1170 } else {
1171 // End the lifetime of the object.
1172 Info.CleanupStack[I].endLifetime();
1173 }
1174 }
1175 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1176 Info.CleanupStack.end());
1177 }
1178 };
1179 typedef ScopeRAII<false> BlockScopeRAII;
1180 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001181}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001182
Richard Smitha8105bc2012-01-06 16:39:00 +00001183bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1184 CheckSubobjectKind CSK) {
1185 if (Invalid)
1186 return false;
1187 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001188 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001189 << CSK;
1190 setInvalid();
1191 return false;
1192 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001193 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1194 // must actually be at least one array element; even a VLA cannot have a
1195 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001196 return true;
1197}
1198
Richard Smith6f4f0f12017-10-20 22:56:25 +00001199void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1200 const Expr *E) {
1201 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1202 // Do not set the designator as invalid: we can represent this situation,
1203 // and correct handling of __builtin_object_size requires us to do so.
1204}
1205
Richard Smitha8105bc2012-01-06 16:39:00 +00001206void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001207 const Expr *E,
1208 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001209 // If we're complaining, we must be able to statically determine the size of
1210 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001211 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001212 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001213 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001214 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001215 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001216 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001217 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001218 setInvalid();
1219}
1220
Richard Smithf6f003a2011-12-16 19:06:07 +00001221CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1222 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001223 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001224 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1225 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001226 Info.CurrentCall = this;
1227 ++Info.CallStackDepth;
1228}
1229
1230CallStackFrame::~CallStackFrame() {
1231 assert(Info.CurrentCall == this && "calls retired out of order");
1232 --Info.CallStackDepth;
1233 Info.CurrentCall = Caller;
1234}
1235
Richard Smith08d6a2c2013-07-24 07:11:57 +00001236APValue &CallStackFrame::createTemporary(const void *Key,
1237 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001238 unsigned Version = Info.CurrentCall->getTempVersion();
1239 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001240 assert(Result.isUninit() && "temporary created multiple times");
1241 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1242 return Result;
1243}
1244
Richard Smith84401042013-06-03 05:03:02 +00001245static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001246
1247void EvalInfo::addCallStack(unsigned Limit) {
1248 // Determine which calls to skip, if any.
1249 unsigned ActiveCalls = CallStackDepth - 1;
1250 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1251 if (Limit && Limit < ActiveCalls) {
1252 SkipStart = Limit / 2 + Limit % 2;
1253 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001254 }
1255
Richard Smithf6f003a2011-12-16 19:06:07 +00001256 // Walk the call stack and add the diagnostics.
1257 unsigned CallIdx = 0;
1258 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1259 Frame = Frame->Caller, ++CallIdx) {
1260 // Skip this call?
1261 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1262 if (CallIdx == SkipStart) {
1263 // Note that we're skipping calls.
1264 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1265 << unsigned(ActiveCalls - Limit);
1266 }
1267 continue;
1268 }
1269
Richard Smith5179eb72016-06-28 19:03:57 +00001270 // Use a different note for an inheriting constructor, because from the
1271 // user's perspective it's not really a function at all.
1272 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1273 if (CD->isInheritingConstructor()) {
1274 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1275 << CD->getParent();
1276 continue;
1277 }
1278 }
1279
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001280 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001281 llvm::raw_svector_ostream Out(Buffer);
1282 describeCall(Frame, Out);
1283 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1284 }
1285}
1286
1287namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001288 struct ComplexValue {
1289 private:
1290 bool IsInt;
1291
1292 public:
1293 APSInt IntReal, IntImag;
1294 APFloat FloatReal, FloatImag;
1295
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001296 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001297
1298 void makeComplexFloat() { IsInt = false; }
1299 bool isComplexFloat() const { return !IsInt; }
1300 APFloat &getComplexFloatReal() { return FloatReal; }
1301 APFloat &getComplexFloatImag() { return FloatImag; }
1302
1303 void makeComplexInt() { IsInt = true; }
1304 bool isComplexInt() const { return IsInt; }
1305 APSInt &getComplexIntReal() { return IntReal; }
1306 APSInt &getComplexIntImag() { return IntImag; }
1307
Richard Smith2e312c82012-03-03 22:46:17 +00001308 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001309 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001310 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001311 else
Richard Smith2e312c82012-03-03 22:46:17 +00001312 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001313 }
Richard Smith2e312c82012-03-03 22:46:17 +00001314 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001315 assert(v.isComplexFloat() || v.isComplexInt());
1316 if (v.isComplexFloat()) {
1317 makeComplexFloat();
1318 FloatReal = v.getComplexFloatReal();
1319 FloatImag = v.getComplexFloatImag();
1320 } else {
1321 makeComplexInt();
1322 IntReal = v.getComplexIntReal();
1323 IntImag = v.getComplexIntImag();
1324 }
1325 }
John McCall93d91dc2010-05-07 17:22:02 +00001326 };
John McCall45d55e42010-05-07 21:00:08 +00001327
1328 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001329 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001330 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001331 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001332 bool IsNullPtr : 1;
1333 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001334
Richard Smithce40ad62011-11-12 22:28:03 +00001335 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001336 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001337 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001338 SubobjectDesignator &getLValueDesignator() { return Designator; }
1339 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001340 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001341
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001342 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1343 unsigned getLValueVersion() const { return Base.getVersion(); }
1344
Richard Smith2e312c82012-03-03 22:46:17 +00001345 void moveInto(APValue &V) const {
1346 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001347 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001348 else {
1349 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001350 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001351 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001352 }
John McCall45d55e42010-05-07 21:00:08 +00001353 }
Richard Smith2e312c82012-03-03 22:46:17 +00001354 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001355 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001356 Base = V.getLValueBase();
1357 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001358 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001359 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001360 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001361 }
1362
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001363 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001364#ifndef NDEBUG
1365 // We only allow a few types of invalid bases. Enforce that here.
1366 if (BInvalid) {
1367 const auto *E = B.get<const Expr *>();
1368 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1369 "Unexpected type of invalid base");
1370 }
1371#endif
1372
Richard Smithce40ad62011-11-12 22:28:03 +00001373 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001374 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001375 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001376 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001377 IsNullPtr = false;
1378 }
1379
1380 void setNull(QualType PointerTy, uint64_t TargetVal) {
1381 Base = (Expr *)nullptr;
1382 Offset = CharUnits::fromQuantity(TargetVal);
1383 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001384 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1385 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001386 }
1387
George Burgess IV3a03fab2015-09-04 21:28:13 +00001388 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001389 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001390 }
1391
Richard Smitha8105bc2012-01-06 16:39:00 +00001392 // Check that this LValue is not based on a null pointer. If it is, produce
1393 // a diagnostic and mark the designator as invalid.
1394 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1395 CheckSubobjectKind CSK) {
1396 if (Designator.Invalid)
1397 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001398 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001399 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001400 << CSK;
1401 Designator.setInvalid();
1402 return false;
1403 }
1404 return true;
1405 }
1406
1407 // Check this LValue refers to an object. If not, set the designator to be
1408 // invalid and emit a diagnostic.
1409 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001410 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001411 Designator.checkSubobject(Info, E, CSK);
1412 }
1413
1414 void addDecl(EvalInfo &Info, const Expr *E,
1415 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001416 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1417 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001418 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001419 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1420 if (!Designator.Entries.empty()) {
1421 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1422 Designator.setInvalid();
1423 return;
1424 }
Richard Smithefdb5032017-11-15 03:03:56 +00001425 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1426 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1427 Designator.FirstEntryIsAnUnsizedArray = true;
1428 Designator.addUnsizedArrayUnchecked(ElemTy);
1429 }
George Burgess IVe3763372016-12-22 02:50:20 +00001430 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001432 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1433 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001434 }
Richard Smith66c96992012-02-18 22:04:06 +00001435 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001436 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1437 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001438 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001439 void clearIsNullPointer() {
1440 IsNullPtr = false;
1441 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001442 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1443 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001444 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1445 // but we're not required to diagnose it and it's valid in C++.)
1446 if (!Index)
1447 return;
1448
1449 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1450 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1451 // offsets.
1452 uint64_t Offset64 = Offset.getQuantity();
1453 uint64_t ElemSize64 = ElementSize.getQuantity();
1454 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1455 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1456
1457 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001458 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001459 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001460 }
1461 void adjustOffset(CharUnits N) {
1462 Offset += N;
1463 if (N.getQuantity())
1464 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001465 }
John McCall45d55e42010-05-07 21:00:08 +00001466 };
Richard Smith027bf112011-11-17 22:56:20 +00001467
1468 struct MemberPtr {
1469 MemberPtr() {}
1470 explicit MemberPtr(const ValueDecl *Decl) :
1471 DeclAndIsDerivedMember(Decl, false), Path() {}
1472
1473 /// The member or (direct or indirect) field referred to by this member
1474 /// pointer, or 0 if this is a null member pointer.
1475 const ValueDecl *getDecl() const {
1476 return DeclAndIsDerivedMember.getPointer();
1477 }
1478 /// Is this actually a member of some type derived from the relevant class?
1479 bool isDerivedMember() const {
1480 return DeclAndIsDerivedMember.getInt();
1481 }
1482 /// Get the class which the declaration actually lives in.
1483 const CXXRecordDecl *getContainingRecord() const {
1484 return cast<CXXRecordDecl>(
1485 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1486 }
1487
Richard Smith2e312c82012-03-03 22:46:17 +00001488 void moveInto(APValue &V) const {
1489 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001490 }
Richard Smith2e312c82012-03-03 22:46:17 +00001491 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001492 assert(V.isMemberPointer());
1493 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1494 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1495 Path.clear();
1496 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1497 Path.insert(Path.end(), P.begin(), P.end());
1498 }
1499
1500 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1501 /// whether the member is a member of some class derived from the class type
1502 /// of the member pointer.
1503 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1504 /// Path - The path of base/derived classes from the member declaration's
1505 /// class (exclusive) to the class type of the member pointer (inclusive).
1506 SmallVector<const CXXRecordDecl*, 4> Path;
1507
1508 /// Perform a cast towards the class of the Decl (either up or down the
1509 /// hierarchy).
1510 bool castBack(const CXXRecordDecl *Class) {
1511 assert(!Path.empty());
1512 const CXXRecordDecl *Expected;
1513 if (Path.size() >= 2)
1514 Expected = Path[Path.size() - 2];
1515 else
1516 Expected = getContainingRecord();
1517 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1518 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1519 // if B does not contain the original member and is not a base or
1520 // derived class of the class containing the original member, the result
1521 // of the cast is undefined.
1522 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1523 // (D::*). We consider that to be a language defect.
1524 return false;
1525 }
1526 Path.pop_back();
1527 return true;
1528 }
1529 /// Perform a base-to-derived member pointer cast.
1530 bool castToDerived(const CXXRecordDecl *Derived) {
1531 if (!getDecl())
1532 return true;
1533 if (!isDerivedMember()) {
1534 Path.push_back(Derived);
1535 return true;
1536 }
1537 if (!castBack(Derived))
1538 return false;
1539 if (Path.empty())
1540 DeclAndIsDerivedMember.setInt(false);
1541 return true;
1542 }
1543 /// Perform a derived-to-base member pointer cast.
1544 bool castToBase(const CXXRecordDecl *Base) {
1545 if (!getDecl())
1546 return true;
1547 if (Path.empty())
1548 DeclAndIsDerivedMember.setInt(true);
1549 if (isDerivedMember()) {
1550 Path.push_back(Base);
1551 return true;
1552 }
1553 return castBack(Base);
1554 }
1555 };
Richard Smith357362d2011-12-13 06:39:58 +00001556
Richard Smith7bb00672012-02-01 01:42:44 +00001557 /// Compare two member pointers, which are assumed to be of the same type.
1558 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1559 if (!LHS.getDecl() || !RHS.getDecl())
1560 return !LHS.getDecl() && !RHS.getDecl();
1561 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1562 return false;
1563 return LHS.Path == RHS.Path;
1564 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001565}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001566
Richard Smith2e312c82012-03-03 22:46:17 +00001567static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001568static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1569 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001570 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001571static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1572 bool InvalidBaseOK = false);
1573static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1574 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001575static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1576 EvalInfo &Info);
1577static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001578static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001579static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001580 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001581static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001582static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001583static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1584 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001585static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001586
1587//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001588// Misc utilities
1589//===----------------------------------------------------------------------===//
1590
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001591/// A helper function to create a temporary and set an LValue.
1592template <class KeyTy>
1593static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1594 LValue &LV, CallStackFrame &Frame) {
1595 LV.set({Key, Frame.Info.CurrentCall->Index,
1596 Frame.Info.CurrentCall->getTempVersion()});
1597 return Frame.createTemporary(Key, IsLifetimeExtended);
1598}
1599
Richard Smithd6cc1982017-01-31 02:23:02 +00001600/// Negate an APSInt in place, converting it to a signed form if necessary, and
1601/// preserving its value (by extending by up to one bit as needed).
1602static void negateAsSigned(APSInt &Int) {
1603 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1604 Int = Int.extend(Int.getBitWidth() + 1);
1605 Int.setIsSigned(true);
1606 }
1607 Int = -Int;
1608}
1609
Richard Smith84401042013-06-03 05:03:02 +00001610/// Produce a string describing the given constexpr call.
1611static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1612 unsigned ArgIndex = 0;
1613 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1614 !isa<CXXConstructorDecl>(Frame->Callee) &&
1615 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1616
1617 if (!IsMemberCall)
1618 Out << *Frame->Callee << '(';
1619
1620 if (Frame->This && IsMemberCall) {
1621 APValue Val;
1622 Frame->This->moveInto(Val);
1623 Val.printPretty(Out, Frame->Info.Ctx,
1624 Frame->This->Designator.MostDerivedType);
1625 // FIXME: Add parens around Val if needed.
1626 Out << "->" << *Frame->Callee << '(';
1627 IsMemberCall = false;
1628 }
1629
1630 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1631 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1632 if (ArgIndex > (unsigned)IsMemberCall)
1633 Out << ", ";
1634
1635 const ParmVarDecl *Param = *I;
1636 const APValue &Arg = Frame->Arguments[ArgIndex];
1637 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1638
1639 if (ArgIndex == 0 && IsMemberCall)
1640 Out << "->" << *Frame->Callee << '(';
1641 }
1642
1643 Out << ')';
1644}
1645
Richard Smithd9f663b2013-04-22 15:31:51 +00001646/// Evaluate an expression to see if it had side-effects, and discard its
1647/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001648/// \return \c true if the caller should keep evaluating.
1649static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001650 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001651 if (!Evaluate(Scratch, Info, E))
1652 // We don't need the value, but we might have skipped a side effect here.
1653 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001654 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001655}
1656
Richard Smithd62306a2011-11-10 06:34:14 +00001657/// Should this call expression be treated as a string literal?
1658static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001659 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001660 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1661 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1662}
1663
Richard Smithce40ad62011-11-12 22:28:03 +00001664static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001665 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1666 // constant expression of pointer type that evaluates to...
1667
1668 // ... a null pointer value, or a prvalue core constant expression of type
1669 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001670 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001671
Richard Smithce40ad62011-11-12 22:28:03 +00001672 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1673 // ... the address of an object with static storage duration,
1674 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1675 return VD->hasGlobalStorage();
1676 // ... the address of a function,
1677 return isa<FunctionDecl>(D);
1678 }
1679
1680 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001681 switch (E->getStmtClass()) {
1682 default:
1683 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001684 case Expr::CompoundLiteralExprClass: {
1685 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1686 return CLE->isFileScope() && CLE->isLValue();
1687 }
Richard Smithe6c01442013-06-05 00:46:14 +00001688 case Expr::MaterializeTemporaryExprClass:
1689 // A materialized temporary might have been lifetime-extended to static
1690 // storage duration.
1691 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001692 // A string literal has static storage duration.
1693 case Expr::StringLiteralClass:
1694 case Expr::PredefinedExprClass:
1695 case Expr::ObjCStringLiteralClass:
1696 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001697 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001698 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001699 return true;
1700 case Expr::CallExprClass:
1701 return IsStringLiteralCall(cast<CallExpr>(E));
1702 // For GCC compatibility, &&label has static storage duration.
1703 case Expr::AddrLabelExprClass:
1704 return true;
1705 // A Block literal expression may be used as the initialization value for
1706 // Block variables at global or local static scope.
1707 case Expr::BlockExprClass:
1708 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001709 case Expr::ImplicitValueInitExprClass:
1710 // FIXME:
1711 // We can never form an lvalue with an implicit value initialization as its
1712 // base through expression evaluation, so these only appear in one case: the
1713 // implicit variable declaration we invent when checking whether a constexpr
1714 // constructor can produce a constant expression. We must assume that such
1715 // an expression might be a global lvalue.
1716 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001717 }
John McCall95007602010-05-10 23:27:23 +00001718}
1719
Richard Smith06f71b52018-08-04 00:57:17 +00001720static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1721 return LVal.Base.dyn_cast<const ValueDecl*>();
1722}
1723
1724static bool IsLiteralLValue(const LValue &Value) {
1725 if (Value.getLValueCallIndex())
1726 return false;
1727 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1728 return E && !isa<MaterializeTemporaryExpr>(E);
1729}
1730
1731static bool IsWeakLValue(const LValue &Value) {
1732 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1733 return Decl && Decl->isWeak();
1734}
1735
1736static bool isZeroSized(const LValue &Value) {
1737 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1738 if (Decl && isa<VarDecl>(Decl)) {
1739 QualType Ty = Decl->getType();
1740 if (Ty->isArrayType())
1741 return Ty->isIncompleteType() ||
1742 Decl->getASTContext().getTypeSize(Ty) == 0;
1743 }
1744 return false;
1745}
1746
1747static bool HasSameBase(const LValue &A, const LValue &B) {
1748 if (!A.getLValueBase())
1749 return !B.getLValueBase();
1750 if (!B.getLValueBase())
1751 return false;
1752
1753 if (A.getLValueBase().getOpaqueValue() !=
1754 B.getLValueBase().getOpaqueValue()) {
1755 const Decl *ADecl = GetLValueBaseDecl(A);
1756 if (!ADecl)
1757 return false;
1758 const Decl *BDecl = GetLValueBaseDecl(B);
1759 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1760 return false;
1761 }
1762
1763 return IsGlobalLValue(A.getLValueBase()) ||
1764 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1765 A.getLValueVersion() == B.getLValueVersion());
1766}
1767
Richard Smithb228a862012-02-15 02:18:13 +00001768static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1769 assert(Base && "no location for a null lvalue");
1770 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1771 if (VD)
1772 Info.Note(VD->getLocation(), diag::note_declared_at);
1773 else
Ted Kremenek28831752012-08-23 20:46:57 +00001774 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001775 diag::note_constexpr_temporary_here);
1776}
1777
Richard Smith80815602011-11-07 05:07:52 +00001778/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001779/// value for an address or reference constant expression. Return true if we
1780/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001781static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001782 QualType Type, const LValue &LVal,
1783 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001784 bool IsReferenceType = Type->isReferenceType();
1785
Richard Smith357362d2011-12-13 06:39:58 +00001786 APValue::LValueBase Base = LVal.getLValueBase();
1787 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1788
Richard Smith0dea49e2012-02-18 04:58:18 +00001789 // Check that the object is a global. Note that the fake 'this' object we
1790 // manufacture when checking potential constant expressions is conservatively
1791 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001792 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001793 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001794 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001795 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001796 << IsReferenceType << !Designator.Entries.empty()
1797 << !!VD << VD;
1798 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001799 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001800 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001801 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001802 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001803 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001804 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001805 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001806 LVal.getLValueCallIndex() == 0) &&
1807 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001808
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001809 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1810 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001811 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001812 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001813 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001814
Hans Wennborg82dd8772014-06-25 22:19:48 +00001815 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001816 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001817 return false;
1818 }
1819 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1820 // __declspec(dllimport) must be handled very carefully:
1821 // We must never initialize an expression with the thunk in C++.
1822 // Doing otherwise would allow the same id-expression to yield
1823 // different addresses for the same function in different translation
1824 // units. However, this means that we must dynamically initialize the
1825 // expression with the contents of the import address table at runtime.
1826 //
1827 // The C language has no notion of ODR; furthermore, it has no notion of
1828 // dynamic initialization. This means that we are permitted to
1829 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001830 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1831 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001832 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001833 }
1834 }
1835
Richard Smitha8105bc2012-01-06 16:39:00 +00001836 // Allow address constant expressions to be past-the-end pointers. This is
1837 // an extension: the standard requires them to point to an object.
1838 if (!IsReferenceType)
1839 return true;
1840
1841 // A reference constant expression must refer to an object.
1842 if (!Base) {
1843 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001844 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001845 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001846 }
1847
Richard Smith357362d2011-12-13 06:39:58 +00001848 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001849 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001850 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001851 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001852 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001853 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001854 }
1855
Richard Smith80815602011-11-07 05:07:52 +00001856 return true;
1857}
1858
Reid Klecknercd016d82017-07-07 22:04:29 +00001859/// Member pointers are constant expressions unless they point to a
1860/// non-virtual dllimport member function.
1861static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1862 SourceLocation Loc,
1863 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001864 const APValue &Value,
1865 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001866 const ValueDecl *Member = Value.getMemberPointerDecl();
1867 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1868 if (!FD)
1869 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001870 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1871 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001872}
1873
Richard Smithfddd3842011-12-30 21:15:51 +00001874/// Check that this core constant expression is of literal type, and if not,
1875/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001876static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001877 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001878 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001879 return true;
1880
Richard Smith7525ff62013-05-09 07:14:00 +00001881 // C++1y: A constant initializer for an object o [...] may also invoke
1882 // constexpr constructors for o and its subobjects even if those objects
1883 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001884 //
1885 // C++11 missed this detail for aggregates, so classes like this:
1886 // struct foo_t { union { int i; volatile int j; } u; };
1887 // are not (obviously) initializable like so:
1888 // __attribute__((__require_constant_initialization__))
1889 // static const foo_t x = {{0}};
1890 // because "i" is a subobject with non-literal initialization (due to the
1891 // volatile member of the union). See:
1892 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1893 // Therefore, we use the C++1y behavior.
1894 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001895 return true;
1896
Richard Smithfddd3842011-12-30 21:15:51 +00001897 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001898 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001899 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001900 << E->getType();
1901 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001902 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001903 return false;
1904}
1905
Richard Smith0b0a0b62011-10-29 20:57:55 +00001906/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001907/// constant expression. If not, report an appropriate diagnostic. Does not
1908/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001909static bool
1910CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1911 const APValue &Value,
1912 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001913 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001914 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001915 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001916 return false;
1917 }
1918
Richard Smith77be48a2014-07-31 06:31:19 +00001919 // We allow _Atomic(T) to be initialized from anything that T can be
1920 // initialized from.
1921 if (const AtomicType *AT = Type->getAs<AtomicType>())
1922 Type = AT->getValueType();
1923
Richard Smithb228a862012-02-15 02:18:13 +00001924 // Core issue 1454: For a literal constant expression of array or class type,
1925 // each subobject of its value shall have been initialized by a constant
1926 // expression.
1927 if (Value.isArray()) {
1928 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1929 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1930 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001931 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001932 return false;
1933 }
1934 if (!Value.hasArrayFiller())
1935 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001936 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1937 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001938 }
Richard Smithb228a862012-02-15 02:18:13 +00001939 if (Value.isUnion() && Value.getUnionField()) {
1940 return CheckConstantExpression(Info, DiagLoc,
1941 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001942 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001943 }
1944 if (Value.isStruct()) {
1945 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1946 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1947 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001948 for (const CXXBaseSpecifier &BS : CD->bases()) {
1949 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1950 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001951 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001952 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001953 }
1954 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001955 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001956 if (I->isUnnamedBitfield())
1957 continue;
1958
David Blaikie2d7c57e2012-04-30 02:36:29 +00001959 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001960 Value.getStructField(I->getFieldIndex()),
1961 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001962 return false;
1963 }
1964 }
1965
1966 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001967 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001968 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001969 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001970 }
1971
Reid Klecknercd016d82017-07-07 22:04:29 +00001972 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00001973 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001974
Richard Smithb228a862012-02-15 02:18:13 +00001975 // Everything else is fine.
1976 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001977}
1978
Richard Smith2e312c82012-03-03 22:46:17 +00001979static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001980 // A null base expression indicates a null pointer. These are always
1981 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001982 if (!Value.getLValueBase()) {
1983 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001984 return true;
1985 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001986
Richard Smith027bf112011-11-17 22:56:20 +00001987 // We have a non-null base. These are generally known to be true, but if it's
1988 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001989 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001990 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001991 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001992}
1993
Richard Smith2e312c82012-03-03 22:46:17 +00001994static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001995 switch (Val.getKind()) {
1996 case APValue::Uninitialized:
1997 return false;
1998 case APValue::Int:
1999 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002000 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002001 case APValue::Float:
2002 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002003 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002004 case APValue::ComplexInt:
2005 Result = Val.getComplexIntReal().getBoolValue() ||
2006 Val.getComplexIntImag().getBoolValue();
2007 return true;
2008 case APValue::ComplexFloat:
2009 Result = !Val.getComplexFloatReal().isZero() ||
2010 !Val.getComplexFloatImag().isZero();
2011 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002012 case APValue::LValue:
2013 return EvalPointerValueAsBool(Val, Result);
2014 case APValue::MemberPointer:
2015 Result = Val.getMemberPointerDecl();
2016 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002017 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002018 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002019 case APValue::Struct:
2020 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002021 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002022 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002023 }
2024
Richard Smith11562c52011-10-28 17:51:58 +00002025 llvm_unreachable("unknown APValue kind");
2026}
2027
2028static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2029 EvalInfo &Info) {
2030 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002031 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002032 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002033 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002034 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002035}
2036
Richard Smith357362d2011-12-13 06:39:58 +00002037template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002038static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002039 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002040 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002041 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002042 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002043}
2044
2045static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2046 QualType SrcType, const APFloat &Value,
2047 QualType DestType, APSInt &Result) {
2048 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002049 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002050 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002051
Richard Smith357362d2011-12-13 06:39:58 +00002052 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002053 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002054 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2055 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002056 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002057 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002058}
2059
Richard Smith357362d2011-12-13 06:39:58 +00002060static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2061 QualType SrcType, QualType DestType,
2062 APFloat &Result) {
2063 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002064 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002065 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2066 APFloat::rmNearestTiesToEven, &ignored)
2067 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002068 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002069 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002070}
2071
Richard Smith911e1422012-01-30 22:27:01 +00002072static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2073 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002074 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002075 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002076 APSInt Result = Value;
2077 // Figure out if this is a truncate, extend or noop cast.
2078 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00002079 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002080 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002081 return Result;
2082}
2083
Richard Smith357362d2011-12-13 06:39:58 +00002084static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2085 QualType SrcType, const APSInt &Value,
2086 QualType DestType, APFloat &Result) {
2087 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2088 if (Result.convertFromAPInt(Value, Value.isSigned(),
2089 APFloat::rmNearestTiesToEven)
2090 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002091 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002092 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002093}
2094
Richard Smith49ca8aa2013-08-06 07:09:20 +00002095static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2096 APValue &Value, const FieldDecl *FD) {
2097 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2098
2099 if (!Value.isInt()) {
2100 // Trying to store a pointer-cast-to-integer into a bitfield.
2101 // FIXME: In this case, we should provide the diagnostic for casting
2102 // a pointer to an integer.
2103 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002104 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002105 return false;
2106 }
2107
2108 APSInt &Int = Value.getInt();
2109 unsigned OldBitWidth = Int.getBitWidth();
2110 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2111 if (NewBitWidth < OldBitWidth)
2112 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2113 return true;
2114}
2115
Eli Friedman803acb32011-12-22 03:51:45 +00002116static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2117 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002118 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002119 if (!Evaluate(SVal, Info, E))
2120 return false;
2121 if (SVal.isInt()) {
2122 Res = SVal.getInt();
2123 return true;
2124 }
2125 if (SVal.isFloat()) {
2126 Res = SVal.getFloat().bitcastToAPInt();
2127 return true;
2128 }
2129 if (SVal.isVector()) {
2130 QualType VecTy = E->getType();
2131 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2132 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2133 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2134 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2135 Res = llvm::APInt::getNullValue(VecSize);
2136 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2137 APValue &Elt = SVal.getVectorElt(i);
2138 llvm::APInt EltAsInt;
2139 if (Elt.isInt()) {
2140 EltAsInt = Elt.getInt();
2141 } else if (Elt.isFloat()) {
2142 EltAsInt = Elt.getFloat().bitcastToAPInt();
2143 } else {
2144 // Don't try to handle vectors of anything other than int or float
2145 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002146 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002147 return false;
2148 }
2149 unsigned BaseEltSize = EltAsInt.getBitWidth();
2150 if (BigEndian)
2151 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2152 else
2153 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2154 }
2155 return true;
2156 }
2157 // Give up if the input isn't an int, float, or vector. For example, we
2158 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002159 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002160 return false;
2161}
2162
Richard Smith43e77732013-05-07 04:50:00 +00002163/// Perform the given integer operation, which is known to need at most BitWidth
2164/// bits, and check for overflow in the original type (if that type was not an
2165/// unsigned type).
2166template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002167static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2168 const APSInt &LHS, const APSInt &RHS,
2169 unsigned BitWidth, Operation Op,
2170 APSInt &Result) {
2171 if (LHS.isUnsigned()) {
2172 Result = Op(LHS, RHS);
2173 return true;
2174 }
Richard Smith43e77732013-05-07 04:50:00 +00002175
2176 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002177 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002178 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002179 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002180 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002181 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002182 << Result.toString(10) << E->getType();
2183 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002184 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002185 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002186 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002187}
2188
2189/// Perform the given binary integer operation.
2190static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2191 BinaryOperatorKind Opcode, APSInt RHS,
2192 APSInt &Result) {
2193 switch (Opcode) {
2194 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002195 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002196 return false;
2197 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002198 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2199 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002200 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002201 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2202 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002203 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002204 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2205 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002206 case BO_And: Result = LHS & RHS; return true;
2207 case BO_Xor: Result = LHS ^ RHS; return true;
2208 case BO_Or: Result = LHS | RHS; return true;
2209 case BO_Div:
2210 case BO_Rem:
2211 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002212 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002213 return false;
2214 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002215 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2216 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2217 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002218 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2219 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002220 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2221 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002222 return true;
2223 case BO_Shl: {
2224 if (Info.getLangOpts().OpenCL)
2225 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2226 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2227 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2228 RHS.isUnsigned());
2229 else if (RHS.isSigned() && RHS.isNegative()) {
2230 // During constant-folding, a negative shift is an opposite shift. Such
2231 // a shift is not a constant expression.
2232 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2233 RHS = -RHS;
2234 goto shift_right;
2235 }
2236 shift_left:
2237 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2238 // the shifted type.
2239 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2240 if (SA != RHS) {
2241 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2242 << RHS << E->getType() << LHS.getBitWidth();
2243 } else if (LHS.isSigned()) {
2244 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2245 // operand, and must not overflow the corresponding unsigned type.
2246 if (LHS.isNegative())
2247 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2248 else if (LHS.countLeadingZeros() < SA)
2249 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2250 }
2251 Result = LHS << SA;
2252 return true;
2253 }
2254 case BO_Shr: {
2255 if (Info.getLangOpts().OpenCL)
2256 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2257 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2258 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2259 RHS.isUnsigned());
2260 else if (RHS.isSigned() && RHS.isNegative()) {
2261 // During constant-folding, a negative shift is an opposite shift. Such a
2262 // shift is not a constant expression.
2263 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2264 RHS = -RHS;
2265 goto shift_left;
2266 }
2267 shift_right:
2268 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2269 // shifted type.
2270 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2271 if (SA != RHS)
2272 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2273 << RHS << E->getType() << LHS.getBitWidth();
2274 Result = LHS >> SA;
2275 return true;
2276 }
2277
2278 case BO_LT: Result = LHS < RHS; return true;
2279 case BO_GT: Result = LHS > RHS; return true;
2280 case BO_LE: Result = LHS <= RHS; return true;
2281 case BO_GE: Result = LHS >= RHS; return true;
2282 case BO_EQ: Result = LHS == RHS; return true;
2283 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002284 case BO_Cmp:
2285 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002286 }
2287}
2288
Richard Smith861b5b52013-05-07 23:34:45 +00002289/// Perform the given binary floating-point operation, in-place, on LHS.
2290static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2291 APFloat &LHS, BinaryOperatorKind Opcode,
2292 const APFloat &RHS) {
2293 switch (Opcode) {
2294 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002295 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002296 return false;
2297 case BO_Mul:
2298 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2299 break;
2300 case BO_Add:
2301 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2302 break;
2303 case BO_Sub:
2304 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2305 break;
2306 case BO_Div:
2307 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2308 break;
2309 }
2310
Richard Smith0c6124b2015-12-03 01:36:22 +00002311 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002312 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002313 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002314 }
Richard Smith861b5b52013-05-07 23:34:45 +00002315 return true;
2316}
2317
Richard Smitha8105bc2012-01-06 16:39:00 +00002318/// Cast an lvalue referring to a base subobject to a derived class, by
2319/// truncating the lvalue's path to the given length.
2320static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2321 const RecordDecl *TruncatedType,
2322 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002323 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002324
2325 // Check we actually point to a derived class object.
2326 if (TruncatedElements == D.Entries.size())
2327 return true;
2328 assert(TruncatedElements >= D.MostDerivedPathLength &&
2329 "not casting to a derived class");
2330 if (!Result.checkSubobject(Info, E, CSK_Derived))
2331 return false;
2332
2333 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002334 const RecordDecl *RD = TruncatedType;
2335 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002336 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002337 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2338 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002339 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002340 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002341 else
Richard Smithd62306a2011-11-10 06:34:14 +00002342 Result.Offset -= Layout.getBaseClassOffset(Base);
2343 RD = Base;
2344 }
Richard Smith027bf112011-11-17 22:56:20 +00002345 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002346 return true;
2347}
2348
John McCalld7bca762012-05-01 00:38:49 +00002349static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002350 const CXXRecordDecl *Derived,
2351 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002352 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002353 if (!RL) {
2354 if (Derived->isInvalidDecl()) return false;
2355 RL = &Info.Ctx.getASTRecordLayout(Derived);
2356 }
2357
Richard Smithd62306a2011-11-10 06:34:14 +00002358 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002359 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002360 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002361}
2362
Richard Smitha8105bc2012-01-06 16:39:00 +00002363static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002364 const CXXRecordDecl *DerivedDecl,
2365 const CXXBaseSpecifier *Base) {
2366 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2367
John McCalld7bca762012-05-01 00:38:49 +00002368 if (!Base->isVirtual())
2369 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002370
Richard Smitha8105bc2012-01-06 16:39:00 +00002371 SubobjectDesignator &D = Obj.Designator;
2372 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002373 return false;
2374
Richard Smitha8105bc2012-01-06 16:39:00 +00002375 // Extract most-derived object and corresponding type.
2376 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2377 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2378 return false;
2379
2380 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002381 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002382 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2383 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002384 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002385 return true;
2386}
2387
Richard Smith84401042013-06-03 05:03:02 +00002388static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2389 QualType Type, LValue &Result) {
2390 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2391 PathE = E->path_end();
2392 PathI != PathE; ++PathI) {
2393 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2394 *PathI))
2395 return false;
2396 Type = (*PathI)->getType();
2397 }
2398 return true;
2399}
2400
Richard Smithd62306a2011-11-10 06:34:14 +00002401/// Update LVal to refer to the given field, which must be a member of the type
2402/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002403static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002404 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002405 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002406 if (!RL) {
2407 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002408 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002409 }
Richard Smithd62306a2011-11-10 06:34:14 +00002410
2411 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002412 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002413 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002414 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002415}
2416
Richard Smith1b78b3d2012-01-25 22:15:11 +00002417/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002418static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002419 LValue &LVal,
2420 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002421 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002422 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002423 return false;
2424 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002425}
2426
Richard Smithd62306a2011-11-10 06:34:14 +00002427/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002428static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2429 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002430 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2431 // extension.
2432 if (Type->isVoidType() || Type->isFunctionType()) {
2433 Size = CharUnits::One();
2434 return true;
2435 }
2436
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002437 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002438 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002439 return false;
2440 }
2441
Richard Smithd62306a2011-11-10 06:34:14 +00002442 if (!Type->isConstantSizeType()) {
2443 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002444 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002445 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002446 return false;
2447 }
2448
2449 Size = Info.Ctx.getTypeSizeInChars(Type);
2450 return true;
2451}
2452
2453/// Update a pointer value to model pointer arithmetic.
2454/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002455/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002456/// \param LVal - The pointer value to be updated.
2457/// \param EltTy - The pointee type represented by LVal.
2458/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002459static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2460 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002461 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002462 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002463 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002464 return false;
2465
Yaxun Liu402804b2016-12-15 08:09:08 +00002466 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002467 return true;
2468}
2469
Richard Smithd6cc1982017-01-31 02:23:02 +00002470static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2471 LValue &LVal, QualType EltTy,
2472 int64_t Adjustment) {
2473 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2474 APSInt::get(Adjustment));
2475}
2476
Richard Smith66c96992012-02-18 22:04:06 +00002477/// Update an lvalue to refer to a component of a complex number.
2478/// \param Info - Information about the ongoing evaluation.
2479/// \param LVal - The lvalue to be updated.
2480/// \param EltTy - The complex number's component type.
2481/// \param Imag - False for the real component, true for the imaginary.
2482static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2483 LValue &LVal, QualType EltTy,
2484 bool Imag) {
2485 if (Imag) {
2486 CharUnits SizeOfComponent;
2487 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2488 return false;
2489 LVal.Offset += SizeOfComponent;
2490 }
2491 LVal.addComplex(Info, E, EltTy, Imag);
2492 return true;
2493}
2494
Faisal Vali051e3a22017-02-16 04:12:21 +00002495static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2496 QualType Type, const LValue &LVal,
2497 APValue &RVal);
2498
Richard Smith27908702011-10-24 17:54:18 +00002499/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002500///
2501/// \param Info Information about the ongoing evaluation.
2502/// \param E An expression to be used when printing diagnostics.
2503/// \param VD The variable whose initializer should be obtained.
2504/// \param Frame The frame in which the variable was created. Must be null
2505/// if this variable is not local to the evaluation.
2506/// \param Result Filled in with a pointer to the value of the variable.
2507static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2508 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002509 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002510
Richard Smith254a73d2011-10-28 22:34:42 +00002511 // If this is a parameter to an active constexpr function call, perform
2512 // argument substitution.
2513 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002514 // Assume arguments of a potential constant expression are unknown
2515 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002516 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002517 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002518 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002519 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002520 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002521 }
Richard Smith3229b742013-05-05 21:17:10 +00002522 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002523 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002524 }
Richard Smith27908702011-10-24 17:54:18 +00002525
Richard Smithd9f663b2013-04-22 15:31:51 +00002526 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002527 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002528 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2529 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002530 if (!Result) {
2531 // Assume variables referenced within a lambda's call operator that were
2532 // not declared within the call operator are captures and during checking
2533 // of a potential constant expression, assume they are unknown constant
2534 // expressions.
2535 assert(isLambdaCallOperator(Frame->Callee) &&
2536 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2537 "missing value for local variable");
2538 if (Info.checkingPotentialConstantExpression())
2539 return false;
2540 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002541 Info.FFDiag(E->getBeginLoc(),
2542 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002543 << "captures not currently allowed";
2544 return false;
2545 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002546 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002547 }
2548
Richard Smithd0b4dd62011-12-19 06:19:21 +00002549 // Dig out the initializer, and use the declaration which it's attached to.
2550 const Expr *Init = VD->getAnyInitializer(VD);
2551 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002552 // If we're checking a potential constant expression, the variable could be
2553 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002554 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002555 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002556 return false;
2557 }
2558
Richard Smithd62306a2011-11-10 06:34:14 +00002559 // If we're currently evaluating the initializer of this declaration, use that
2560 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002561 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002562 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002563 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002564 }
2565
Richard Smithcecf1842011-11-01 21:06:14 +00002566 // Never evaluate the initializer of a weak variable. We can't be sure that
2567 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002568 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002569 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002570 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002571 }
Richard Smithcecf1842011-11-01 21:06:14 +00002572
Richard Smithd0b4dd62011-12-19 06:19:21 +00002573 // Check that we can fold the initializer. In C++, we will have already done
2574 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002575 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002576 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002577 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002578 Notes.size() + 1) << VD;
2579 Info.Note(VD->getLocation(), diag::note_declared_at);
2580 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002581 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002582 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002583 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002584 Notes.size() + 1) << VD;
2585 Info.Note(VD->getLocation(), diag::note_declared_at);
2586 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002587 }
Richard Smith27908702011-10-24 17:54:18 +00002588
Richard Smith3229b742013-05-05 21:17:10 +00002589 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002590 return true;
Richard Smith27908702011-10-24 17:54:18 +00002591}
2592
Richard Smith11562c52011-10-28 17:51:58 +00002593static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002594 Qualifiers Quals = T.getQualifiers();
2595 return Quals.hasConst() && !Quals.hasVolatile();
2596}
2597
Richard Smithe97cbd72011-11-11 04:05:33 +00002598/// Get the base index of the given base class within an APValue representing
2599/// the given derived class.
2600static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2601 const CXXRecordDecl *Base) {
2602 Base = Base->getCanonicalDecl();
2603 unsigned Index = 0;
2604 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2605 E = Derived->bases_end(); I != E; ++I, ++Index) {
2606 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2607 return Index;
2608 }
2609
2610 llvm_unreachable("base class missing from derived class's bases list");
2611}
2612
Richard Smith3da88fa2013-04-26 14:36:30 +00002613/// Extract the value of a character from a string literal.
2614static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2615 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002616 // FIXME: Support MakeStringConstant
2617 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2618 std::string Str;
2619 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2620 assert(Index <= Str.size() && "Index too large");
2621 return APSInt::getUnsigned(Str.c_str()[Index]);
2622 }
2623
Alexey Bataevec474782014-10-09 08:45:04 +00002624 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2625 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 const StringLiteral *S = cast<StringLiteral>(Lit);
2627 const ConstantArrayType *CAT =
2628 Info.Ctx.getAsConstantArrayType(S->getType());
2629 assert(CAT && "string literal isn't an array");
2630 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002631 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002632
2633 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002634 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002635 if (Index < S->getLength())
2636 Value = S->getCodeUnit(Index);
2637 return Value;
2638}
2639
Richard Smith3da88fa2013-04-26 14:36:30 +00002640// Expand a string literal into an array of characters.
2641static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2642 APValue &Result) {
2643 const StringLiteral *S = cast<StringLiteral>(Lit);
2644 const ConstantArrayType *CAT =
2645 Info.Ctx.getAsConstantArrayType(S->getType());
2646 assert(CAT && "string literal isn't an array");
2647 QualType CharType = CAT->getElementType();
2648 assert(CharType->isIntegerType() && "unexpected character type");
2649
2650 unsigned Elts = CAT->getSize().getZExtValue();
2651 Result = APValue(APValue::UninitArray(),
2652 std::min(S->getLength(), Elts), Elts);
2653 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2654 CharType->isUnsignedIntegerType());
2655 if (Result.hasArrayFiller())
2656 Result.getArrayFiller() = APValue(Value);
2657 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2658 Value = S->getCodeUnit(I);
2659 Result.getArrayInitializedElt(I) = APValue(Value);
2660 }
2661}
2662
2663// Expand an array so that it has more than Index filled elements.
2664static void expandArray(APValue &Array, unsigned Index) {
2665 unsigned Size = Array.getArraySize();
2666 assert(Index < Size);
2667
2668 // Always at least double the number of elements for which we store a value.
2669 unsigned OldElts = Array.getArrayInitializedElts();
2670 unsigned NewElts = std::max(Index+1, OldElts * 2);
2671 NewElts = std::min(Size, std::max(NewElts, 8u));
2672
2673 // Copy the data across.
2674 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2675 for (unsigned I = 0; I != OldElts; ++I)
2676 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2677 for (unsigned I = OldElts; I != NewElts; ++I)
2678 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2679 if (NewValue.hasArrayFiller())
2680 NewValue.getArrayFiller() = Array.getArrayFiller();
2681 Array.swap(NewValue);
2682}
2683
Richard Smithb01fe402014-09-16 01:24:02 +00002684/// Determine whether a type would actually be read by an lvalue-to-rvalue
2685/// conversion. If it's of class type, we may assume that the copy operation
2686/// is trivial. Note that this is never true for a union type with fields
2687/// (because the copy always "reads" the active member) and always true for
2688/// a non-class type.
2689static bool isReadByLvalueToRvalueConversion(QualType T) {
2690 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2691 if (!RD || (RD->isUnion() && !RD->field_empty()))
2692 return true;
2693 if (RD->isEmpty())
2694 return false;
2695
2696 for (auto *Field : RD->fields())
2697 if (isReadByLvalueToRvalueConversion(Field->getType()))
2698 return true;
2699
2700 for (auto &BaseSpec : RD->bases())
2701 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2702 return true;
2703
2704 return false;
2705}
2706
2707/// Diagnose an attempt to read from any unreadable field within the specified
2708/// type, which might be a class type.
2709static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2710 QualType T) {
2711 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2712 if (!RD)
2713 return false;
2714
2715 if (!RD->hasMutableFields())
2716 return false;
2717
2718 for (auto *Field : RD->fields()) {
2719 // If we're actually going to read this field in some way, then it can't
2720 // be mutable. If we're in a union, then assigning to a mutable field
2721 // (even an empty one) can change the active member, so that's not OK.
2722 // FIXME: Add core issue number for the union case.
2723 if (Field->isMutable() &&
2724 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002725 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002726 Info.Note(Field->getLocation(), diag::note_declared_at);
2727 return true;
2728 }
2729
2730 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2731 return true;
2732 }
2733
2734 for (auto &BaseSpec : RD->bases())
2735 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2736 return true;
2737
2738 // All mutable fields were empty, and thus not actually read.
2739 return false;
2740}
2741
Richard Smith861b5b52013-05-07 23:34:45 +00002742/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002743enum AccessKinds {
2744 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002745 AK_Assign,
2746 AK_Increment,
2747 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002748};
2749
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002750namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002751/// A handle to a complete object (an object that is not a subobject of
2752/// another object).
2753struct CompleteObject {
2754 /// The value of the complete object.
2755 APValue *Value;
2756 /// The type of the complete object.
2757 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002758 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002759
Craig Topper36250ad2014-05-12 05:36:57 +00002760 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002761 CompleteObject(APValue *Value, QualType Type,
2762 bool LifetimeStartedInEvaluation)
2763 : Value(Value), Type(Type),
2764 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002765 assert(Value && "missing value for complete object");
2766 }
2767
Aaron Ballman67347662015-02-15 22:00:28 +00002768 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002769};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002770} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002771
Richard Smith3da88fa2013-04-26 14:36:30 +00002772/// Find the designated sub-object of an rvalue.
2773template<typename SubobjectHandler>
2774typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002775findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002776 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002777 if (Sub.Invalid)
2778 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002779 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002780 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002781 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002782 Info.FFDiag(E, Sub.isOnePastTheEnd()
2783 ? diag::note_constexpr_access_past_end
2784 : diag::note_constexpr_access_unsized_array)
2785 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002786 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002787 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002788 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002789 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002790
Richard Smith3229b742013-05-05 21:17:10 +00002791 APValue *O = Obj.Value;
2792 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002793 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002794 const bool MayReadMutableMembers =
2795 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002796
Richard Smithd62306a2011-11-10 06:34:14 +00002797 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002798 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2799 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002800 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002801 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002802 return handler.failed();
2803 }
2804
Richard Smith49ca8aa2013-08-06 07:09:20 +00002805 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002806 // If we are reading an object of class type, there may still be more
2807 // things we need to check: if there are any mutable subobjects, we
2808 // cannot perform this read. (This only happens when performing a trivial
2809 // copy or assignment.)
2810 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002811 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002812 return handler.failed();
2813
Richard Smith49ca8aa2013-08-06 07:09:20 +00002814 if (!handler.found(*O, ObjType))
2815 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002816
Richard Smith49ca8aa2013-08-06 07:09:20 +00002817 // If we modified a bit-field, truncate it to the right width.
2818 if (handler.AccessKind != AK_Read &&
2819 LastField && LastField->isBitField() &&
2820 !truncateBitfieldValue(Info, E, *O, LastField))
2821 return false;
2822
2823 return true;
2824 }
2825
Craig Topper36250ad2014-05-12 05:36:57 +00002826 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002827 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002828 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002829 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002830 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002831 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002832 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002833 // Note, it should not be possible to form a pointer with a valid
2834 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002835 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002836 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002837 << handler.AccessKind;
2838 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002839 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002840 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002841 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002842
2843 ObjType = CAT->getElementType();
2844
Richard Smith14a94132012-02-17 03:35:37 +00002845 // An array object is represented as either an Array APValue or as an
2846 // LValue which refers to a string literal.
2847 if (O->isLValue()) {
2848 assert(I == N - 1 && "extracting subobject of character?");
2849 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002850 if (handler.AccessKind != AK_Read)
2851 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2852 *O);
2853 else
2854 return handler.foundString(*O, ObjType, Index);
2855 }
2856
2857 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002858 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002859 else if (handler.AccessKind != AK_Read) {
2860 expandArray(*O, Index);
2861 O = &O->getArrayInitializedElt(Index);
2862 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002863 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002864 } else if (ObjType->isAnyComplexType()) {
2865 // Next subobject is a complex number.
2866 uint64_t Index = Sub.Entries[I].ArrayIndex;
2867 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002868 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002869 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002870 << handler.AccessKind;
2871 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002872 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002873 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002874 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002875
2876 bool WasConstQualified = ObjType.isConstQualified();
2877 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2878 if (WasConstQualified)
2879 ObjType.addConst();
2880
Richard Smith66c96992012-02-18 22:04:06 +00002881 assert(I == N - 1 && "extracting subobject of scalar?");
2882 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002883 return handler.found(Index ? O->getComplexIntImag()
2884 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002885 } else {
2886 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002887 return handler.found(Index ? O->getComplexFloatImag()
2888 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002889 }
Richard Smithd62306a2011-11-10 06:34:14 +00002890 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002891 // In C++14 onwards, it is permitted to read a mutable member whose
2892 // lifetime began within the evaluation.
2893 // FIXME: Should we also allow this in C++11?
2894 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2895 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002896 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002897 << Field;
2898 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002899 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002900 }
2901
Richard Smithd62306a2011-11-10 06:34:14 +00002902 // Next subobject is a class, struct or union field.
2903 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2904 if (RD->isUnion()) {
2905 const FieldDecl *UnionField = O->getUnionField();
2906 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002907 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002908 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002909 << handler.AccessKind << Field << !UnionField << UnionField;
2910 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002911 }
Richard Smithd62306a2011-11-10 06:34:14 +00002912 O = &O->getUnionValue();
2913 } else
2914 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002915
2916 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002917 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002918 if (WasConstQualified && !Field->isMutable())
2919 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002920
2921 if (ObjType.isVolatileQualified()) {
2922 if (Info.getLangOpts().CPlusPlus) {
2923 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002924 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002925 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002926 Info.Note(Field->getLocation(), diag::note_declared_at);
2927 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002928 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002929 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002930 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002931 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002932
2933 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002934 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002935 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002936 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2937 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2938 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002939
2940 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002941 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002942 if (WasConstQualified)
2943 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002944 }
2945 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002946}
2947
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002948namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002949struct ExtractSubobjectHandler {
2950 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002951 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002952
2953 static const AccessKinds AccessKind = AK_Read;
2954
2955 typedef bool result_type;
2956 bool failed() { return false; }
2957 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002958 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002959 return true;
2960 }
2961 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002962 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002963 return true;
2964 }
2965 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002966 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002967 return true;
2968 }
2969 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002970 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2972 return true;
2973 }
2974};
Richard Smith3229b742013-05-05 21:17:10 +00002975} // end anonymous namespace
2976
Richard Smith3da88fa2013-04-26 14:36:30 +00002977const AccessKinds ExtractSubobjectHandler::AccessKind;
2978
2979/// Extract the designated sub-object of an rvalue.
2980static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002981 const CompleteObject &Obj,
2982 const SubobjectDesignator &Sub,
2983 APValue &Result) {
2984 ExtractSubobjectHandler Handler = { Info, Result };
2985 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002986}
2987
Richard Smith3229b742013-05-05 21:17:10 +00002988namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002989struct ModifySubobjectHandler {
2990 EvalInfo &Info;
2991 APValue &NewVal;
2992 const Expr *E;
2993
2994 typedef bool result_type;
2995 static const AccessKinds AccessKind = AK_Assign;
2996
2997 bool checkConst(QualType QT) {
2998 // Assigning to a const object has undefined behavior.
2999 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003000 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003001 return false;
3002 }
3003 return true;
3004 }
3005
3006 bool failed() { return false; }
3007 bool found(APValue &Subobj, QualType SubobjType) {
3008 if (!checkConst(SubobjType))
3009 return false;
3010 // We've been given ownership of NewVal, so just swap it in.
3011 Subobj.swap(NewVal);
3012 return true;
3013 }
3014 bool found(APSInt &Value, QualType SubobjType) {
3015 if (!checkConst(SubobjType))
3016 return false;
3017 if (!NewVal.isInt()) {
3018 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003019 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003020 return false;
3021 }
3022 Value = NewVal.getInt();
3023 return true;
3024 }
3025 bool found(APFloat &Value, QualType SubobjType) {
3026 if (!checkConst(SubobjType))
3027 return false;
3028 Value = NewVal.getFloat();
3029 return true;
3030 }
3031 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3032 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3033 }
3034};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003035} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003036
Richard Smith3229b742013-05-05 21:17:10 +00003037const AccessKinds ModifySubobjectHandler::AccessKind;
3038
Richard Smith3da88fa2013-04-26 14:36:30 +00003039/// Update the designated sub-object of an rvalue to the given value.
3040static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003041 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003042 const SubobjectDesignator &Sub,
3043 APValue &NewVal) {
3044 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003045 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003046}
3047
Richard Smith84f6dcf2012-02-02 01:16:57 +00003048/// Find the position where two subobject designators diverge, or equivalently
3049/// the length of the common initial subsequence.
3050static unsigned FindDesignatorMismatch(QualType ObjType,
3051 const SubobjectDesignator &A,
3052 const SubobjectDesignator &B,
3053 bool &WasArrayIndex) {
3054 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3055 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003056 if (!ObjType.isNull() &&
3057 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003058 // Next subobject is an array element.
3059 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3060 WasArrayIndex = true;
3061 return I;
3062 }
Richard Smith66c96992012-02-18 22:04:06 +00003063 if (ObjType->isAnyComplexType())
3064 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3065 else
3066 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003067 } else {
3068 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3069 WasArrayIndex = false;
3070 return I;
3071 }
3072 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3073 // Next subobject is a field.
3074 ObjType = FD->getType();
3075 else
3076 // Next subobject is a base class.
3077 ObjType = QualType();
3078 }
3079 }
3080 WasArrayIndex = false;
3081 return I;
3082}
3083
3084/// Determine whether the given subobject designators refer to elements of the
3085/// same array object.
3086static bool AreElementsOfSameArray(QualType ObjType,
3087 const SubobjectDesignator &A,
3088 const SubobjectDesignator &B) {
3089 if (A.Entries.size() != B.Entries.size())
3090 return false;
3091
George Burgess IVa51c4072015-10-16 01:49:01 +00003092 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003093 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3094 // A is a subobject of the array element.
3095 return false;
3096
3097 // If A (and B) designates an array element, the last entry will be the array
3098 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3099 // of length 1' case, and the entire path must match.
3100 bool WasArrayIndex;
3101 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3102 return CommonLength >= A.Entries.size() - IsArray;
3103}
3104
Richard Smith3229b742013-05-05 21:17:10 +00003105/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003106static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3107 AccessKinds AK, const LValue &LVal,
3108 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003109 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003110 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003111 return CompleteObject();
3112 }
3113
Craig Topper36250ad2014-05-12 05:36:57 +00003114 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003115 if (LVal.getLValueCallIndex()) {
3116 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003117 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003118 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003119 << AK << LVal.Base.is<const ValueDecl*>();
3120 NoteLValueLocation(Info, LVal.Base);
3121 return CompleteObject();
3122 }
Richard Smith3229b742013-05-05 21:17:10 +00003123 }
3124
3125 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3126 // is not a constant expression (even if the object is non-volatile). We also
3127 // apply this rule to C++98, in order to conform to the expected 'volatile'
3128 // semantics.
3129 if (LValType.isVolatileQualified()) {
3130 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003131 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003132 << AK << LValType;
3133 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003134 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003135 return CompleteObject();
3136 }
3137
3138 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003139 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003140 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003141 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003142
3143 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3144 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3145 // In C++11, constexpr, non-volatile variables initialized with constant
3146 // expressions are constant expressions too. Inside constexpr functions,
3147 // parameters are constant expressions even if they're non-const.
3148 // In C++1y, objects local to a constant expression (those with a Frame) are
3149 // both readable and writable inside constant expressions.
3150 // In C, such things can also be folded, although they are not ICEs.
3151 const VarDecl *VD = dyn_cast<VarDecl>(D);
3152 if (VD) {
3153 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3154 VD = VDef;
3155 }
3156 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003157 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003158 return CompleteObject();
3159 }
3160
3161 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003162 if (BaseType.isVolatileQualified()) {
3163 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003164 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003165 << AK << 1 << VD;
3166 Info.Note(VD->getLocation(), diag::note_declared_at);
3167 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003168 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003169 }
3170 return CompleteObject();
3171 }
3172
3173 // Unless we're looking at a local variable or argument in a constexpr call,
3174 // the variable we're reading must be const.
3175 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003176 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003177 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3178 // OK, we can read and modify an object if we're in the process of
3179 // evaluating its initializer, because its lifetime began in this
3180 // evaluation.
3181 } else if (AK != AK_Read) {
3182 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003183 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003184 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003185 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003186 // OK, we can read this variable.
3187 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003188 // In OpenCL if a variable is in constant address space it is a const value.
3189 if (!(BaseType.isConstQualified() ||
3190 (Info.getLangOpts().OpenCL &&
3191 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003192 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003193 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003194 Info.Note(VD->getLocation(), diag::note_declared_at);
3195 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003196 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003197 }
3198 return CompleteObject();
3199 }
3200 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3201 // We support folding of const floating-point types, in order to make
3202 // static const data members of such types (supported as an extension)
3203 // more useful.
3204 if (Info.getLangOpts().CPlusPlus11) {
3205 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3206 Info.Note(VD->getLocation(), diag::note_declared_at);
3207 } else {
3208 Info.CCEDiag(E);
3209 }
George Burgess IVb5316982016-12-27 05:33:20 +00003210 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3211 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3212 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003213 } else {
3214 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003215 if (Info.checkingPotentialConstantExpression() &&
3216 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3217 // The definition of this variable could be constexpr. We can't
3218 // access it right now, but may be able to in future.
3219 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003220 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003221 Info.Note(VD->getLocation(), diag::note_declared_at);
3222 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003223 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003224 }
3225 return CompleteObject();
3226 }
3227 }
3228
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003229 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003230 return CompleteObject();
3231 } else {
3232 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3233
3234 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003235 if (const MaterializeTemporaryExpr *MTE =
3236 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3237 assert(MTE->getStorageDuration() == SD_Static &&
3238 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003239
Richard Smithe6c01442013-06-05 00:46:14 +00003240 // Per C++1y [expr.const]p2:
3241 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3242 // - a [...] glvalue of integral or enumeration type that refers to
3243 // a non-volatile const object [...]
3244 // [...]
3245 // - a [...] glvalue of literal type that refers to a non-volatile
3246 // object whose lifetime began within the evaluation of e.
3247 //
3248 // C++11 misses the 'began within the evaluation of e' check and
3249 // instead allows all temporaries, including things like:
3250 // int &&r = 1;
3251 // int x = ++r;
3252 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003253 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003254 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3255 const ValueDecl *ED = MTE->getExtendingDecl();
3256 if (!(BaseType.isConstQualified() &&
3257 BaseType->isIntegralOrEnumerationType()) &&
3258 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003259 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003260 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3261 return CompleteObject();
3262 }
3263
3264 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3265 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003266 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003267 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003268 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003269 return CompleteObject();
3270 }
3271 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003272 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003273 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003274 }
Richard Smith3229b742013-05-05 21:17:10 +00003275
3276 // Volatile temporary objects cannot be accessed in constant expressions.
3277 if (BaseType.isVolatileQualified()) {
3278 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003279 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003280 << AK << 0;
3281 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3282 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003283 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003284 }
3285 return CompleteObject();
3286 }
3287 }
3288
Richard Smith7525ff62013-05-09 07:14:00 +00003289 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003290 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003291 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003292 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3293 LVal.getLValueCallIndex(),
3294 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003295 BaseType = Info.Ctx.getCanonicalType(BaseType);
3296 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003297 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003298 }
3299
Richard Smith9defb7d2018-02-21 03:38:30 +00003300 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003301 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003302 //
3303 // FIXME: Not all local state is mutable. Allow local constant subobjects
3304 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003305 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3306 Info.EvalStatus.HasSideEffects) ||
3307 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003308 return CompleteObject();
3309
Richard Smith9defb7d2018-02-21 03:38:30 +00003310 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003311}
3312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003313/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003314/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3315/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003316///
3317/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003318/// \param Conv - The expression for which we are performing the conversion.
3319/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003320/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3321/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003322/// \param LVal - The glvalue on which we are attempting to perform this action.
3323/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003324static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003325 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003326 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003327 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003328 return false;
3329
Richard Smith3229b742013-05-05 21:17:10 +00003330 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003331 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003332 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003333 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3334 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3335 // initializer until now for such expressions. Such an expression can't be
3336 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003337 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003338 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003339 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003340 }
Richard Smith3229b742013-05-05 21:17:10 +00003341 APValue Lit;
3342 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3343 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003344 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003345 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003346 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003347 // We represent a string literal array as an lvalue pointing at the
3348 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003349 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003350 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003351 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003352 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003353 }
Richard Smith11562c52011-10-28 17:51:58 +00003354 }
3355
Richard Smith3229b742013-05-05 21:17:10 +00003356 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3357 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003358}
3359
3360/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003361static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003362 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003363 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003364 return false;
3365
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003366 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003367 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003368 return false;
3369 }
3370
Richard Smith3229b742013-05-05 21:17:10 +00003371 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003372 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3373}
3374
3375namespace {
3376struct CompoundAssignSubobjectHandler {
3377 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003378 const Expr *E;
3379 QualType PromotedLHSType;
3380 BinaryOperatorKind Opcode;
3381 const APValue &RHS;
3382
3383 static const AccessKinds AccessKind = AK_Assign;
3384
3385 typedef bool result_type;
3386
3387 bool checkConst(QualType QT) {
3388 // Assigning to a const object has undefined behavior.
3389 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003390 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003391 return false;
3392 }
3393 return true;
3394 }
3395
3396 bool failed() { return false; }
3397 bool found(APValue &Subobj, QualType SubobjType) {
3398 switch (Subobj.getKind()) {
3399 case APValue::Int:
3400 return found(Subobj.getInt(), SubobjType);
3401 case APValue::Float:
3402 return found(Subobj.getFloat(), SubobjType);
3403 case APValue::ComplexInt:
3404 case APValue::ComplexFloat:
3405 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003406 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003407 return false;
3408 case APValue::LValue:
3409 return foundPointer(Subobj, SubobjType);
3410 default:
3411 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003412 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003413 return false;
3414 }
3415 }
3416 bool found(APSInt &Value, QualType SubobjType) {
3417 if (!checkConst(SubobjType))
3418 return false;
3419
3420 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3421 // We don't support compound assignment on integer-cast-to-pointer
3422 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003423 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003424 return false;
3425 }
3426
3427 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3428 SubobjType, Value);
3429 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3430 return false;
3431 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3432 return true;
3433 }
3434 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003435 return checkConst(SubobjType) &&
3436 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3437 Value) &&
3438 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3439 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003440 }
3441 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3442 if (!checkConst(SubobjType))
3443 return false;
3444
3445 QualType PointeeType;
3446 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3447 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003448
3449 if (PointeeType.isNull() || !RHS.isInt() ||
3450 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003451 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003452 return false;
3453 }
3454
Richard Smithd6cc1982017-01-31 02:23:02 +00003455 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003456 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003457 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003458
3459 LValue LVal;
3460 LVal.setFrom(Info.Ctx, Subobj);
3461 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3462 return false;
3463 LVal.moveInto(Subobj);
3464 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003465 }
3466 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3467 llvm_unreachable("shouldn't encounter string elements here");
3468 }
3469};
3470} // end anonymous namespace
3471
3472const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3473
3474/// Perform a compound assignment of LVal <op>= RVal.
3475static bool handleCompoundAssignment(
3476 EvalInfo &Info, const Expr *E,
3477 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3478 BinaryOperatorKind Opcode, const APValue &RVal) {
3479 if (LVal.Designator.Invalid)
3480 return false;
3481
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003482 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003483 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003484 return false;
3485 }
3486
3487 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3488 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3489 RVal };
3490 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3491}
3492
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003493namespace {
3494struct IncDecSubobjectHandler {
3495 EvalInfo &Info;
3496 const UnaryOperator *E;
3497 AccessKinds AccessKind;
3498 APValue *Old;
3499
Richard Smith243ef902013-05-05 23:31:59 +00003500 typedef bool result_type;
3501
3502 bool checkConst(QualType QT) {
3503 // Assigning to a const object has undefined behavior.
3504 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003505 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003506 return false;
3507 }
3508 return true;
3509 }
3510
3511 bool failed() { return false; }
3512 bool found(APValue &Subobj, QualType SubobjType) {
3513 // Stash the old value. Also clear Old, so we don't clobber it later
3514 // if we're post-incrementing a complex.
3515 if (Old) {
3516 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003517 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003518 }
3519
3520 switch (Subobj.getKind()) {
3521 case APValue::Int:
3522 return found(Subobj.getInt(), SubobjType);
3523 case APValue::Float:
3524 return found(Subobj.getFloat(), SubobjType);
3525 case APValue::ComplexInt:
3526 return found(Subobj.getComplexIntReal(),
3527 SubobjType->castAs<ComplexType>()->getElementType()
3528 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3529 case APValue::ComplexFloat:
3530 return found(Subobj.getComplexFloatReal(),
3531 SubobjType->castAs<ComplexType>()->getElementType()
3532 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3533 case APValue::LValue:
3534 return foundPointer(Subobj, SubobjType);
3535 default:
3536 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003537 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003538 return false;
3539 }
3540 }
3541 bool found(APSInt &Value, QualType SubobjType) {
3542 if (!checkConst(SubobjType))
3543 return false;
3544
3545 if (!SubobjType->isIntegerType()) {
3546 // We don't support increment / decrement on integer-cast-to-pointer
3547 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003548 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003549 return false;
3550 }
3551
3552 if (Old) *Old = APValue(Value);
3553
3554 // bool arithmetic promotes to int, and the conversion back to bool
3555 // doesn't reduce mod 2^n, so special-case it.
3556 if (SubobjType->isBooleanType()) {
3557 if (AccessKind == AK_Increment)
3558 Value = 1;
3559 else
3560 Value = !Value;
3561 return true;
3562 }
3563
3564 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003565 if (AccessKind == AK_Increment) {
3566 ++Value;
3567
3568 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3569 APSInt ActualValue(Value, /*IsUnsigned*/true);
3570 return HandleOverflow(Info, E, ActualValue, SubobjType);
3571 }
3572 } else {
3573 --Value;
3574
3575 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3576 unsigned BitWidth = Value.getBitWidth();
3577 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3578 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003579 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003580 }
3581 }
3582 return true;
3583 }
3584 bool found(APFloat &Value, QualType SubobjType) {
3585 if (!checkConst(SubobjType))
3586 return false;
3587
3588 if (Old) *Old = APValue(Value);
3589
3590 APFloat One(Value.getSemantics(), 1);
3591 if (AccessKind == AK_Increment)
3592 Value.add(One, APFloat::rmNearestTiesToEven);
3593 else
3594 Value.subtract(One, APFloat::rmNearestTiesToEven);
3595 return true;
3596 }
3597 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3598 if (!checkConst(SubobjType))
3599 return false;
3600
3601 QualType PointeeType;
3602 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3603 PointeeType = PT->getPointeeType();
3604 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003605 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003606 return false;
3607 }
3608
3609 LValue LVal;
3610 LVal.setFrom(Info.Ctx, Subobj);
3611 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3612 AccessKind == AK_Increment ? 1 : -1))
3613 return false;
3614 LVal.moveInto(Subobj);
3615 return true;
3616 }
3617 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3618 llvm_unreachable("shouldn't encounter string elements here");
3619 }
3620};
3621} // end anonymous namespace
3622
3623/// Perform an increment or decrement on LVal.
3624static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3625 QualType LValType, bool IsIncrement, APValue *Old) {
3626 if (LVal.Designator.Invalid)
3627 return false;
3628
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003629 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003630 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003631 return false;
3632 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003633
3634 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3635 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3636 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3637 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3638}
3639
Richard Smithe97cbd72011-11-11 04:05:33 +00003640/// Build an lvalue for the object argument of a member function call.
3641static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3642 LValue &This) {
3643 if (Object->getType()->isPointerType())
3644 return EvaluatePointer(Object, This, Info);
3645
3646 if (Object->isGLValue())
3647 return EvaluateLValue(Object, This, Info);
3648
Richard Smithd9f663b2013-04-22 15:31:51 +00003649 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003650 return EvaluateTemporary(Object, This, Info);
3651
Faisal Valie690b7a2016-07-02 22:34:24 +00003652 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003653 return false;
3654}
3655
3656/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3657/// lvalue referring to the result.
3658///
3659/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003660/// \param LV - An lvalue referring to the base of the member pointer.
3661/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003662/// \param IncludeMember - Specifies whether the member itself is included in
3663/// the resulting LValue subobject designator. This is not possible when
3664/// creating a bound member function.
3665/// \return The field or method declaration to which the member pointer refers,
3666/// or 0 if evaluation fails.
3667static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003668 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003669 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003670 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003671 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003672 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003673 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003674 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003675
3676 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3677 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003678 if (!MemPtr.getDecl()) {
3679 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003680 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003681 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003682 }
Richard Smith253c2a32012-01-27 01:14:48 +00003683
Richard Smith027bf112011-11-17 22:56:20 +00003684 if (MemPtr.isDerivedMember()) {
3685 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003686 // The end of the derived-to-base path for the base object must match the
3687 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003688 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003689 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003690 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003691 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003692 }
Richard Smith027bf112011-11-17 22:56:20 +00003693 unsigned PathLengthToMember =
3694 LV.Designator.Entries.size() - MemPtr.Path.size();
3695 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3696 const CXXRecordDecl *LVDecl = getAsBaseClass(
3697 LV.Designator.Entries[PathLengthToMember + I]);
3698 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003699 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003700 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003701 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003702 }
Richard Smith027bf112011-11-17 22:56:20 +00003703 }
3704
3705 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003706 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003707 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003708 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003709 } else if (!MemPtr.Path.empty()) {
3710 // Extend the LValue path with the member pointer's path.
3711 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3712 MemPtr.Path.size() + IncludeMember);
3713
3714 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003715 if (const PointerType *PT = LVType->getAs<PointerType>())
3716 LVType = PT->getPointeeType();
3717 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3718 assert(RD && "member pointer access on non-class-type expression");
3719 // The first class in the path is that of the lvalue.
3720 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3721 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003722 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003723 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003724 RD = Base;
3725 }
3726 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003727 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3728 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003729 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003730 }
3731
3732 // Add the member. Note that we cannot build bound member functions here.
3733 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003734 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003735 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003736 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003737 } else if (const IndirectFieldDecl *IFD =
3738 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003739 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003740 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003741 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003742 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003743 }
Richard Smith027bf112011-11-17 22:56:20 +00003744 }
3745
3746 return MemPtr.getDecl();
3747}
3748
Richard Smith84401042013-06-03 05:03:02 +00003749static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3750 const BinaryOperator *BO,
3751 LValue &LV,
3752 bool IncludeMember = true) {
3753 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3754
3755 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003756 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003757 MemberPtr MemPtr;
3758 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3759 }
Craig Topper36250ad2014-05-12 05:36:57 +00003760 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003761 }
3762
3763 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3764 BO->getRHS(), IncludeMember);
3765}
3766
Richard Smith027bf112011-11-17 22:56:20 +00003767/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3768/// the provided lvalue, which currently refers to the base object.
3769static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3770 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003771 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003772 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003773 return false;
3774
Richard Smitha8105bc2012-01-06 16:39:00 +00003775 QualType TargetQT = E->getType();
3776 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3777 TargetQT = PT->getPointeeType();
3778
3779 // Check this cast lands within the final derived-to-base subobject path.
3780 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003781 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003782 << D.MostDerivedType << TargetQT;
3783 return false;
3784 }
3785
Richard Smith027bf112011-11-17 22:56:20 +00003786 // Check the type of the final cast. We don't need to check the path,
3787 // since a cast can only be formed if the path is unique.
3788 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003789 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3790 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003791 if (NewEntriesSize == D.MostDerivedPathLength)
3792 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3793 else
Richard Smith027bf112011-11-17 22:56:20 +00003794 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003795 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003796 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003797 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003798 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003799 }
Richard Smith027bf112011-11-17 22:56:20 +00003800
3801 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003802 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003803}
3804
Mike Stump876387b2009-10-27 22:09:17 +00003805namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003806enum EvalStmtResult {
3807 /// Evaluation failed.
3808 ESR_Failed,
3809 /// Hit a 'return' statement.
3810 ESR_Returned,
3811 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003812 ESR_Succeeded,
3813 /// Hit a 'continue' statement.
3814 ESR_Continue,
3815 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003816 ESR_Break,
3817 /// Still scanning for 'case' or 'default' statement.
3818 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003819};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003820}
Richard Smith254a73d2011-10-28 22:34:42 +00003821
Richard Smith97fcf4b2016-08-14 23:15:52 +00003822static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3823 // We don't need to evaluate the initializer for a static local.
3824 if (!VD->hasLocalStorage())
3825 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003826
Richard Smith97fcf4b2016-08-14 23:15:52 +00003827 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003828 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003829
Richard Smith97fcf4b2016-08-14 23:15:52 +00003830 const Expr *InitE = VD->getInit();
3831 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003832 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3833 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003834 Val = APValue();
3835 return false;
3836 }
Richard Smith51f03172013-06-20 03:00:05 +00003837
Richard Smith97fcf4b2016-08-14 23:15:52 +00003838 if (InitE->isValueDependent())
3839 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003840
Richard Smith97fcf4b2016-08-14 23:15:52 +00003841 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3842 // Wipe out any partially-computed value, to allow tracking that this
3843 // evaluation failed.
3844 Val = APValue();
3845 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003846 }
3847
3848 return true;
3849}
3850
Richard Smith97fcf4b2016-08-14 23:15:52 +00003851static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3852 bool OK = true;
3853
3854 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3855 OK &= EvaluateVarDecl(Info, VD);
3856
3857 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3858 for (auto *BD : DD->bindings())
3859 if (auto *VD = BD->getHoldingVar())
3860 OK &= EvaluateDecl(Info, VD);
3861
3862 return OK;
3863}
3864
3865
Richard Smith4e18ca52013-05-06 05:56:11 +00003866/// Evaluate a condition (either a variable declaration or an expression).
3867static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3868 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003869 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003870 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3871 return false;
3872 return EvaluateAsBooleanCondition(Cond, Result, Info);
3873}
3874
Richard Smith89210072016-04-04 23:29:43 +00003875namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003876/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003877/// statement should be stored.
3878struct StmtResult {
3879 /// The APValue that should be filled in with the returned value.
3880 APValue &Value;
3881 /// The location containing the result, if any (used to support RVO).
3882 const LValue *Slot;
3883};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003884
3885struct TempVersionRAII {
3886 CallStackFrame &Frame;
3887
3888 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3889 Frame.pushTempVersion();
3890 }
3891
3892 ~TempVersionRAII() {
3893 Frame.popTempVersion();
3894 }
3895};
3896
Richard Smith89210072016-04-04 23:29:43 +00003897}
Richard Smith52a980a2015-08-28 02:43:42 +00003898
3899static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003900 const Stmt *S,
3901 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003902
3903/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003904static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003905 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003906 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003907 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003908 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003909 case ESR_Break:
3910 return ESR_Succeeded;
3911 case ESR_Succeeded:
3912 case ESR_Continue:
3913 return ESR_Continue;
3914 case ESR_Failed:
3915 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003916 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003917 return ESR;
3918 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003919 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003920}
3921
Richard Smith496ddcf2013-05-12 17:32:42 +00003922/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003923static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003924 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003925 BlockScopeRAII Scope(Info);
3926
Richard Smith496ddcf2013-05-12 17:32:42 +00003927 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003928 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003929 {
3930 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003931 if (const Stmt *Init = SS->getInit()) {
3932 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3933 if (ESR != ESR_Succeeded)
3934 return ESR;
3935 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003936 if (SS->getConditionVariable() &&
3937 !EvaluateDecl(Info, SS->getConditionVariable()))
3938 return ESR_Failed;
3939 if (!EvaluateInteger(SS->getCond(), Value, Info))
3940 return ESR_Failed;
3941 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003942
3943 // Find the switch case corresponding to the value of the condition.
3944 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003945 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003946 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3947 SC = SC->getNextSwitchCase()) {
3948 if (isa<DefaultStmt>(SC)) {
3949 Found = SC;
3950 continue;
3951 }
3952
3953 const CaseStmt *CS = cast<CaseStmt>(SC);
3954 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3955 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3956 : LHS;
3957 if (LHS <= Value && Value <= RHS) {
3958 Found = SC;
3959 break;
3960 }
3961 }
3962
3963 if (!Found)
3964 return ESR_Succeeded;
3965
3966 // Search the switch body for the switch case and evaluate it from there.
3967 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3968 case ESR_Break:
3969 return ESR_Succeeded;
3970 case ESR_Succeeded:
3971 case ESR_Continue:
3972 case ESR_Failed:
3973 case ESR_Returned:
3974 return ESR;
3975 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003976 // This can only happen if the switch case is nested within a statement
3977 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003978 Info.FFDiag(Found->getBeginLoc(),
3979 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003980 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003981 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003982 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003983}
3984
Richard Smith254a73d2011-10-28 22:34:42 +00003985// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003986static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003987 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003988 if (!Info.nextStep(S))
3989 return ESR_Failed;
3990
Richard Smith496ddcf2013-05-12 17:32:42 +00003991 // If we're hunting down a 'case' or 'default' label, recurse through
3992 // substatements until we hit the label.
3993 if (Case) {
3994 // FIXME: We don't start the lifetime of objects whose initialization we
3995 // jump over. However, such objects must be of class type with a trivial
3996 // default constructor that initialize all subobjects, so must be empty,
3997 // so this almost never matters.
3998 switch (S->getStmtClass()) {
3999 case Stmt::CompoundStmtClass:
4000 // FIXME: Precompute which substatement of a compound statement we
4001 // would jump to, and go straight there rather than performing a
4002 // linear scan each time.
4003 case Stmt::LabelStmtClass:
4004 case Stmt::AttributedStmtClass:
4005 case Stmt::DoStmtClass:
4006 break;
4007
4008 case Stmt::CaseStmtClass:
4009 case Stmt::DefaultStmtClass:
4010 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004011 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004012 break;
4013
4014 case Stmt::IfStmtClass: {
4015 // FIXME: Precompute which side of an 'if' we would jump to, and go
4016 // straight there rather than scanning both sides.
4017 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004018
4019 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4020 // preceded by our switch label.
4021 BlockScopeRAII Scope(Info);
4022
Richard Smith496ddcf2013-05-12 17:32:42 +00004023 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4024 if (ESR != ESR_CaseNotFound || !IS->getElse())
4025 return ESR;
4026 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4027 }
4028
4029 case Stmt::WhileStmtClass: {
4030 EvalStmtResult ESR =
4031 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4032 if (ESR != ESR_Continue)
4033 return ESR;
4034 break;
4035 }
4036
4037 case Stmt::ForStmtClass: {
4038 const ForStmt *FS = cast<ForStmt>(S);
4039 EvalStmtResult ESR =
4040 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4041 if (ESR != ESR_Continue)
4042 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004043 if (FS->getInc()) {
4044 FullExpressionRAII IncScope(Info);
4045 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4046 return ESR_Failed;
4047 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004048 break;
4049 }
4050
4051 case Stmt::DeclStmtClass:
4052 // FIXME: If the variable has initialization that can't be jumped over,
4053 // bail out of any immediately-surrounding compound-statement too.
4054 default:
4055 return ESR_CaseNotFound;
4056 }
4057 }
4058
Richard Smith254a73d2011-10-28 22:34:42 +00004059 switch (S->getStmtClass()) {
4060 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004061 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004062 // Don't bother evaluating beyond an expression-statement which couldn't
4063 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004064 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004065 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004066 return ESR_Failed;
4067 return ESR_Succeeded;
4068 }
4069
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004070 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004071 return ESR_Failed;
4072
4073 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004074 return ESR_Succeeded;
4075
Richard Smithd9f663b2013-04-22 15:31:51 +00004076 case Stmt::DeclStmtClass: {
4077 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004078 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004079 // Each declaration initialization is its own full-expression.
4080 // FIXME: This isn't quite right; if we're performing aggregate
4081 // initialization, each braced subexpression is its own full-expression.
4082 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004083 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004084 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004085 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004086 return ESR_Succeeded;
4087 }
4088
Richard Smith357362d2011-12-13 06:39:58 +00004089 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004090 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004091 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004092 if (RetExpr &&
4093 !(Result.Slot
4094 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4095 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004096 return ESR_Failed;
4097 return ESR_Returned;
4098 }
Richard Smith254a73d2011-10-28 22:34:42 +00004099
4100 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004101 BlockScopeRAII Scope(Info);
4102
Richard Smith254a73d2011-10-28 22:34:42 +00004103 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004104 for (const auto *BI : CS->body()) {
4105 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004106 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004107 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004108 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004109 return ESR;
4110 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004111 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004112 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004113
4114 case Stmt::IfStmtClass: {
4115 const IfStmt *IS = cast<IfStmt>(S);
4116
4117 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004118 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004119 if (const Stmt *Init = IS->getInit()) {
4120 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4121 if (ESR != ESR_Succeeded)
4122 return ESR;
4123 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004124 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004125 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004126 return ESR_Failed;
4127
4128 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4129 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4130 if (ESR != ESR_Succeeded)
4131 return ESR;
4132 }
4133 return ESR_Succeeded;
4134 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004135
4136 case Stmt::WhileStmtClass: {
4137 const WhileStmt *WS = cast<WhileStmt>(S);
4138 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004139 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004140 bool Continue;
4141 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4142 Continue))
4143 return ESR_Failed;
4144 if (!Continue)
4145 break;
4146
4147 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4148 if (ESR != ESR_Continue)
4149 return ESR;
4150 }
4151 return ESR_Succeeded;
4152 }
4153
4154 case Stmt::DoStmtClass: {
4155 const DoStmt *DS = cast<DoStmt>(S);
4156 bool Continue;
4157 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004158 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004159 if (ESR != ESR_Continue)
4160 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004161 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004162
Richard Smith08d6a2c2013-07-24 07:11:57 +00004163 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004164 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4165 return ESR_Failed;
4166 } while (Continue);
4167 return ESR_Succeeded;
4168 }
4169
4170 case Stmt::ForStmtClass: {
4171 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004172 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004173 if (FS->getInit()) {
4174 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4175 if (ESR != ESR_Succeeded)
4176 return ESR;
4177 }
4178 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004179 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004180 bool Continue = true;
4181 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4182 FS->getCond(), Continue))
4183 return ESR_Failed;
4184 if (!Continue)
4185 break;
4186
4187 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4188 if (ESR != ESR_Continue)
4189 return ESR;
4190
Richard Smith08d6a2c2013-07-24 07:11:57 +00004191 if (FS->getInc()) {
4192 FullExpressionRAII IncScope(Info);
4193 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4194 return ESR_Failed;
4195 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004196 }
4197 return ESR_Succeeded;
4198 }
4199
Richard Smith896e0d72013-05-06 06:51:17 +00004200 case Stmt::CXXForRangeStmtClass: {
4201 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004202 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004203
Richard Smith8baa5002018-09-28 18:44:09 +00004204 // Evaluate the init-statement if present.
4205 if (FS->getInit()) {
4206 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4207 if (ESR != ESR_Succeeded)
4208 return ESR;
4209 }
4210
Richard Smith896e0d72013-05-06 06:51:17 +00004211 // Initialize the __range variable.
4212 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4213 if (ESR != ESR_Succeeded)
4214 return ESR;
4215
4216 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004217 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4218 if (ESR != ESR_Succeeded)
4219 return ESR;
4220 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004221 if (ESR != ESR_Succeeded)
4222 return ESR;
4223
4224 while (true) {
4225 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004226 {
4227 bool Continue = true;
4228 FullExpressionRAII CondExpr(Info);
4229 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4230 return ESR_Failed;
4231 if (!Continue)
4232 break;
4233 }
Richard Smith896e0d72013-05-06 06:51:17 +00004234
4235 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004236 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004237 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4238 if (ESR != ESR_Succeeded)
4239 return ESR;
4240
4241 // Loop body.
4242 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4243 if (ESR != ESR_Continue)
4244 return ESR;
4245
4246 // Increment: ++__begin
4247 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4248 return ESR_Failed;
4249 }
4250
4251 return ESR_Succeeded;
4252 }
4253
Richard Smith496ddcf2013-05-12 17:32:42 +00004254 case Stmt::SwitchStmtClass:
4255 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4256
Richard Smith4e18ca52013-05-06 05:56:11 +00004257 case Stmt::ContinueStmtClass:
4258 return ESR_Continue;
4259
4260 case Stmt::BreakStmtClass:
4261 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004262
4263 case Stmt::LabelStmtClass:
4264 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4265
4266 case Stmt::AttributedStmtClass:
4267 // As a general principle, C++11 attributes can be ignored without
4268 // any semantic impact.
4269 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4270 Case);
4271
4272 case Stmt::CaseStmtClass:
4273 case Stmt::DefaultStmtClass:
4274 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004275 }
4276}
4277
Richard Smithcc36f692011-12-22 02:22:31 +00004278/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4279/// default constructor. If so, we'll fold it whether or not it's marked as
4280/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4281/// so we need special handling.
4282static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004283 const CXXConstructorDecl *CD,
4284 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004285 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4286 return false;
4287
Richard Smith66e05fe2012-01-18 05:21:49 +00004288 // Value-initialization does not call a trivial default constructor, so such a
4289 // call is a core constant expression whether or not the constructor is
4290 // constexpr.
4291 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004292 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004293 // FIXME: If DiagDecl is an implicitly-declared special member function,
4294 // we should be much more explicit about why it's not constexpr.
4295 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4296 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4297 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004298 } else {
4299 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4300 }
4301 }
4302 return true;
4303}
4304
Richard Smith357362d2011-12-13 06:39:58 +00004305/// CheckConstexprFunction - Check that a function can be called in a constant
4306/// expression.
4307static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4308 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004309 const FunctionDecl *Definition,
4310 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004311 // Potential constant expressions can contain calls to declared, but not yet
4312 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004313 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004314 Declaration->isConstexpr())
4315 return false;
4316
James Y Knightc7d3e602018-10-05 17:49:48 +00004317 // Bail out if the function declaration itself is invalid. We will
4318 // have produced a relevant diagnostic while parsing it, so just
4319 // note the problematic sub-expression.
4320 if (Declaration->isInvalidDecl()) {
4321 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004322 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004323 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004324
Richard Smith357362d2011-12-13 06:39:58 +00004325 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004326 if (Definition && Definition->isConstexpr() &&
4327 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004328 return true;
4329
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004330 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004331 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004332
Richard Smith5179eb72016-06-28 19:03:57 +00004333 // If this function is not constexpr because it is an inherited
4334 // non-constexpr constructor, diagnose that directly.
4335 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4336 if (CD && CD->isInheritingConstructor()) {
4337 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004338 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004339 DiagDecl = CD = Inherited;
4340 }
4341
4342 // FIXME: If DiagDecl is an implicitly-declared special member function
4343 // or an inheriting constructor, we should be much more explicit about why
4344 // it's not constexpr.
4345 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004346 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004347 << CD->getInheritedConstructor().getConstructor()->getParent();
4348 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004349 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004350 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004351 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4352 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004353 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004354 }
4355 return false;
4356}
4357
Richard Smithbe6dd812014-11-19 21:27:17 +00004358/// Determine if a class has any fields that might need to be copied by a
4359/// trivial copy or move operation.
4360static bool hasFields(const CXXRecordDecl *RD) {
4361 if (!RD || RD->isEmpty())
4362 return false;
4363 for (auto *FD : RD->fields()) {
4364 if (FD->isUnnamedBitfield())
4365 continue;
4366 return true;
4367 }
4368 for (auto &Base : RD->bases())
4369 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4370 return true;
4371 return false;
4372}
4373
Richard Smithd62306a2011-11-10 06:34:14 +00004374namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004375typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004376}
4377
4378/// EvaluateArgs - Evaluate the arguments to a function call.
4379static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4380 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004381 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004382 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004383 I != E; ++I) {
4384 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4385 // If we're checking for a potential constant expression, evaluate all
4386 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004387 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004388 return false;
4389 Success = false;
4390 }
4391 }
4392 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004393}
4394
Richard Smith254a73d2011-10-28 22:34:42 +00004395/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004396static bool HandleFunctionCall(SourceLocation CallLoc,
4397 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004398 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004399 EvalInfo &Info, APValue &Result,
4400 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004401 ArgVector ArgValues(Args.size());
4402 if (!EvaluateArgs(Args, ArgValues, Info))
4403 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004404
Richard Smith253c2a32012-01-27 01:14:48 +00004405 if (!Info.CheckCallLimit(CallLoc))
4406 return false;
4407
4408 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004409
4410 // For a trivial copy or move assignment, perform an APValue copy. This is
4411 // essential for unions, where the operations performed by the assignment
4412 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004413 //
4414 // Skip this for non-union classes with no fields; in that case, the defaulted
4415 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004416 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004417 if (MD && MD->isDefaulted() &&
4418 (MD->getParent()->isUnion() ||
4419 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004420 assert(This &&
4421 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4422 LValue RHS;
4423 RHS.setFrom(Info.Ctx, ArgValues[0]);
4424 APValue RHSValue;
4425 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4426 RHS, RHSValue))
4427 return false;
4428 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4429 RHSValue))
4430 return false;
4431 This->moveInto(Result);
4432 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004433 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004434 // We're in a lambda; determine the lambda capture field maps unless we're
4435 // just constexpr checking a lambda's call operator. constexpr checking is
4436 // done before the captures have been added to the closure object (unless
4437 // we're inferring constexpr-ness), so we don't have access to them in this
4438 // case. But since we don't need the captures to constexpr check, we can
4439 // just ignore them.
4440 if (!Info.checkingPotentialConstantExpression())
4441 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4442 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004443 }
4444
Richard Smith52a980a2015-08-28 02:43:42 +00004445 StmtResult Ret = {Result, ResultSlot};
4446 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004447 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004448 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004449 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004450 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004451 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004452 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004453}
4454
Richard Smithd62306a2011-11-10 06:34:14 +00004455/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004456static bool HandleConstructorCall(const Expr *E, const LValue &This,
4457 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004458 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004459 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004460 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004461 if (!Info.CheckCallLimit(CallLoc))
4462 return false;
4463
Richard Smith3607ffe2012-02-13 03:54:03 +00004464 const CXXRecordDecl *RD = Definition->getParent();
4465 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004466 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004467 return false;
4468 }
4469
Erik Pilkington42925492017-10-04 00:18:55 +00004470 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004471 Info, {This.getLValueBase(),
4472 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004473 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004474
Richard Smith52a980a2015-08-28 02:43:42 +00004475 // FIXME: Creating an APValue just to hold a nonexistent return value is
4476 // wasteful.
4477 APValue RetVal;
4478 StmtResult Ret = {RetVal, nullptr};
4479
Richard Smith5179eb72016-06-28 19:03:57 +00004480 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004481 if (Definition->isDelegatingConstructor()) {
4482 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004483 {
4484 FullExpressionRAII InitScope(Info);
4485 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4486 return false;
4487 }
Richard Smith52a980a2015-08-28 02:43:42 +00004488 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004489 }
4490
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004491 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004492 // essential for unions (or classes with anonymous union members), where the
4493 // operations performed by the constructor cannot be represented by
4494 // ctor-initializers.
4495 //
4496 // Skip this for empty non-union classes; we should not perform an
4497 // lvalue-to-rvalue conversion on them because their copy constructor does not
4498 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004499 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004500 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004501 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004502 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004503 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004504 return handleLValueToRValueConversion(
4505 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4506 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004507 }
4508
4509 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004510 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004511 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004512 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004513
John McCalld7bca762012-05-01 00:38:49 +00004514 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004515 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4516
Richard Smith08d6a2c2013-07-24 07:11:57 +00004517 // A scope for temporaries lifetime-extended by reference members.
4518 BlockScopeRAII LifetimeExtendedScope(Info);
4519
Richard Smith253c2a32012-01-27 01:14:48 +00004520 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004521 unsigned BasesSeen = 0;
4522#ifndef NDEBUG
4523 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4524#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004525 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004526 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004527 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004528 APValue *Value = &Result;
4529
4530 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004531 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004532 if (I->isBaseInitializer()) {
4533 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004534#ifndef NDEBUG
4535 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004536 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004537 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4538 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4539 "base class initializers not in expected order");
4540 ++BaseIt;
4541#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004542 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004543 BaseType->getAsCXXRecordDecl(), &Layout))
4544 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004545 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004546 } else if ((FD = I->getMember())) {
4547 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004548 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004549 if (RD->isUnion()) {
4550 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004551 Value = &Result.getUnionValue();
4552 } else {
4553 Value = &Result.getStructField(FD->getFieldIndex());
4554 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004555 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004556 // Walk the indirect field decl's chain to find the object to initialize,
4557 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004558 auto IndirectFieldChain = IFD->chain();
4559 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004560 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004561 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4562 // Switch the union field if it differs. This happens if we had
4563 // preceding zero-initialization, and we're now initializing a union
4564 // subobject other than the first.
4565 // FIXME: In this case, the values of the other subobjects are
4566 // specified, since zero-initialization sets all padding bits to zero.
4567 if (Value->isUninit() ||
4568 (Value->isUnion() && Value->getUnionField() != FD)) {
4569 if (CD->isUnion())
4570 *Value = APValue(FD);
4571 else
4572 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004573 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004574 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004575 // Store Subobject as its parent before updating it for the last element
4576 // in the chain.
4577 if (C == IndirectFieldChain.back())
4578 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004579 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004580 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004581 if (CD->isUnion())
4582 Value = &Value->getUnionValue();
4583 else
4584 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004585 }
Richard Smithd62306a2011-11-10 06:34:14 +00004586 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004587 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004588 }
Richard Smith253c2a32012-01-27 01:14:48 +00004589
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004590 // Need to override This for implicit field initializers as in this case
4591 // This refers to innermost anonymous struct/union containing initializer,
4592 // not to currently constructed class.
4593 const Expr *Init = I->getInit();
4594 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4595 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004596 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004597 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4598 (FD && FD->isBitField() &&
4599 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004600 // If we're checking for a potential constant expression, evaluate all
4601 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004602 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004603 return false;
4604 Success = false;
4605 }
Richard Smithd62306a2011-11-10 06:34:14 +00004606 }
4607
Richard Smithd9f663b2013-04-22 15:31:51 +00004608 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004609 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004610}
4611
Richard Smith5179eb72016-06-28 19:03:57 +00004612static bool HandleConstructorCall(const Expr *E, const LValue &This,
4613 ArrayRef<const Expr*> Args,
4614 const CXXConstructorDecl *Definition,
4615 EvalInfo &Info, APValue &Result) {
4616 ArgVector ArgValues(Args.size());
4617 if (!EvaluateArgs(Args, ArgValues, Info))
4618 return false;
4619
4620 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4621 Info, Result);
4622}
4623
Eli Friedman9a156e52008-11-12 09:44:48 +00004624//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004625// Generic Evaluation
4626//===----------------------------------------------------------------------===//
4627namespace {
4628
Aaron Ballman68af21c2014-01-03 19:26:43 +00004629template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004630class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004631 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004632private:
Richard Smith52a980a2015-08-28 02:43:42 +00004633 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004634 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004635 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004636 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004637 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004638 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004639 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004640
Richard Smith17100ba2012-02-16 02:46:34 +00004641 // Check whether a conditional operator with a non-constant condition is a
4642 // potential constant expression. If neither arm is a potential constant
4643 // expression, then the conditional operator is not either.
4644 template<typename ConditionalOperator>
4645 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004646 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004647
4648 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004649 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004650 {
Richard Smith17100ba2012-02-16 02:46:34 +00004651 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004652 StmtVisitorTy::Visit(E->getFalseExpr());
4653 if (Diag.empty())
4654 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004655 }
Richard Smith17100ba2012-02-16 02:46:34 +00004656
George Burgess IV8c892b52016-05-25 22:31:54 +00004657 {
4658 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004659 Diag.clear();
4660 StmtVisitorTy::Visit(E->getTrueExpr());
4661 if (Diag.empty())
4662 return;
4663 }
4664
4665 Error(E, diag::note_constexpr_conditional_never_const);
4666 }
4667
4668
4669 template<typename ConditionalOperator>
4670 bool HandleConditionalOperator(const ConditionalOperator *E) {
4671 bool BoolResult;
4672 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004673 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004674 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004675 return false;
4676 }
4677 if (Info.noteFailure()) {
4678 StmtVisitorTy::Visit(E->getTrueExpr());
4679 StmtVisitorTy::Visit(E->getFalseExpr());
4680 }
Richard Smith17100ba2012-02-16 02:46:34 +00004681 return false;
4682 }
4683
4684 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4685 return StmtVisitorTy::Visit(EvalExpr);
4686 }
4687
Peter Collingbournee9200682011-05-13 03:29:01 +00004688protected:
4689 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004690 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004691 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4692
Richard Smith92b1ce02011-12-12 09:28:41 +00004693 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004694 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004695 }
4696
Aaron Ballman68af21c2014-01-03 19:26:43 +00004697 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004698
4699public:
4700 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4701
4702 EvalInfo &getEvalInfo() { return Info; }
4703
Richard Smithf57d8cb2011-12-09 22:58:01 +00004704 /// Report an evaluation error. This should only be called when an error is
4705 /// first discovered. When propagating an error, just return false.
4706 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004707 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004708 return false;
4709 }
4710 bool Error(const Expr *E) {
4711 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4712 }
4713
Aaron Ballman68af21c2014-01-03 19:26:43 +00004714 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004715 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004716 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004717 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004718 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004719 }
4720
Aaron Ballman68af21c2014-01-03 19:26:43 +00004721 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004722 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004723 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004724 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004725 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004726 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004727 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004728 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004729 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004730 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004731 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004732 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004733 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4734 TempVersionRAII RAII(*Info.CurrentCall);
4735 return StmtVisitorTy::Visit(E->getExpr());
4736 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004737 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004738 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004739 // The initializer may not have been parsed yet, or might be erroneous.
4740 if (!E->getExpr())
4741 return Error(E);
4742 return StmtVisitorTy::Visit(E->getExpr());
4743 }
Richard Smith5894a912011-12-19 22:12:41 +00004744 // We cannot create any objects for which cleanups are required, so there is
4745 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004746 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004747 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004748
Aaron Ballman68af21c2014-01-03 19:26:43 +00004749 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004750 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4751 return static_cast<Derived*>(this)->VisitCastExpr(E);
4752 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004753 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004754 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4755 return static_cast<Derived*>(this)->VisitCastExpr(E);
4756 }
4757
Aaron Ballman68af21c2014-01-03 19:26:43 +00004758 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004759 switch (E->getOpcode()) {
4760 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004761 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004762
4763 case BO_Comma:
4764 VisitIgnoredValue(E->getLHS());
4765 return StmtVisitorTy::Visit(E->getRHS());
4766
4767 case BO_PtrMemD:
4768 case BO_PtrMemI: {
4769 LValue Obj;
4770 if (!HandleMemberPointerAccess(Info, E, Obj))
4771 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004772 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004773 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004774 return false;
4775 return DerivedSuccess(Result, E);
4776 }
4777 }
4778 }
4779
Aaron Ballman68af21c2014-01-03 19:26:43 +00004780 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004781 // Evaluate and cache the common expression. We treat it as a temporary,
4782 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004783 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004784 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004785 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004786
Richard Smith17100ba2012-02-16 02:46:34 +00004787 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004788 }
4789
Aaron Ballman68af21c2014-01-03 19:26:43 +00004790 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004791 bool IsBcpCall = false;
4792 // If the condition (ignoring parens) is a __builtin_constant_p call,
4793 // the result is a constant expression if it can be folded without
4794 // side-effects. This is an important GNU extension. See GCC PR38377
4795 // for discussion.
4796 if (const CallExpr *CallCE =
4797 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004798 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004799 IsBcpCall = true;
4800
4801 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4802 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004803 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004804 return false;
4805
Richard Smith6d4c6582013-11-05 22:18:15 +00004806 FoldConstant Fold(Info, IsBcpCall);
4807 if (!HandleConditionalOperator(E)) {
4808 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004809 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004810 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004811
4812 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004813 }
4814
Aaron Ballman68af21c2014-01-03 19:26:43 +00004815 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004816 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004817 return DerivedSuccess(*Value, E);
4818
4819 const Expr *Source = E->getSourceExpr();
4820 if (!Source)
4821 return Error(E);
4822 if (Source == E) { // sanity checking.
4823 assert(0 && "OpaqueValueExpr recursively refers to itself");
4824 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004825 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004826 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004827 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004828
Aaron Ballman68af21c2014-01-03 19:26:43 +00004829 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004830 APValue Result;
4831 if (!handleCallExpr(E, Result, nullptr))
4832 return false;
4833 return DerivedSuccess(Result, E);
4834 }
4835
4836 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004837 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004838 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004839 QualType CalleeType = Callee->getType();
4840
Craig Topper36250ad2014-05-12 05:36:57 +00004841 const FunctionDecl *FD = nullptr;
4842 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004843 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004844 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004845
Richard Smithe97cbd72011-11-11 04:05:33 +00004846 // Extract function decl and 'this' pointer from the callee.
4847 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004848 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004849 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4850 // Explicit bound member calls, such as x.f() or p->g();
4851 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004852 return false;
4853 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004854 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004855 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004856 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4857 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004858 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4859 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004860 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004861 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004862 return Error(Callee);
4863
4864 FD = dyn_cast<FunctionDecl>(Member);
4865 if (!FD)
4866 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004867 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004868 LValue Call;
4869 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004870 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004871
Richard Smitha8105bc2012-01-06 16:39:00 +00004872 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004873 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004874 FD = dyn_cast_or_null<FunctionDecl>(
4875 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004876 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004877 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004878 // Don't call function pointers which have been cast to some other type.
4879 // Per DR (no number yet), the caller and callee can differ in noexcept.
4880 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4881 CalleeType->getPointeeType(), FD->getType())) {
4882 return Error(E);
4883 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004884
4885 // Overloaded operator calls to member functions are represented as normal
4886 // calls with '*this' as the first argument.
4887 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4888 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004889 // FIXME: When selecting an implicit conversion for an overloaded
4890 // operator delete, we sometimes try to evaluate calls to conversion
4891 // operators without a 'this' parameter!
4892 if (Args.empty())
4893 return Error(E);
4894
Nick Lewycky13073a62017-06-12 21:15:44 +00004895 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004896 return false;
4897 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004898 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004899 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004900 // Map the static invoker for the lambda back to the call operator.
4901 // Conveniently, we don't have to slice out the 'this' argument (as is
4902 // being done for the non-static case), since a static member function
4903 // doesn't have an implicit argument passed in.
4904 const CXXRecordDecl *ClosureClass = MD->getParent();
4905 assert(
4906 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4907 "Number of captures must be zero for conversion to function-ptr");
4908
4909 const CXXMethodDecl *LambdaCallOp =
4910 ClosureClass->getLambdaCallOperator();
4911
4912 // Set 'FD', the function that will be called below, to the call
4913 // operator. If the closure object represents a generic lambda, find
4914 // the corresponding specialization of the call operator.
4915
4916 if (ClosureClass->isGenericLambda()) {
4917 assert(MD->isFunctionTemplateSpecialization() &&
4918 "A generic lambda's static-invoker function must be a "
4919 "template specialization");
4920 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4921 FunctionTemplateDecl *CallOpTemplate =
4922 LambdaCallOp->getDescribedFunctionTemplate();
4923 void *InsertPos = nullptr;
4924 FunctionDecl *CorrespondingCallOpSpecialization =
4925 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4926 assert(CorrespondingCallOpSpecialization &&
4927 "We must always have a function call operator specialization "
4928 "that corresponds to our static invoker specialization");
4929 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4930 } else
4931 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004932 }
4933
Fangrui Song6907ce22018-07-30 19:24:48 +00004934
Richard Smithe97cbd72011-11-11 04:05:33 +00004935 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004936 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004937
Richard Smith47b34932012-02-01 02:39:43 +00004938 if (This && !This->checkSubobject(Info, E, CSK_This))
4939 return false;
4940
Richard Smith3607ffe2012-02-13 03:54:03 +00004941 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4942 // calls to such functions in constant expressions.
4943 if (This && !HasQualifier &&
4944 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4945 return Error(E, diag::note_constexpr_virtual_call);
4946
Craig Topper36250ad2014-05-12 05:36:57 +00004947 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004948 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004949
Nick Lewycky13073a62017-06-12 21:15:44 +00004950 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4951 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004952 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004953 return false;
4954
Richard Smith52a980a2015-08-28 02:43:42 +00004955 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004956 }
4957
Aaron Ballman68af21c2014-01-03 19:26:43 +00004958 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004959 return StmtVisitorTy::Visit(E->getInitializer());
4960 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004961 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004962 if (E->getNumInits() == 0)
4963 return DerivedZeroInitialization(E);
4964 if (E->getNumInits() == 1)
4965 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004966 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004967 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004968 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004969 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004970 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004971 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004972 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004973 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004974 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004975 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004976 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004977
Richard Smithd62306a2011-11-10 06:34:14 +00004978 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004979 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004980 assert(!E->isArrow() && "missing call to bound member function?");
4981
Richard Smith2e312c82012-03-03 22:46:17 +00004982 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004983 if (!Evaluate(Val, Info, E->getBase()))
4984 return false;
4985
4986 QualType BaseTy = E->getBase()->getType();
4987
4988 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004989 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004990 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004991 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004992 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4993
Richard Smith9defb7d2018-02-21 03:38:30 +00004994 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004995 SubobjectDesignator Designator(BaseTy);
4996 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004997
Richard Smith3229b742013-05-05 21:17:10 +00004998 APValue Result;
4999 return extractSubobject(Info, E, Obj, Designator, Result) &&
5000 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005001 }
5002
Aaron Ballman68af21c2014-01-03 19:26:43 +00005003 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005004 switch (E->getCastKind()) {
5005 default:
5006 break;
5007
Richard Smitha23ab512013-05-23 00:30:41 +00005008 case CK_AtomicToNonAtomic: {
5009 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005010 // This does not need to be done in place even for class/array types:
5011 // atomic-to-non-atomic conversion implies copying the object
5012 // representation.
5013 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005014 return false;
5015 return DerivedSuccess(AtomicVal, E);
5016 }
5017
Richard Smith11562c52011-10-28 17:51:58 +00005018 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005019 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005020 return StmtVisitorTy::Visit(E->getSubExpr());
5021
5022 case CK_LValueToRValue: {
5023 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005024 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5025 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005026 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005027 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005028 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005029 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005030 return false;
5031 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005032 }
5033 }
5034
Richard Smithf57d8cb2011-12-09 22:58:01 +00005035 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005036 }
5037
Aaron Ballman68af21c2014-01-03 19:26:43 +00005038 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005039 return VisitUnaryPostIncDec(UO);
5040 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005041 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005042 return VisitUnaryPostIncDec(UO);
5043 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005044 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005045 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005046 return Error(UO);
5047
5048 LValue LVal;
5049 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5050 return false;
5051 APValue RVal;
5052 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5053 UO->isIncrementOp(), &RVal))
5054 return false;
5055 return DerivedSuccess(RVal, UO);
5056 }
5057
Aaron Ballman68af21c2014-01-03 19:26:43 +00005058 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005059 // We will have checked the full-expressions inside the statement expression
5060 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005061 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005062 return Error(E);
5063
Richard Smith08d6a2c2013-07-24 07:11:57 +00005064 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005065 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005066 if (CS->body_empty())
5067 return true;
5068
Richard Smith51f03172013-06-20 03:00:05 +00005069 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5070 BE = CS->body_end();
5071 /**/; ++BI) {
5072 if (BI + 1 == BE) {
5073 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5074 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005075 Info.FFDiag((*BI)->getBeginLoc(),
5076 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005077 return false;
5078 }
5079 return this->Visit(FinalExpr);
5080 }
5081
5082 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005083 StmtResult Result = { ReturnValue, nullptr };
5084 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005085 if (ESR != ESR_Succeeded) {
5086 // FIXME: If the statement-expression terminated due to 'return',
5087 // 'break', or 'continue', it would be nice to propagate that to
5088 // the outer statement evaluation rather than bailing out.
5089 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005090 Info.FFDiag((*BI)->getBeginLoc(),
5091 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005092 return false;
5093 }
5094 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005095
5096 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005097 }
5098
Richard Smith4a678122011-10-24 18:44:57 +00005099 /// Visit a value which is evaluated, but whose value is ignored.
5100 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005101 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005102 }
David Majnemere9807b22016-02-26 04:23:19 +00005103
5104 /// Potentially visit a MemberExpr's base expression.
5105 void VisitIgnoredBaseExpression(const Expr *E) {
5106 // While MSVC doesn't evaluate the base expression, it does diagnose the
5107 // presence of side-effecting behavior.
5108 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5109 return;
5110 VisitIgnoredValue(E);
5111 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005112};
5113
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005114} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005115
5116//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005117// Common base class for lvalue and temporary evaluation.
5118//===----------------------------------------------------------------------===//
5119namespace {
5120template<class Derived>
5121class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005122 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005123protected:
5124 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005125 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005126 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005127 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005128
5129 bool Success(APValue::LValueBase B) {
5130 Result.set(B);
5131 return true;
5132 }
5133
George Burgess IVf9013bf2017-02-10 22:52:29 +00005134 bool evaluatePointer(const Expr *E, LValue &Result) {
5135 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5136 }
5137
Richard Smith027bf112011-11-17 22:56:20 +00005138public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005139 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5140 : ExprEvaluatorBaseTy(Info), Result(Result),
5141 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005142
Richard Smith2e312c82012-03-03 22:46:17 +00005143 bool Success(const APValue &V, const Expr *E) {
5144 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005145 return true;
5146 }
Richard Smith027bf112011-11-17 22:56:20 +00005147
Richard Smith027bf112011-11-17 22:56:20 +00005148 bool VisitMemberExpr(const MemberExpr *E) {
5149 // Handle non-static data members.
5150 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005151 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005152 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005153 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005154 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005155 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005156 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005157 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005158 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005159 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005160 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005161 BaseTy = E->getBase()->getType();
5162 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005163 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005164 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005165 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005166 Result.setInvalid(E);
5167 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005168 }
Richard Smith027bf112011-11-17 22:56:20 +00005169
Richard Smith1b78b3d2012-01-25 22:15:11 +00005170 const ValueDecl *MD = E->getMemberDecl();
5171 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5172 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5173 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5174 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005175 if (!HandleLValueMember(this->Info, E, Result, FD))
5176 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005177 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005178 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5179 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005180 } else
5181 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005182
Richard Smith1b78b3d2012-01-25 22:15:11 +00005183 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005184 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005185 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005186 RefValue))
5187 return false;
5188 return Success(RefValue, E);
5189 }
5190 return true;
5191 }
5192
5193 bool VisitBinaryOperator(const BinaryOperator *E) {
5194 switch (E->getOpcode()) {
5195 default:
5196 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5197
5198 case BO_PtrMemD:
5199 case BO_PtrMemI:
5200 return HandleMemberPointerAccess(this->Info, E, Result);
5201 }
5202 }
5203
5204 bool VisitCastExpr(const CastExpr *E) {
5205 switch (E->getCastKind()) {
5206 default:
5207 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5208
5209 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005210 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005211 if (!this->Visit(E->getSubExpr()))
5212 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005213
5214 // Now figure out the necessary offset to add to the base LV to get from
5215 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005216 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5217 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005218 }
5219 }
5220};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005221}
Richard Smith027bf112011-11-17 22:56:20 +00005222
5223//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005224// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005225//
5226// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5227// function designators (in C), decl references to void objects (in C), and
5228// temporaries (if building with -Wno-address-of-temporary).
5229//
5230// LValue evaluation produces values comprising a base expression of one of the
5231// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005232// - Declarations
5233// * VarDecl
5234// * FunctionDecl
5235// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005236// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005237// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005238// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005239// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005240// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005241// * ObjCEncodeExpr
5242// * AddrLabelExpr
5243// * BlockExpr
5244// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005245// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005246// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005247// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005248// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5249// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005250// * A MaterializeTemporaryExpr that has static storage duration, with no
5251// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005252// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005253//===----------------------------------------------------------------------===//
5254namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005255class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005256 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005257public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005258 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5259 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005260
Richard Smith11562c52011-10-28 17:51:58 +00005261 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005262 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005263
Peter Collingbournee9200682011-05-13 03:29:01 +00005264 bool VisitDeclRefExpr(const DeclRefExpr *E);
5265 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005266 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005267 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5268 bool VisitMemberExpr(const MemberExpr *E);
5269 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5270 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005271 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005272 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005273 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5274 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005275 bool VisitUnaryReal(const UnaryOperator *E);
5276 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005277 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5278 return VisitUnaryPreIncDec(UO);
5279 }
5280 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5281 return VisitUnaryPreIncDec(UO);
5282 }
Richard Smith3229b742013-05-05 21:17:10 +00005283 bool VisitBinAssign(const BinaryOperator *BO);
5284 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005285
Peter Collingbournee9200682011-05-13 03:29:01 +00005286 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005287 switch (E->getCastKind()) {
5288 default:
Richard Smith027bf112011-11-17 22:56:20 +00005289 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005290
Eli Friedmance3e02a2011-10-11 00:13:24 +00005291 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005292 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005293 if (!Visit(E->getSubExpr()))
5294 return false;
5295 Result.Designator.setInvalid();
5296 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005297
Richard Smith027bf112011-11-17 22:56:20 +00005298 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005299 if (!Visit(E->getSubExpr()))
5300 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005301 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005302 }
5303 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005304};
5305} // end anonymous namespace
5306
Richard Smith11562c52011-10-28 17:51:58 +00005307/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005308/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005309/// * function designators in C, and
5310/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005311/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005312static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5313 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005314 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005315 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005316 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005317}
5318
Peter Collingbournee9200682011-05-13 03:29:01 +00005319bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005320 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005321 return Success(FD);
5322 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005323 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005324 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005325 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005326 return Error(E);
5327}
Richard Smith733237d2011-10-24 23:14:33 +00005328
Faisal Vali0528a312016-11-13 06:09:16 +00005329
Richard Smith11562c52011-10-28 17:51:58 +00005330bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005331
5332 // If we are within a lambda's call operator, check whether the 'VD' referred
5333 // to within 'E' actually represents a lambda-capture that maps to a
5334 // data-member/field within the closure object, and if so, evaluate to the
5335 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005336 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5337 isa<DeclRefExpr>(E) &&
5338 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5339 // We don't always have a complete capture-map when checking or inferring if
5340 // the function call operator meets the requirements of a constexpr function
5341 // - but we don't need to evaluate the captures to determine constexprness
5342 // (dcl.constexpr C++17).
5343 if (Info.checkingPotentialConstantExpression())
5344 return false;
5345
Faisal Vali051e3a22017-02-16 04:12:21 +00005346 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005347 // Start with 'Result' referring to the complete closure object...
5348 Result = *Info.CurrentCall->This;
5349 // ... then update it to refer to the field of the closure object
5350 // that represents the capture.
5351 if (!HandleLValueMember(Info, E, Result, FD))
5352 return false;
5353 // And if the field is of reference type, update 'Result' to refer to what
5354 // the field refers to.
5355 if (FD->getType()->isReferenceType()) {
5356 APValue RVal;
5357 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5358 RVal))
5359 return false;
5360 Result.setFrom(Info.Ctx, RVal);
5361 }
5362 return true;
5363 }
5364 }
Craig Topper36250ad2014-05-12 05:36:57 +00005365 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005366 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5367 // Only if a local variable was declared in the function currently being
5368 // evaluated, do we expect to be able to find its value in the current
5369 // frame. (Otherwise it was likely declared in an enclosing context and
5370 // could either have a valid evaluatable value (for e.g. a constexpr
5371 // variable) or be ill-formed (and trigger an appropriate evaluation
5372 // diagnostic)).
5373 if (Info.CurrentCall->Callee &&
5374 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5375 Frame = Info.CurrentCall;
5376 }
5377 }
Richard Smith3229b742013-05-05 21:17:10 +00005378
Richard Smithfec09922011-11-01 16:57:24 +00005379 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005380 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005381 Result.set({VD, Frame->Index,
5382 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005383 return true;
5384 }
Richard Smithce40ad62011-11-12 22:28:03 +00005385 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005386 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005387
Richard Smith3229b742013-05-05 21:17:10 +00005388 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005389 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005390 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005391 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005392 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005393 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005394 return false;
5395 }
Richard Smith3229b742013-05-05 21:17:10 +00005396 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005397}
5398
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005399bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5400 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005401 // Walk through the expression to find the materialized temporary itself.
5402 SmallVector<const Expr *, 2> CommaLHSs;
5403 SmallVector<SubobjectAdjustment, 2> Adjustments;
5404 const Expr *Inner = E->GetTemporaryExpr()->
5405 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005406
Richard Smith84401042013-06-03 05:03:02 +00005407 // If we passed any comma operators, evaluate their LHSs.
5408 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5409 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5410 return false;
5411
Richard Smithe6c01442013-06-05 00:46:14 +00005412 // A materialized temporary with static storage duration can appear within the
5413 // result of a constant expression evaluation, so we need to preserve its
5414 // value for use outside this evaluation.
5415 APValue *Value;
5416 if (E->getStorageDuration() == SD_Static) {
5417 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005418 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005419 Result.set(E);
5420 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005421 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5422 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005423 }
5424
Richard Smithea4ad5d2013-06-06 08:19:16 +00005425 QualType Type = Inner->getType();
5426
Richard Smith84401042013-06-03 05:03:02 +00005427 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005428 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5429 (E->getStorageDuration() == SD_Static &&
5430 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5431 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005432 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005433 }
Richard Smith84401042013-06-03 05:03:02 +00005434
5435 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005436 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5437 --I;
5438 switch (Adjustments[I].Kind) {
5439 case SubobjectAdjustment::DerivedToBaseAdjustment:
5440 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5441 Type, Result))
5442 return false;
5443 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5444 break;
5445
5446 case SubobjectAdjustment::FieldAdjustment:
5447 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5448 return false;
5449 Type = Adjustments[I].Field->getType();
5450 break;
5451
5452 case SubobjectAdjustment::MemberPointerAdjustment:
5453 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5454 Adjustments[I].Ptr.RHS))
5455 return false;
5456 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5457 break;
5458 }
5459 }
5460
5461 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005462}
5463
Peter Collingbournee9200682011-05-13 03:29:01 +00005464bool
5465LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005466 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5467 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005468 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5469 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005470 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005471}
5472
Richard Smith6e525142011-12-27 12:18:28 +00005473bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005474 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005475 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005476
Faisal Valie690b7a2016-07-02 22:34:24 +00005477 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005478 << E->getExprOperand()->getType()
5479 << E->getExprOperand()->getSourceRange();
5480 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005481}
5482
Francois Pichet0066db92012-04-16 04:08:35 +00005483bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5484 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005485}
Francois Pichet0066db92012-04-16 04:08:35 +00005486
Peter Collingbournee9200682011-05-13 03:29:01 +00005487bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005488 // Handle static data members.
5489 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005490 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005491 return VisitVarDecl(E, VD);
5492 }
5493
Richard Smith254a73d2011-10-28 22:34:42 +00005494 // Handle static member functions.
5495 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5496 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005497 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005498 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005499 }
5500 }
5501
Richard Smithd62306a2011-11-10 06:34:14 +00005502 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005503 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005504}
5505
Peter Collingbournee9200682011-05-13 03:29:01 +00005506bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005507 // FIXME: Deal with vectors as array subscript bases.
5508 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005509 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005510
Nick Lewyckyad888682017-04-27 07:27:36 +00005511 bool Success = true;
5512 if (!evaluatePointer(E->getBase(), Result)) {
5513 if (!Info.noteFailure())
5514 return false;
5515 Success = false;
5516 }
Mike Stump11289f42009-09-09 15:08:12 +00005517
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005518 APSInt Index;
5519 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005520 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005521
Nick Lewyckyad888682017-04-27 07:27:36 +00005522 return Success &&
5523 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005524}
Eli Friedman9a156e52008-11-12 09:44:48 +00005525
Peter Collingbournee9200682011-05-13 03:29:01 +00005526bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005527 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005528}
5529
Richard Smith66c96992012-02-18 22:04:06 +00005530bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5531 if (!Visit(E->getSubExpr()))
5532 return false;
5533 // __real is a no-op on scalar lvalues.
5534 if (E->getSubExpr()->getType()->isAnyComplexType())
5535 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5536 return true;
5537}
5538
5539bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5540 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5541 "lvalue __imag__ on scalar?");
5542 if (!Visit(E->getSubExpr()))
5543 return false;
5544 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5545 return true;
5546}
5547
Richard Smith243ef902013-05-05 23:31:59 +00005548bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005549 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005550 return Error(UO);
5551
5552 if (!this->Visit(UO->getSubExpr()))
5553 return false;
5554
Richard Smith243ef902013-05-05 23:31:59 +00005555 return handleIncDec(
5556 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005557 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005558}
5559
5560bool LValueExprEvaluator::VisitCompoundAssignOperator(
5561 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005562 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005563 return Error(CAO);
5564
Richard Smith3229b742013-05-05 21:17:10 +00005565 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005566
5567 // The overall lvalue result is the result of evaluating the LHS.
5568 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005569 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005570 Evaluate(RHS, this->Info, CAO->getRHS());
5571 return false;
5572 }
5573
Richard Smith3229b742013-05-05 21:17:10 +00005574 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5575 return false;
5576
Richard Smith43e77732013-05-07 04:50:00 +00005577 return handleCompoundAssignment(
5578 this->Info, CAO,
5579 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5580 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005581}
5582
5583bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005584 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005585 return Error(E);
5586
Richard Smith3229b742013-05-05 21:17:10 +00005587 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005588
5589 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005590 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005591 Evaluate(NewVal, this->Info, E->getRHS());
5592 return false;
5593 }
5594
Richard Smith3229b742013-05-05 21:17:10 +00005595 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5596 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005597
5598 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005599 NewVal);
5600}
5601
Eli Friedman9a156e52008-11-12 09:44:48 +00005602//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005603// Pointer Evaluation
5604//===----------------------------------------------------------------------===//
5605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005607/// returned by a function with the alloc_size attribute. Returns true if we
5608/// were successful. Places an unsigned number into `Result`.
5609///
5610/// This expects the given CallExpr to be a call to a function with an
5611/// alloc_size attribute.
5612static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5613 const CallExpr *Call,
5614 llvm::APInt &Result) {
5615 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5616
Joel E. Denny81508102018-03-13 14:51:22 +00005617 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5618 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005619 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5620 if (Call->getNumArgs() <= SizeArgNo)
5621 return false;
5622
5623 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5624 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5625 return false;
5626 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5627 return false;
5628 Into = Into.zextOrSelf(BitsInSizeT);
5629 return true;
5630 };
5631
5632 APSInt SizeOfElem;
5633 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5634 return false;
5635
Joel E. Denny81508102018-03-13 14:51:22 +00005636 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005637 Result = std::move(SizeOfElem);
5638 return true;
5639 }
5640
5641 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005642 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005643 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5644 return false;
5645
5646 bool Overflow;
5647 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5648 if (Overflow)
5649 return false;
5650
5651 Result = std::move(BytesAvailable);
5652 return true;
5653}
5654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005655/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005656/// function.
5657static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5658 const LValue &LVal,
5659 llvm::APInt &Result) {
5660 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5661 "Can't get the size of a non alloc_size function");
5662 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5663 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5664 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5665}
5666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005667/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005668/// a function with the alloc_size attribute. If it was possible to do so, this
5669/// function will return true, make Result's Base point to said function call,
5670/// and mark Result's Base as invalid.
5671static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5672 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005673 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005674 return false;
5675
5676 // Because we do no form of static analysis, we only support const variables.
5677 //
5678 // Additionally, we can't support parameters, nor can we support static
5679 // variables (in the latter case, use-before-assign isn't UB; in the former,
5680 // we have no clue what they'll be assigned to).
5681 const auto *VD =
5682 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5683 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5684 return false;
5685
5686 const Expr *Init = VD->getAnyInitializer();
5687 if (!Init)
5688 return false;
5689
5690 const Expr *E = Init->IgnoreParens();
5691 if (!tryUnwrapAllocSizeCall(E))
5692 return false;
5693
5694 // Store E instead of E unwrapped so that the type of the LValue's base is
5695 // what the user wanted.
5696 Result.setInvalid(E);
5697
5698 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005699 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005700 return true;
5701}
5702
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005703namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005704class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005705 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005706 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005707 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005708
Peter Collingbournee9200682011-05-13 03:29:01 +00005709 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005710 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005711 return true;
5712 }
George Burgess IVe3763372016-12-22 02:50:20 +00005713
George Burgess IVf9013bf2017-02-10 22:52:29 +00005714 bool evaluateLValue(const Expr *E, LValue &Result) {
5715 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5716 }
5717
5718 bool evaluatePointer(const Expr *E, LValue &Result) {
5719 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5720 }
5721
George Burgess IVe3763372016-12-22 02:50:20 +00005722 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005723public:
Mike Stump11289f42009-09-09 15:08:12 +00005724
George Burgess IVf9013bf2017-02-10 22:52:29 +00005725 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5726 : ExprEvaluatorBaseTy(info), Result(Result),
5727 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005728
Richard Smith2e312c82012-03-03 22:46:17 +00005729 bool Success(const APValue &V, const Expr *E) {
5730 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005731 return true;
5732 }
Richard Smithfddd3842011-12-30 21:15:51 +00005733 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005734 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5735 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005736 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005737 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005738
John McCall45d55e42010-05-07 21:00:08 +00005739 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005740 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005741 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005742 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005743 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005744 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5745 if (Info.noteFailure())
5746 EvaluateIgnoredValue(Info, E->getSubExpr());
5747 return Error(E);
5748 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005749 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005750 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005751 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005752 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005753 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005754 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005755 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005756 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005757 }
Richard Smithd62306a2011-11-10 06:34:14 +00005758 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005759 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005760 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005761 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005762 if (!Info.CurrentCall->This) {
5763 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005764 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005765 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005766 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005767 return false;
5768 }
Richard Smithd62306a2011-11-10 06:34:14 +00005769 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005770 // If we are inside a lambda's call operator, the 'this' expression refers
5771 // to the enclosing '*this' object (either by value or reference) which is
5772 // either copied into the closure object's field that represents the '*this'
5773 // or refers to '*this'.
5774 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5775 // Update 'Result' to refer to the data member/field of the closure object
5776 // that represents the '*this' capture.
5777 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005778 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005779 return false;
5780 // If we captured '*this' by reference, replace the field with its referent.
5781 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5782 ->isPointerType()) {
5783 APValue RVal;
5784 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5785 RVal))
5786 return false;
5787
5788 Result.setFrom(Info.Ctx, RVal);
5789 }
5790 }
Richard Smithd62306a2011-11-10 06:34:14 +00005791 return true;
5792 }
John McCallc07a0c72011-02-17 10:25:35 +00005793
Eli Friedman449fe542009-03-23 04:56:01 +00005794 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005795};
Chris Lattner05706e882008-07-11 18:11:29 +00005796} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005797
George Burgess IVf9013bf2017-02-10 22:52:29 +00005798static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5799 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005800 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005801 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005802}
5803
John McCall45d55e42010-05-07 21:00:08 +00005804bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005805 if (E->getOpcode() != BO_Add &&
5806 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005807 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005808
Chris Lattner05706e882008-07-11 18:11:29 +00005809 const Expr *PExp = E->getLHS();
5810 const Expr *IExp = E->getRHS();
5811 if (IExp->getType()->isPointerType())
5812 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005813
George Burgess IVf9013bf2017-02-10 22:52:29 +00005814 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005815 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005817
John McCall45d55e42010-05-07 21:00:08 +00005818 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005819 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005820 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005821
Richard Smith96e0c102011-11-04 02:25:55 +00005822 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005823 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005824
Ted Kremenek28831752012-08-23 20:46:57 +00005825 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005826 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005827}
Eli Friedman9a156e52008-11-12 09:44:48 +00005828
John McCall45d55e42010-05-07 21:00:08 +00005829bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005830 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005831}
Mike Stump11289f42009-09-09 15:08:12 +00005832
Richard Smith81dfef92018-07-11 00:29:05 +00005833bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5834 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005835
Eli Friedman847a2bc2009-12-27 05:43:15 +00005836 switch (E->getCastKind()) {
5837 default:
5838 break;
5839
John McCalle3027922010-08-25 11:45:40 +00005840 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005841 case CK_CPointerToObjCPointerCast:
5842 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005843 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005844 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005845 if (!Visit(SubExpr))
5846 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005847 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5848 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5849 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005850 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005851 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005852 if (SubExpr->getType()->isVoidPointerType())
5853 CCEDiag(E, diag::note_constexpr_invalid_cast)
5854 << 3 << SubExpr->getType();
5855 else
5856 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5857 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005858 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5859 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005860 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005861
Anders Carlsson18275092010-10-31 20:41:46 +00005862 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005863 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005864 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005865 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005866 if (!Result.Base && Result.Offset.isZero())
5867 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005868
Richard Smithd62306a2011-11-10 06:34:14 +00005869 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005870 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005871 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5872 castAs<PointerType>()->getPointeeType(),
5873 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005874
Richard Smith027bf112011-11-17 22:56:20 +00005875 case CK_BaseToDerived:
5876 if (!Visit(E->getSubExpr()))
5877 return false;
5878 if (!Result.Base && Result.Offset.isZero())
5879 return true;
5880 return HandleBaseToDerivedCast(Info, E, Result);
5881
Richard Smith0b0a0b62011-10-29 20:57:55 +00005882 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005883 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005884 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005885
John McCalle3027922010-08-25 11:45:40 +00005886 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005887 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5888
Richard Smith2e312c82012-03-03 22:46:17 +00005889 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005890 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005891 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005892
John McCall45d55e42010-05-07 21:00:08 +00005893 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005894 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5895 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005896 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005897 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005898 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005899 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005900 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005901 return true;
5902 } else {
5903 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005904 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005905 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005906 }
5907 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005908
5909 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005910 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005911 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005912 return false;
5913 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005914 APValue &Value = createTemporary(SubExpr, false, Result,
5915 *Info.CurrentCall);
5916 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005917 return false;
5918 }
Richard Smith96e0c102011-11-04 02:25:55 +00005919 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005920 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5921 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005922 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005923 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005924 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005925 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005926 }
Richard Smithdd785442011-10-31 20:57:44 +00005927
John McCalle3027922010-08-25 11:45:40 +00005928 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005929 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005930
5931 case CK_LValueToRValue: {
5932 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005933 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005934 return false;
5935
5936 APValue RVal;
5937 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5938 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5939 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005940 return InvalidBaseOK &&
5941 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005942 return Success(RVal, E);
5943 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005944 }
5945
Richard Smith11562c52011-10-28 17:51:58 +00005946 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005947}
Chris Lattner05706e882008-07-11 18:11:29 +00005948
Hal Finkel0dd05d42014-10-03 17:18:37 +00005949static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5950 // C++ [expr.alignof]p3:
5951 // When alignof is applied to a reference type, the result is the
5952 // alignment of the referenced type.
5953 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5954 T = Ref->getPointeeType();
5955
5956 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005957 if (T.getQualifiers().hasUnaligned())
5958 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005959 return Info.Ctx.toCharUnitsFromBits(
5960 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5961}
5962
5963static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5964 E = E->IgnoreParens();
5965
5966 // The kinds of expressions that we have special-case logic here for
5967 // should be kept up to date with the special checks for those
5968 // expressions in Sema.
5969
5970 // alignof decl is always accepted, even if it doesn't make sense: we default
5971 // to 1 in those cases.
5972 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5973 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5974 /*RefAsPointee*/true);
5975
5976 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5977 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5978 /*RefAsPointee*/true);
5979
5980 return GetAlignOfType(Info, E->getType());
5981}
5982
George Burgess IVe3763372016-12-22 02:50:20 +00005983// To be clear: this happily visits unsupported builtins. Better name welcomed.
5984bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5985 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5986 return true;
5987
George Burgess IVf9013bf2017-02-10 22:52:29 +00005988 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005989 return false;
5990
5991 Result.setInvalid(E);
5992 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005993 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005994 return true;
5995}
5996
Peter Collingbournee9200682011-05-13 03:29:01 +00005997bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005998 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005999 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006000
Richard Smith6328cbd2016-11-16 00:57:23 +00006001 if (unsigned BuiltinOp = E->getBuiltinCallee())
6002 return VisitBuiltinCallExpr(E, BuiltinOp);
6003
George Burgess IVe3763372016-12-22 02:50:20 +00006004 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006005}
6006
6007bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6008 unsigned BuiltinOp) {
6009 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006010 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006011 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006012 case Builtin::BI__builtin_assume_aligned: {
6013 // We need to be very careful here because: if the pointer does not have the
6014 // asserted alignment, then the behavior is undefined, and undefined
6015 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006016 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006017 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006018
Hal Finkel0dd05d42014-10-03 17:18:37 +00006019 LValue OffsetResult(Result);
6020 APSInt Alignment;
6021 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6022 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006023 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006024
6025 if (E->getNumArgs() > 2) {
6026 APSInt Offset;
6027 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6028 return false;
6029
Richard Smith642a2362017-01-30 23:30:26 +00006030 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006031 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6032 }
6033
6034 // If there is a base object, then it must have the correct alignment.
6035 if (OffsetResult.Base) {
6036 CharUnits BaseAlignment;
6037 if (const ValueDecl *VD =
6038 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6039 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6040 } else {
6041 BaseAlignment =
6042 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
6043 }
6044
6045 if (BaseAlignment < Align) {
6046 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006047 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006048 CCEDiag(E->getArg(0),
6049 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006050 << (unsigned)BaseAlignment.getQuantity()
6051 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006052 return false;
6053 }
6054 }
6055
6056 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006057 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006058 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006059
Richard Smith642a2362017-01-30 23:30:26 +00006060 (OffsetResult.Base
6061 ? CCEDiag(E->getArg(0),
6062 diag::note_constexpr_baa_insufficient_alignment) << 1
6063 : CCEDiag(E->getArg(0),
6064 diag::note_constexpr_baa_value_insufficient_alignment))
6065 << (int)OffsetResult.Offset.getQuantity()
6066 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006067 return false;
6068 }
6069
6070 return true;
6071 }
Richard Smithe9507952016-11-12 01:39:56 +00006072
6073 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006074 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006075 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006076 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006077 if (Info.getLangOpts().CPlusPlus11)
6078 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6079 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006080 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006081 else
6082 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006083 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006084 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006085 case Builtin::BI__builtin_wcschr:
6086 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006087 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006088 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006089 if (!Visit(E->getArg(0)))
6090 return false;
6091 APSInt Desired;
6092 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6093 return false;
6094 uint64_t MaxLength = uint64_t(-1);
6095 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006096 BuiltinOp != Builtin::BIwcschr &&
6097 BuiltinOp != Builtin::BI__builtin_strchr &&
6098 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006099 APSInt N;
6100 if (!EvaluateInteger(E->getArg(2), N, Info))
6101 return false;
6102 MaxLength = N.getExtValue();
6103 }
6104
Richard Smith8110c9d2016-11-29 19:45:17 +00006105 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006106
Richard Smith8110c9d2016-11-29 19:45:17 +00006107 // Figure out what value we're actually looking for (after converting to
6108 // the corresponding unsigned type if necessary).
6109 uint64_t DesiredVal;
6110 bool StopAtNull = false;
6111 switch (BuiltinOp) {
6112 case Builtin::BIstrchr:
6113 case Builtin::BI__builtin_strchr:
6114 // strchr compares directly to the passed integer, and therefore
6115 // always fails if given an int that is not a char.
6116 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6117 E->getArg(1)->getType(),
6118 Desired),
6119 Desired))
6120 return ZeroInitialization(E);
6121 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006122 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006123 case Builtin::BImemchr:
6124 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006125 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006126 // memchr compares by converting both sides to unsigned char. That's also
6127 // correct for strchr if we get this far (to cope with plain char being
6128 // unsigned in the strchr case).
6129 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6130 break;
Richard Smithe9507952016-11-12 01:39:56 +00006131
Richard Smith8110c9d2016-11-29 19:45:17 +00006132 case Builtin::BIwcschr:
6133 case Builtin::BI__builtin_wcschr:
6134 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006135 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006136 case Builtin::BIwmemchr:
6137 case Builtin::BI__builtin_wmemchr:
6138 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6139 DesiredVal = Desired.getZExtValue();
6140 break;
6141 }
Richard Smithe9507952016-11-12 01:39:56 +00006142
6143 for (; MaxLength; --MaxLength) {
6144 APValue Char;
6145 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6146 !Char.isInt())
6147 return false;
6148 if (Char.getInt().getZExtValue() == DesiredVal)
6149 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006150 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006151 break;
6152 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6153 return false;
6154 }
6155 // Not found: return nullptr.
6156 return ZeroInitialization(E);
6157 }
6158
Richard Smith06f71b52018-08-04 00:57:17 +00006159 case Builtin::BImemcpy:
6160 case Builtin::BImemmove:
6161 case Builtin::BIwmemcpy:
6162 case Builtin::BIwmemmove:
6163 if (Info.getLangOpts().CPlusPlus11)
6164 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6165 << /*isConstexpr*/0 << /*isConstructor*/0
6166 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6167 else
6168 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6169 LLVM_FALLTHROUGH;
6170 case Builtin::BI__builtin_memcpy:
6171 case Builtin::BI__builtin_memmove:
6172 case Builtin::BI__builtin_wmemcpy:
6173 case Builtin::BI__builtin_wmemmove: {
6174 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6175 BuiltinOp == Builtin::BIwmemmove ||
6176 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6177 BuiltinOp == Builtin::BI__builtin_wmemmove;
6178 bool Move = BuiltinOp == Builtin::BImemmove ||
6179 BuiltinOp == Builtin::BIwmemmove ||
6180 BuiltinOp == Builtin::BI__builtin_memmove ||
6181 BuiltinOp == Builtin::BI__builtin_wmemmove;
6182
6183 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006184 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006185 return false;
6186 LValue Dest = Result;
6187
6188 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006189 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006190 return false;
6191
6192 APSInt N;
6193 if (!EvaluateInteger(E->getArg(2), N, Info))
6194 return false;
6195 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6196
6197 // If the size is zero, we treat this as always being a valid no-op.
6198 // (Even if one of the src and dest pointers is null.)
6199 if (!N)
6200 return true;
6201
Richard Smith128719c2018-09-13 22:47:33 +00006202 // Otherwise, if either of the operands is null, we can't proceed. Don't
6203 // try to determine the type of the copied objects, because there aren't
6204 // any.
6205 if (!Src.Base || !Dest.Base) {
6206 APValue Val;
6207 (!Src.Base ? Src : Dest).moveInto(Val);
6208 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6209 << Move << WChar << !!Src.Base
6210 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6211 return false;
6212 }
6213 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6214 return false;
6215
Richard Smith06f71b52018-08-04 00:57:17 +00006216 // We require that Src and Dest are both pointers to arrays of
6217 // trivially-copyable type. (For the wide version, the designator will be
6218 // invalid if the designated object is not a wchar_t.)
6219 QualType T = Dest.Designator.getType(Info.Ctx);
6220 QualType SrcT = Src.Designator.getType(Info.Ctx);
6221 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6222 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6223 return false;
6224 }
Petr Pavlued083f22018-10-04 09:25:44 +00006225 if (T->isIncompleteType()) {
6226 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6227 return false;
6228 }
Richard Smith06f71b52018-08-04 00:57:17 +00006229 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6230 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6231 return false;
6232 }
6233
6234 // Figure out how many T's we're copying.
6235 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6236 if (!WChar) {
6237 uint64_t Remainder;
6238 llvm::APInt OrigN = N;
6239 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6240 if (Remainder) {
6241 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6242 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6243 << (unsigned)TSize;
6244 return false;
6245 }
6246 }
6247
6248 // Check that the copying will remain within the arrays, just so that we
6249 // can give a more meaningful diagnostic. This implicitly also checks that
6250 // N fits into 64 bits.
6251 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6252 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6253 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6254 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6255 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6256 << N.toString(10, /*Signed*/false);
6257 return false;
6258 }
6259 uint64_t NElems = N.getZExtValue();
6260 uint64_t NBytes = NElems * TSize;
6261
6262 // Check for overlap.
6263 int Direction = 1;
6264 if (HasSameBase(Src, Dest)) {
6265 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6266 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6267 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6268 // Dest is inside the source region.
6269 if (!Move) {
6270 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6271 return false;
6272 }
6273 // For memmove and friends, copy backwards.
6274 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6275 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6276 return false;
6277 Direction = -1;
6278 } else if (!Move && SrcOffset >= DestOffset &&
6279 SrcOffset - DestOffset < NBytes) {
6280 // Src is inside the destination region for memcpy: invalid.
6281 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6282 return false;
6283 }
6284 }
6285
6286 while (true) {
6287 APValue Val;
6288 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6289 !handleAssignment(Info, E, Dest, T, Val))
6290 return false;
6291 // Do not iterate past the last element; if we're copying backwards, that
6292 // might take us off the start of the array.
6293 if (--NElems == 0)
6294 return true;
6295 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6296 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6297 return false;
6298 }
6299 }
6300
Richard Smith6cbd65d2013-07-11 02:27:57 +00006301 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006302 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006303 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006304}
Chris Lattner05706e882008-07-11 18:11:29 +00006305
6306//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006307// Member Pointer Evaluation
6308//===----------------------------------------------------------------------===//
6309
6310namespace {
6311class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006312 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006313 MemberPtr &Result;
6314
6315 bool Success(const ValueDecl *D) {
6316 Result = MemberPtr(D);
6317 return true;
6318 }
6319public:
6320
6321 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6322 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6323
Richard Smith2e312c82012-03-03 22:46:17 +00006324 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006325 Result.setFrom(V);
6326 return true;
6327 }
Richard Smithfddd3842011-12-30 21:15:51 +00006328 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006329 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006330 }
6331
6332 bool VisitCastExpr(const CastExpr *E);
6333 bool VisitUnaryAddrOf(const UnaryOperator *E);
6334};
6335} // end anonymous namespace
6336
6337static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6338 EvalInfo &Info) {
6339 assert(E->isRValue() && E->getType()->isMemberPointerType());
6340 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6341}
6342
6343bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6344 switch (E->getCastKind()) {
6345 default:
6346 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6347
6348 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006349 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006350 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006351
6352 case CK_BaseToDerivedMemberPointer: {
6353 if (!Visit(E->getSubExpr()))
6354 return false;
6355 if (E->path_empty())
6356 return true;
6357 // Base-to-derived member pointer casts store the path in derived-to-base
6358 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6359 // the wrong end of the derived->base arc, so stagger the path by one class.
6360 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6361 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6362 PathI != PathE; ++PathI) {
6363 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6364 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6365 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006366 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006367 }
6368 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6369 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006370 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006371 return true;
6372 }
6373
6374 case CK_DerivedToBaseMemberPointer:
6375 if (!Visit(E->getSubExpr()))
6376 return false;
6377 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6378 PathE = E->path_end(); PathI != PathE; ++PathI) {
6379 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6380 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6381 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006382 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006383 }
6384 return true;
6385 }
6386}
6387
6388bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6389 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6390 // member can be formed.
6391 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6392}
6393
6394//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006395// Record Evaluation
6396//===----------------------------------------------------------------------===//
6397
6398namespace {
6399 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006400 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006401 const LValue &This;
6402 APValue &Result;
6403 public:
6404
6405 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6406 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6407
Richard Smith2e312c82012-03-03 22:46:17 +00006408 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006409 Result = V;
6410 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006411 }
Richard Smithb8348f52016-05-12 22:16:28 +00006412 bool ZeroInitialization(const Expr *E) {
6413 return ZeroInitialization(E, E->getType());
6414 }
6415 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006416
Richard Smith52a980a2015-08-28 02:43:42 +00006417 bool VisitCallExpr(const CallExpr *E) {
6418 return handleCallExpr(E, Result, &This);
6419 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006420 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006421 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006422 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6423 return VisitCXXConstructExpr(E, E->getType());
6424 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006425 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006426 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006427 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006428 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006429
6430 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006431 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006432}
Richard Smithd62306a2011-11-10 06:34:14 +00006433
Richard Smithfddd3842011-12-30 21:15:51 +00006434/// Perform zero-initialization on an object of non-union class type.
6435/// C++11 [dcl.init]p5:
6436/// To zero-initialize an object or reference of type T means:
6437/// [...]
6438/// -- if T is a (possibly cv-qualified) non-union class type,
6439/// each non-static data member and each base-class subobject is
6440/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006441static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6442 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006443 const LValue &This, APValue &Result) {
6444 assert(!RD->isUnion() && "Expected non-union class type");
6445 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6446 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006447 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006448
John McCalld7bca762012-05-01 00:38:49 +00006449 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006450 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6451
6452 if (CD) {
6453 unsigned Index = 0;
6454 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006455 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006456 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6457 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006458 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6459 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006460 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006461 Result.getStructBase(Index)))
6462 return false;
6463 }
6464 }
6465
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006466 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006467 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006468 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006469 continue;
6470
6471 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006472 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006473 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006474
David Blaikie2d7c57e2012-04-30 02:36:29 +00006475 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006476 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006477 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006478 return false;
6479 }
6480
6481 return true;
6482}
6483
Richard Smithb8348f52016-05-12 22:16:28 +00006484bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6485 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006486 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006487 if (RD->isUnion()) {
6488 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6489 // object's first non-static named data member is zero-initialized
6490 RecordDecl::field_iterator I = RD->field_begin();
6491 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006492 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006493 return true;
6494 }
6495
6496 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006497 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006498 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006499 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006500 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006501 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006502 }
6503
Richard Smith5d108602012-02-17 00:44:16 +00006504 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006505 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006506 return false;
6507 }
6508
Richard Smitha8105bc2012-01-06 16:39:00 +00006509 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006510}
6511
Richard Smithe97cbd72011-11-11 04:05:33 +00006512bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6513 switch (E->getCastKind()) {
6514 default:
6515 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6516
6517 case CK_ConstructorConversion:
6518 return Visit(E->getSubExpr());
6519
6520 case CK_DerivedToBase:
6521 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006522 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006523 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006524 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006525 if (!DerivedObject.isStruct())
6526 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006527
6528 // Derived-to-base rvalue conversion: just slice off the derived part.
6529 APValue *Value = &DerivedObject;
6530 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6531 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6532 PathE = E->path_end(); PathI != PathE; ++PathI) {
6533 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6534 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6535 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6536 RD = Base;
6537 }
6538 Result = *Value;
6539 return true;
6540 }
6541 }
6542}
6543
Richard Smithd62306a2011-11-10 06:34:14 +00006544bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006545 if (E->isTransparent())
6546 return Visit(E->getInit(0));
6547
Richard Smithd62306a2011-11-10 06:34:14 +00006548 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006549 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006550 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6551
6552 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006553 const FieldDecl *Field = E->getInitializedFieldInUnion();
6554 Result = APValue(Field);
6555 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006556 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006557
6558 // If the initializer list for a union does not contain any elements, the
6559 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006560 // FIXME: The element should be initialized from an initializer list.
6561 // Is this difference ever observable for initializer lists which
6562 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006563 ImplicitValueInitExpr VIE(Field->getType());
6564 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6565
Richard Smithd62306a2011-11-10 06:34:14 +00006566 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006567 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6568 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006569
6570 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6571 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6572 isa<CXXDefaultInitExpr>(InitExpr));
6573
Richard Smithb228a862012-02-15 02:18:13 +00006574 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006575 }
6576
Richard Smith872307e2016-03-08 22:17:41 +00006577 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006578 if (Result.isUninit())
6579 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6580 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006581 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006582 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006583
6584 // Initialize base classes.
6585 if (CXXRD) {
6586 for (const auto &Base : CXXRD->bases()) {
6587 assert(ElementNo < E->getNumInits() && "missing init for base class");
6588 const Expr *Init = E->getInit(ElementNo);
6589
6590 LValue Subobject = This;
6591 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6592 return false;
6593
6594 APValue &FieldVal = Result.getStructBase(ElementNo);
6595 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006596 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006597 return false;
6598 Success = false;
6599 }
6600 ++ElementNo;
6601 }
6602 }
6603
6604 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006605 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006606 // Anonymous bit-fields are not considered members of the class for
6607 // purposes of aggregate initialization.
6608 if (Field->isUnnamedBitfield())
6609 continue;
6610
6611 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006612
Richard Smith253c2a32012-01-27 01:14:48 +00006613 bool HaveInit = ElementNo < E->getNumInits();
6614
6615 // FIXME: Diagnostics here should point to the end of the initializer
6616 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006617 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006618 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006619 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006620
6621 // Perform an implicit value-initialization for members beyond the end of
6622 // the initializer list.
6623 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006624 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006625
Richard Smith852c9db2013-04-20 22:23:05 +00006626 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6627 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6628 isa<CXXDefaultInitExpr>(Init));
6629
Richard Smith49ca8aa2013-08-06 07:09:20 +00006630 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6631 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6632 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006633 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006634 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006635 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006636 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006637 }
6638 }
6639
Richard Smith253c2a32012-01-27 01:14:48 +00006640 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006641}
6642
Richard Smithb8348f52016-05-12 22:16:28 +00006643bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6644 QualType T) {
6645 // Note that E's type is not necessarily the type of our class here; we might
6646 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006647 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006648 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6649
Richard Smithfddd3842011-12-30 21:15:51 +00006650 bool ZeroInit = E->requiresZeroInitialization();
6651 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006652 // If we've already performed zero-initialization, we're already done.
6653 if (!Result.isUninit())
6654 return true;
6655
Richard Smithda3f4fd2014-03-05 23:32:50 +00006656 // We can get here in two different ways:
6657 // 1) We're performing value-initialization, and should zero-initialize
6658 // the object, or
6659 // 2) We're performing default-initialization of an object with a trivial
6660 // constexpr default constructor, in which case we should start the
6661 // lifetimes of all the base subobjects (there can be no data member
6662 // subobjects in this case) per [basic.life]p1.
6663 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006664 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006665 }
6666
Craig Topper36250ad2014-05-12 05:36:57 +00006667 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006668 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006669
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006670 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006671 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006672
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006673 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006674 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006675 if (const MaterializeTemporaryExpr *ME
6676 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6677 return Visit(ME->GetTemporaryExpr());
6678
Richard Smithb8348f52016-05-12 22:16:28 +00006679 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006680 return false;
6681
Craig Topper5fc8fc22014-08-27 06:28:36 +00006682 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006683 return HandleConstructorCall(E, This, Args,
6684 cast<CXXConstructorDecl>(Definition), Info,
6685 Result);
6686}
6687
6688bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6689 const CXXInheritedCtorInitExpr *E) {
6690 if (!Info.CurrentCall) {
6691 assert(Info.checkingPotentialConstantExpression());
6692 return false;
6693 }
6694
6695 const CXXConstructorDecl *FD = E->getConstructor();
6696 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6697 return false;
6698
6699 const FunctionDecl *Definition = nullptr;
6700 auto Body = FD->getBody(Definition);
6701
6702 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6703 return false;
6704
6705 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006706 cast<CXXConstructorDecl>(Definition), Info,
6707 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006708}
6709
Richard Smithcc1b96d2013-06-12 22:31:48 +00006710bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6711 const CXXStdInitializerListExpr *E) {
6712 const ConstantArrayType *ArrayType =
6713 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6714
6715 LValue Array;
6716 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6717 return false;
6718
6719 // Get a pointer to the first element of the array.
6720 Array.addArray(Info, E, ArrayType);
6721
6722 // FIXME: Perform the checks on the field types in SemaInit.
6723 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6724 RecordDecl::field_iterator Field = Record->field_begin();
6725 if (Field == Record->field_end())
6726 return Error(E);
6727
6728 // Start pointer.
6729 if (!Field->getType()->isPointerType() ||
6730 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6731 ArrayType->getElementType()))
6732 return Error(E);
6733
6734 // FIXME: What if the initializer_list type has base classes, etc?
6735 Result = APValue(APValue::UninitStruct(), 0, 2);
6736 Array.moveInto(Result.getStructField(0));
6737
6738 if (++Field == Record->field_end())
6739 return Error(E);
6740
6741 if (Field->getType()->isPointerType() &&
6742 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6743 ArrayType->getElementType())) {
6744 // End pointer.
6745 if (!HandleLValueArrayAdjustment(Info, E, Array,
6746 ArrayType->getElementType(),
6747 ArrayType->getSize().getZExtValue()))
6748 return false;
6749 Array.moveInto(Result.getStructField(1));
6750 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6751 // Length.
6752 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6753 else
6754 return Error(E);
6755
6756 if (++Field != Record->field_end())
6757 return Error(E);
6758
6759 return true;
6760}
6761
Faisal Valic72a08c2017-01-09 03:02:53 +00006762bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6763 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6764 if (ClosureClass->isInvalidDecl()) return false;
6765
6766 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006767
Faisal Vali051e3a22017-02-16 04:12:21 +00006768 const size_t NumFields =
6769 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006770
6771 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6772 E->capture_init_end()) &&
6773 "The number of lambda capture initializers should equal the number of "
6774 "fields within the closure type");
6775
Faisal Vali051e3a22017-02-16 04:12:21 +00006776 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6777 // Iterate through all the lambda's closure object's fields and initialize
6778 // them.
6779 auto *CaptureInitIt = E->capture_init_begin();
6780 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6781 bool Success = true;
6782 for (const auto *Field : ClosureClass->fields()) {
6783 assert(CaptureInitIt != E->capture_init_end());
6784 // Get the initializer for this field
6785 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006786
Faisal Vali051e3a22017-02-16 04:12:21 +00006787 // If there is no initializer, either this is a VLA or an error has
6788 // occurred.
6789 if (!CurFieldInit)
6790 return Error(E);
6791
6792 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6793 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6794 if (!Info.keepEvaluatingAfterFailure())
6795 return false;
6796 Success = false;
6797 }
6798 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006799 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006800 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006801}
6802
Richard Smithd62306a2011-11-10 06:34:14 +00006803static bool EvaluateRecord(const Expr *E, const LValue &This,
6804 APValue &Result, EvalInfo &Info) {
6805 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006806 "can't evaluate expression as a record rvalue");
6807 return RecordExprEvaluator(Info, This, Result).Visit(E);
6808}
6809
6810//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006811// Temporary Evaluation
6812//
6813// Temporaries are represented in the AST as rvalues, but generally behave like
6814// lvalues. The full-object of which the temporary is a subobject is implicitly
6815// materialized so that a reference can bind to it.
6816//===----------------------------------------------------------------------===//
6817namespace {
6818class TemporaryExprEvaluator
6819 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6820public:
6821 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006822 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006823
6824 /// Visit an expression which constructs the value of this temporary.
6825 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006826 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6827 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006828 }
6829
6830 bool VisitCastExpr(const CastExpr *E) {
6831 switch (E->getCastKind()) {
6832 default:
6833 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6834
6835 case CK_ConstructorConversion:
6836 return VisitConstructExpr(E->getSubExpr());
6837 }
6838 }
6839 bool VisitInitListExpr(const InitListExpr *E) {
6840 return VisitConstructExpr(E);
6841 }
6842 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6843 return VisitConstructExpr(E);
6844 }
6845 bool VisitCallExpr(const CallExpr *E) {
6846 return VisitConstructExpr(E);
6847 }
Richard Smith513955c2014-12-17 19:24:30 +00006848 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6849 return VisitConstructExpr(E);
6850 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006851 bool VisitLambdaExpr(const LambdaExpr *E) {
6852 return VisitConstructExpr(E);
6853 }
Richard Smith027bf112011-11-17 22:56:20 +00006854};
6855} // end anonymous namespace
6856
6857/// Evaluate an expression of record type as a temporary.
6858static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006859 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006860 return TemporaryExprEvaluator(Info, Result).Visit(E);
6861}
6862
6863//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006864// Vector Evaluation
6865//===----------------------------------------------------------------------===//
6866
6867namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006868 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006869 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006870 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006871 public:
Mike Stump11289f42009-09-09 15:08:12 +00006872
Richard Smith2d406342011-10-22 21:10:00 +00006873 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6874 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006875
Craig Topper9798b932015-09-29 04:30:05 +00006876 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006877 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6878 // FIXME: remove this APValue copy.
6879 Result = APValue(V.data(), V.size());
6880 return true;
6881 }
Richard Smith2e312c82012-03-03 22:46:17 +00006882 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006883 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006884 Result = V;
6885 return true;
6886 }
Richard Smithfddd3842011-12-30 21:15:51 +00006887 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006888
Richard Smith2d406342011-10-22 21:10:00 +00006889 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006890 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006891 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006892 bool VisitInitListExpr(const InitListExpr *E);
6893 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006894 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006895 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006896 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006897 };
6898} // end anonymous namespace
6899
6900static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006901 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006902 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006903}
6904
George Burgess IV533ff002015-12-11 00:23:35 +00006905bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006906 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006907 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006908
Richard Smith161f09a2011-12-06 22:44:34 +00006909 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006910 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006911
Eli Friedmanc757de22011-03-25 00:43:55 +00006912 switch (E->getCastKind()) {
6913 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006914 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006915 if (SETy->isIntegerType()) {
6916 APSInt IntResult;
6917 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006918 return false;
6919 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006920 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006921 APFloat FloatResult(0.0);
6922 if (!EvaluateFloat(SE, FloatResult, Info))
6923 return false;
6924 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006925 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006926 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006927 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006928
6929 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006930 SmallVector<APValue, 4> Elts(NElts, Val);
6931 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006932 }
Eli Friedman803acb32011-12-22 03:51:45 +00006933 case CK_BitCast: {
6934 // Evaluate the operand into an APInt we can extract from.
6935 llvm::APInt SValInt;
6936 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6937 return false;
6938 // Extract the elements
6939 QualType EltTy = VTy->getElementType();
6940 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6941 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6942 SmallVector<APValue, 4> Elts;
6943 if (EltTy->isRealFloatingType()) {
6944 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006945 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006946 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006947 FloatEltSize = 80;
6948 for (unsigned i = 0; i < NElts; i++) {
6949 llvm::APInt Elt;
6950 if (BigEndian)
6951 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6952 else
6953 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006954 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006955 }
6956 } else if (EltTy->isIntegerType()) {
6957 for (unsigned i = 0; i < NElts; i++) {
6958 llvm::APInt Elt;
6959 if (BigEndian)
6960 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6961 else
6962 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6963 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6964 }
6965 } else {
6966 return Error(E);
6967 }
6968 return Success(Elts, E);
6969 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006970 default:
Richard Smith11562c52011-10-28 17:51:58 +00006971 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006972 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006973}
6974
Richard Smith2d406342011-10-22 21:10:00 +00006975bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006976VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006977 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006978 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006979 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006980
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006981 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006982 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006983
Eli Friedmanb9c71292012-01-03 23:24:20 +00006984 // The number of initializers can be less than the number of
6985 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00006986 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006987 // should be initialized with zeroes.
6988 unsigned CountInits = 0, CountElts = 0;
6989 while (CountElts < NumElements) {
6990 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00006991 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006992 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006993 APValue v;
6994 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6995 return Error(E);
6996 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00006997 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006998 Elements.push_back(v.getVectorElt(j));
6999 CountElts += vlen;
7000 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007001 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007002 if (CountInits < NumInits) {
7003 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007004 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007005 } else // trailing integer zero.
7006 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7007 Elements.push_back(APValue(sInt));
7008 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007009 } else {
7010 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007011 if (CountInits < NumInits) {
7012 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007013 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007014 } else // trailing float zero.
7015 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7016 Elements.push_back(APValue(f));
7017 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007018 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007019 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007020 }
Richard Smith2d406342011-10-22 21:10:00 +00007021 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007022}
7023
Richard Smith2d406342011-10-22 21:10:00 +00007024bool
Richard Smithfddd3842011-12-30 21:15:51 +00007025VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007026 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007027 QualType EltTy = VT->getElementType();
7028 APValue ZeroElement;
7029 if (EltTy->isIntegerType())
7030 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7031 else
7032 ZeroElement =
7033 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7034
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007035 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007036 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007037}
7038
Richard Smith2d406342011-10-22 21:10:00 +00007039bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007040 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007041 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007042}
7043
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007044//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007045// Array Evaluation
7046//===----------------------------------------------------------------------===//
7047
7048namespace {
7049 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007050 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007051 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007052 APValue &Result;
7053 public:
7054
Richard Smithd62306a2011-11-10 06:34:14 +00007055 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7056 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007057
7058 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00007059 assert((V.isArray() || V.isLValue()) &&
7060 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00007061 Result = V;
7062 return true;
7063 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007064
Richard Smithfddd3842011-12-30 21:15:51 +00007065 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007066 const ConstantArrayType *CAT =
7067 Info.Ctx.getAsConstantArrayType(E->getType());
7068 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007069 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007070
7071 Result = APValue(APValue::UninitArray(), 0,
7072 CAT->getSize().getZExtValue());
7073 if (!Result.hasArrayFiller()) return true;
7074
Richard Smithfddd3842011-12-30 21:15:51 +00007075 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007076 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007077 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007078 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007079 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007080 }
7081
Richard Smith52a980a2015-08-28 02:43:42 +00007082 bool VisitCallExpr(const CallExpr *E) {
7083 return handleCallExpr(E, Result, &This);
7084 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007085 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007086 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007087 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007088 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7089 const LValue &Subobject,
7090 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00007091 };
7092} // end anonymous namespace
7093
Richard Smithd62306a2011-11-10 06:34:14 +00007094static bool EvaluateArray(const Expr *E, const LValue &This,
7095 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007096 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007097 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007098}
7099
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007100// Return true iff the given array filler may depend on the element index.
7101static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7102 // For now, just whitelist non-class value-initialization and initialization
7103 // lists comprised of them.
7104 if (isa<ImplicitValueInitExpr>(FillerExpr))
7105 return false;
7106 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7107 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7108 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7109 return true;
7110 }
7111 return false;
7112 }
7113 return true;
7114}
7115
Richard Smithf3e9e432011-11-07 09:22:26 +00007116bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7117 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7118 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007119 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007120
Richard Smithca2cfbf2011-12-22 01:07:19 +00007121 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7122 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00007123 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00007124 LValue LV;
7125 if (!EvaluateLValue(E->getInit(0), LV, Info))
7126 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007127 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00007128 LV.moveInto(Val);
7129 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00007130 }
7131
Richard Smith253c2a32012-01-27 01:14:48 +00007132 bool Success = true;
7133
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007134 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7135 "zero-initialized array shouldn't have any initialized elts");
7136 APValue Filler;
7137 if (Result.isArray() && Result.hasArrayFiller())
7138 Filler = Result.getArrayFiller();
7139
Richard Smith9543c5e2013-04-22 14:44:29 +00007140 unsigned NumEltsToInit = E->getNumInits();
7141 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007142 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007143
7144 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007145 // array element.
7146 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007147 NumEltsToInit = NumElts;
7148
Nicola Zaghen3538b392018-05-15 13:30:56 +00007149 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7150 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007151
Richard Smith9543c5e2013-04-22 14:44:29 +00007152 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007153
7154 // If the array was previously zero-initialized, preserve the
7155 // zero-initialized values.
7156 if (!Filler.isUninit()) {
7157 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7158 Result.getArrayInitializedElt(I) = Filler;
7159 if (Result.hasArrayFiller())
7160 Result.getArrayFiller() = Filler;
7161 }
7162
Richard Smithd62306a2011-11-10 06:34:14 +00007163 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007164 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007165 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7166 const Expr *Init =
7167 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007168 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007169 Info, Subobject, Init) ||
7170 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007171 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007172 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007173 return false;
7174 Success = false;
7175 }
Richard Smithd62306a2011-11-10 06:34:14 +00007176 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007177
Richard Smith9543c5e2013-04-22 14:44:29 +00007178 if (!Result.hasArrayFiller())
7179 return Success;
7180
7181 // If we get here, we have a trivial filler, which we can just evaluate
7182 // once and splat over the rest of the array elements.
7183 assert(FillerExpr && "no array filler for incomplete init list");
7184 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7185 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007186}
7187
Richard Smith410306b2016-12-12 02:53:20 +00007188bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7189 if (E->getCommonExpr() &&
7190 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7191 Info, E->getCommonExpr()->getSourceExpr()))
7192 return false;
7193
7194 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7195
7196 uint64_t Elements = CAT->getSize().getZExtValue();
7197 Result = APValue(APValue::UninitArray(), Elements, Elements);
7198
7199 LValue Subobject = This;
7200 Subobject.addArray(Info, E, CAT);
7201
7202 bool Success = true;
7203 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7204 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7205 Info, Subobject, E->getSubExpr()) ||
7206 !HandleLValueArrayAdjustment(Info, E, Subobject,
7207 CAT->getElementType(), 1)) {
7208 if (!Info.noteFailure())
7209 return false;
7210 Success = false;
7211 }
7212 }
7213
7214 return Success;
7215}
7216
Richard Smith027bf112011-11-17 22:56:20 +00007217bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007218 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7219}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007220
Richard Smith9543c5e2013-04-22 14:44:29 +00007221bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7222 const LValue &Subobject,
7223 APValue *Value,
7224 QualType Type) {
7225 bool HadZeroInit = !Value->isUninit();
7226
7227 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7228 unsigned N = CAT->getSize().getZExtValue();
7229
7230 // Preserve the array filler if we had prior zero-initialization.
7231 APValue Filler =
7232 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7233 : APValue();
7234
7235 *Value = APValue(APValue::UninitArray(), N, N);
7236
7237 if (HadZeroInit)
7238 for (unsigned I = 0; I != N; ++I)
7239 Value->getArrayInitializedElt(I) = Filler;
7240
7241 // Initialize the elements.
7242 LValue ArrayElt = Subobject;
7243 ArrayElt.addArray(Info, E, CAT);
7244 for (unsigned I = 0; I != N; ++I)
7245 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7246 CAT->getElementType()) ||
7247 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7248 CAT->getElementType(), 1))
7249 return false;
7250
7251 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007252 }
Richard Smith027bf112011-11-17 22:56:20 +00007253
Richard Smith9543c5e2013-04-22 14:44:29 +00007254 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007255 return Error(E);
7256
Richard Smithb8348f52016-05-12 22:16:28 +00007257 return RecordExprEvaluator(Info, Subobject, *Value)
7258 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007259}
7260
Richard Smithf3e9e432011-11-07 09:22:26 +00007261//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007262// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007263//
7264// As a GNU extension, we support casting pointers to sufficiently-wide integer
7265// types and back in constant folding. Integer values are thus represented
7266// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007267//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007268
7269namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007270class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007271 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007272 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007273public:
Richard Smith2e312c82012-03-03 22:46:17 +00007274 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007275 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007276
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007277 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007278 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007279 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007280 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007281 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007282 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007283 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007284 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007285 return true;
7286 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007287 bool Success(const llvm::APSInt &SI, const Expr *E) {
7288 return Success(SI, E, Result);
7289 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007290
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007291 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007292 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007293 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007294 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007295 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007296 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007297 Result.getInt().setIsUnsigned(
7298 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007299 return true;
7300 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007301 bool Success(const llvm::APInt &I, const Expr *E) {
7302 return Success(I, E, Result);
7303 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007304
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007305 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007306 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007307 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007308 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007309 return true;
7310 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007311 bool Success(uint64_t Value, const Expr *E) {
7312 return Success(Value, E, Result);
7313 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007314
Ken Dyckdbc01912011-03-11 02:13:43 +00007315 bool Success(CharUnits Size, const Expr *E) {
7316 return Success(Size.getQuantity(), E);
7317 }
7318
Richard Smith2e312c82012-03-03 22:46:17 +00007319 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007320 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007321 Result = V;
7322 return true;
7323 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007324 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007325 }
Mike Stump11289f42009-09-09 15:08:12 +00007326
Richard Smithfddd3842011-12-30 21:15:51 +00007327 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007328
Peter Collingbournee9200682011-05-13 03:29:01 +00007329 //===--------------------------------------------------------------------===//
7330 // Visitor Methods
7331 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007332
Chris Lattner7174bf32008-07-12 00:38:25 +00007333 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007334 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007335 }
7336 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007337 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007338 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007339
7340 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7341 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007342 if (CheckReferencedDecl(E, E->getDecl()))
7343 return true;
7344
7345 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007346 }
7347 bool VisitMemberExpr(const MemberExpr *E) {
7348 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007349 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007350 return true;
7351 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007352
7353 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007354 }
7355
Peter Collingbournee9200682011-05-13 03:29:01 +00007356 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007357 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007358 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007359 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007360 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007361
Peter Collingbournee9200682011-05-13 03:29:01 +00007362 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007363 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007364
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007365 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007366 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007367 }
Mike Stump11289f42009-09-09 15:08:12 +00007368
Ted Kremeneke65b0862012-03-06 20:05:56 +00007369 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7370 return Success(E->getValue(), E);
7371 }
Richard Smith410306b2016-12-12 02:53:20 +00007372
7373 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7374 if (Info.ArrayInitIndex == uint64_t(-1)) {
7375 // We were asked to evaluate this subexpression independent of the
7376 // enclosing ArrayInitLoopExpr. We can't do that.
7377 Info.FFDiag(E);
7378 return false;
7379 }
7380 return Success(Info.ArrayInitIndex, E);
7381 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007382
Richard Smith4ce706a2011-10-11 21:43:33 +00007383 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007384 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007385 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007386 }
7387
Douglas Gregor29c42f22012-02-24 07:38:34 +00007388 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7389 return Success(E->getValue(), E);
7390 }
7391
John Wiegley6242b6a2011-04-28 00:16:57 +00007392 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7393 return Success(E->getValue(), E);
7394 }
7395
John Wiegleyf9f65842011-04-25 06:54:41 +00007396 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7397 return Success(E->getValue(), E);
7398 }
7399
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007400 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007401 bool VisitUnaryImag(const UnaryOperator *E);
7402
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007403 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007404 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007405
Eli Friedman4e7a2412009-02-27 04:45:43 +00007406 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007407};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007408
7409class FixedPointExprEvaluator
7410 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7411 APValue &Result;
7412
7413 public:
7414 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7415 : ExprEvaluatorBaseTy(info), Result(result) {}
7416
7417 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7418 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7419 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7420 "Invalid evaluation result.");
7421 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7422 "Invalid evaluation result.");
7423 Result = APValue(SI);
7424 return true;
7425 }
7426 bool Success(const llvm::APSInt &SI, const Expr *E) {
7427 return Success(SI, E, Result);
7428 }
7429
7430 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7431 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7432 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7433 "Invalid evaluation result.");
7434 Result = APValue(APSInt(I));
7435 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7436 return true;
7437 }
7438 bool Success(const llvm::APInt &I, const Expr *E) {
7439 return Success(I, E, Result);
7440 }
7441
7442 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7443 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7444 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7445 return true;
7446 }
7447 bool Success(uint64_t Value, const Expr *E) {
7448 return Success(Value, E, Result);
7449 }
7450
7451 bool Success(CharUnits Size, const Expr *E) {
7452 return Success(Size.getQuantity(), E);
7453 }
7454
7455 bool Success(const APValue &V, const Expr *E) {
7456 if (V.isLValue() || V.isAddrLabelDiff()) {
7457 Result = V;
7458 return true;
7459 }
7460 return Success(V.getInt(), E);
7461 }
7462
7463 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7464
7465 //===--------------------------------------------------------------------===//
7466 // Visitor Methods
7467 //===--------------------------------------------------------------------===//
7468
7469 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7470 return Success(E->getValue(), E);
7471 }
7472
7473 bool VisitUnaryOperator(const UnaryOperator *E);
7474};
Chris Lattner05706e882008-07-11 18:11:29 +00007475} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007476
Richard Smith11562c52011-10-28 17:51:58 +00007477/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7478/// produce either the integer value or a pointer.
7479///
7480/// GCC has a heinous extension which folds casts between pointer types and
7481/// pointer-sized integral types. We support this by allowing the evaluation of
7482/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7483/// Some simple arithmetic on such values is supported (they are treated much
7484/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007485static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007486 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007487 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007488 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007489}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007490
Richard Smithf57d8cb2011-12-09 22:58:01 +00007491static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007492 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007493 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007494 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007495 if (!Val.isInt()) {
7496 // FIXME: It would be better to produce the diagnostic for casting
7497 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007498 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007499 return false;
7500 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007501 Result = Val.getInt();
7502 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007503}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007504
Richard Smithf57d8cb2011-12-09 22:58:01 +00007505/// Check whether the given declaration can be directly converted to an integral
7506/// rvalue. If not, no diagnostic is produced; there are other things we can
7507/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007508bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007509 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007510 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007511 // Check for signedness/width mismatches between E type and ECD value.
7512 bool SameSign = (ECD->getInitVal().isSigned()
7513 == E->getType()->isSignedIntegerOrEnumerationType());
7514 bool SameWidth = (ECD->getInitVal().getBitWidth()
7515 == Info.Ctx.getIntWidth(E->getType()));
7516 if (SameSign && SameWidth)
7517 return Success(ECD->getInitVal(), E);
7518 else {
7519 // Get rid of mismatch (otherwise Success assertions will fail)
7520 // by computing a new value matching the type of E.
7521 llvm::APSInt Val = ECD->getInitVal();
7522 if (!SameSign)
7523 Val.setIsSigned(!ECD->getInitVal().isSigned());
7524 if (!SameWidth)
7525 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7526 return Success(Val, E);
7527 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007528 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007529 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007530}
7531
Richard Smith08b682b2018-05-23 21:18:00 +00007532/// Values returned by __builtin_classify_type, chosen to match the values
7533/// produced by GCC's builtin.
7534enum class GCCTypeClass {
7535 None = -1,
7536 Void = 0,
7537 Integer = 1,
7538 // GCC reserves 2 for character types, but instead classifies them as
7539 // integers.
7540 Enum = 3,
7541 Bool = 4,
7542 Pointer = 5,
7543 // GCC reserves 6 for references, but appears to never use it (because
7544 // expressions never have reference type, presumably).
7545 PointerToDataMember = 7,
7546 RealFloat = 8,
7547 Complex = 9,
7548 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7549 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7550 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7551 // uses 12 for that purpose, same as for a class or struct. Maybe it
7552 // internally implements a pointer to member as a struct? Who knows.
7553 PointerToMemberFunction = 12, // Not a bug, see above.
7554 ClassOrStruct = 12,
7555 Union = 13,
7556 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7557 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7558 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7559 // literals.
7560};
7561
Chris Lattner86ee2862008-10-06 06:40:35 +00007562/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7563/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007564static GCCTypeClass
7565EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7566 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007567
Richard Smith08b682b2018-05-23 21:18:00 +00007568 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007569 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7570
7571 switch (CanTy->getTypeClass()) {
7572#define TYPE(ID, BASE)
7573#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7574#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7575#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7576#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007577 case Type::Auto:
7578 case Type::DeducedTemplateSpecialization:
7579 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007580
7581 case Type::Builtin:
7582 switch (BT->getKind()) {
7583#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007584#define SIGNED_TYPE(ID, SINGLETON_ID) \
7585 case BuiltinType::ID: return GCCTypeClass::Integer;
7586#define FLOATING_TYPE(ID, SINGLETON_ID) \
7587 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7588#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7589 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007590#include "clang/AST/BuiltinTypes.def"
7591 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007592 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007593
7594 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007595 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007596
Richard Smith08b682b2018-05-23 21:18:00 +00007597 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007598 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007599 case BuiltinType::WChar_U:
7600 case BuiltinType::Char8:
7601 case BuiltinType::Char16:
7602 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007603 case BuiltinType::UShort:
7604 case BuiltinType::UInt:
7605 case BuiltinType::ULong:
7606 case BuiltinType::ULongLong:
7607 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007608 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007609
Leonard Chanf921d852018-06-04 16:07:52 +00007610 case BuiltinType::UShortAccum:
7611 case BuiltinType::UAccum:
7612 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007613 case BuiltinType::UShortFract:
7614 case BuiltinType::UFract:
7615 case BuiltinType::ULongFract:
7616 case BuiltinType::SatUShortAccum:
7617 case BuiltinType::SatUAccum:
7618 case BuiltinType::SatULongAccum:
7619 case BuiltinType::SatUShortFract:
7620 case BuiltinType::SatUFract:
7621 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007622 return GCCTypeClass::None;
7623
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007624 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007625
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007626 case BuiltinType::ObjCId:
7627 case BuiltinType::ObjCClass:
7628 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007629#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7630 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007631#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007632 case BuiltinType::OCLSampler:
7633 case BuiltinType::OCLEvent:
7634 case BuiltinType::OCLClkEvent:
7635 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007636 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007637 return GCCTypeClass::None;
7638
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007639 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007640 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007641 };
Richard Smith08b682b2018-05-23 21:18:00 +00007642 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007643
7644 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007645 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007646
7647 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007648 case Type::ConstantArray:
7649 case Type::VariableArray:
7650 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007651 case Type::FunctionNoProto:
7652 case Type::FunctionProto:
7653 return GCCTypeClass::Pointer;
7654
7655 case Type::MemberPointer:
7656 return CanTy->isMemberDataPointerType()
7657 ? GCCTypeClass::PointerToDataMember
7658 : GCCTypeClass::PointerToMemberFunction;
7659
7660 case Type::Complex:
7661 return GCCTypeClass::Complex;
7662
7663 case Type::Record:
7664 return CanTy->isUnionType() ? GCCTypeClass::Union
7665 : GCCTypeClass::ClassOrStruct;
7666
7667 case Type::Atomic:
7668 // GCC classifies _Atomic T the same as T.
7669 return EvaluateBuiltinClassifyType(
7670 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007671
7672 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007673 case Type::Vector:
7674 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007675 case Type::ObjCObject:
7676 case Type::ObjCInterface:
7677 case Type::ObjCObjectPointer:
7678 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007679 // GCC classifies vectors as None. We follow its lead and classify all
7680 // other types that don't fit into the regular classification the same way.
7681 return GCCTypeClass::None;
7682
7683 case Type::LValueReference:
7684 case Type::RValueReference:
7685 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007686 }
7687
Richard Smith08b682b2018-05-23 21:18:00 +00007688 llvm_unreachable("unexpected type class");
7689}
7690
7691/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7692/// as GCC.
7693static GCCTypeClass
7694EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7695 // If no argument was supplied, default to None. This isn't
7696 // ideal, however it is what gcc does.
7697 if (E->getNumArgs() == 0)
7698 return GCCTypeClass::None;
7699
7700 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7701 // being an ICE, but still folds it to a constant using the type of the first
7702 // argument.
7703 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007704}
7705
Richard Smith5fab0c92011-12-28 19:48:30 +00007706/// EvaluateBuiltinConstantPForLValue - Determine the result of
7707/// __builtin_constant_p when applied to the given lvalue.
7708///
7709/// An lvalue is only "constant" if it is a pointer or reference to the first
7710/// character of a string literal.
7711template<typename LValue>
7712static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007713 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007714 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7715}
7716
7717/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7718/// GCC as we can manage.
7719static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7720 QualType ArgType = Arg->getType();
7721
7722 // __builtin_constant_p always has one operand. The rules which gcc follows
7723 // are not precisely documented, but are as follows:
7724 //
7725 // - If the operand is of integral, floating, complex or enumeration type,
7726 // and can be folded to a known value of that type, it returns 1.
7727 // - If the operand and can be folded to a pointer to the first character
7728 // of a string literal (or such a pointer cast to an integral type), it
7729 // returns 1.
7730 //
7731 // Otherwise, it returns 0.
7732 //
7733 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7734 // its support for this does not currently work.
7735 if (ArgType->isIntegralOrEnumerationType()) {
7736 Expr::EvalResult Result;
7737 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7738 return false;
7739
7740 APValue &V = Result.Val;
7741 if (V.getKind() == APValue::Int)
7742 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007743 if (V.getKind() == APValue::LValue)
7744 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007745 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7746 return Arg->isEvaluatable(Ctx);
7747 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7748 LValue LV;
7749 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007750 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007751 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7752 : EvaluatePointer(Arg, LV, Info)) &&
7753 !Status.HasSideEffects)
7754 return EvaluateBuiltinConstantPForLValue(LV);
7755 }
7756
7757 // Anything else isn't considered to be sufficiently constant.
7758 return false;
7759}
7760
John McCall95007602010-05-10 23:27:23 +00007761/// Retrieves the "underlying object type" of the given expression,
7762/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007763static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007764 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7765 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007766 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007767 } else if (const Expr *E = B.get<const Expr*>()) {
7768 if (isa<CompoundLiteralExpr>(E))
7769 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007770 }
7771
7772 return QualType();
7773}
7774
George Burgess IV3a03fab2015-09-04 21:28:13 +00007775/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007776/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007777/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007778/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7779///
7780/// Always returns an RValue with a pointer representation.
7781static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7782 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7783
7784 auto *NoParens = E->IgnoreParens();
7785 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007786 if (Cast == nullptr)
7787 return NoParens;
7788
7789 // We only conservatively allow a few kinds of casts, because this code is
7790 // inherently a simple solution that seeks to support the common case.
7791 auto CastKind = Cast->getCastKind();
7792 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7793 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007794 return NoParens;
7795
7796 auto *SubExpr = Cast->getSubExpr();
7797 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7798 return NoParens;
7799 return ignorePointerCastsAndParens(SubExpr);
7800}
7801
George Burgess IVa51c4072015-10-16 01:49:01 +00007802/// Checks to see if the given LValue's Designator is at the end of the LValue's
7803/// record layout. e.g.
7804/// struct { struct { int a, b; } fst, snd; } obj;
7805/// obj.fst // no
7806/// obj.snd // yes
7807/// obj.fst.a // no
7808/// obj.fst.b // no
7809/// obj.snd.a // no
7810/// obj.snd.b // yes
7811///
7812/// Please note: this function is specialized for how __builtin_object_size
7813/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007814///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007815/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7816/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007817static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7818 assert(!LVal.Designator.Invalid);
7819
George Burgess IV4168d752016-06-27 19:40:41 +00007820 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7821 const RecordDecl *Parent = FD->getParent();
7822 Invalid = Parent->isInvalidDecl();
7823 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007824 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007825 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007826 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7827 };
7828
7829 auto &Base = LVal.getLValueBase();
7830 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7831 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007832 bool Invalid;
7833 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7834 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007835 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007836 for (auto *FD : IFD->chain()) {
7837 bool Invalid;
7838 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7839 return Invalid;
7840 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007841 }
7842 }
7843
George Burgess IVe3763372016-12-22 02:50:20 +00007844 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007845 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007846 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007847 // If we don't know the array bound, conservatively assume we're looking at
7848 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007849 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007850 if (BaseType->isIncompleteArrayType())
7851 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7852 else
7853 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007854 }
7855
7856 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7857 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007858 if (BaseType->isArrayType()) {
7859 // Because __builtin_object_size treats arrays as objects, we can ignore
7860 // the index iff this is the last array in the Designator.
7861 if (I + 1 == E)
7862 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007863 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7864 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007865 if (Index + 1 != CAT->getSize())
7866 return false;
7867 BaseType = CAT->getElementType();
7868 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007869 const auto *CT = BaseType->castAs<ComplexType>();
7870 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007871 if (Index != 1)
7872 return false;
7873 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007874 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007875 bool Invalid;
7876 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7877 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007878 BaseType = FD->getType();
7879 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007880 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007881 return false;
7882 }
7883 }
7884 return true;
7885}
7886
George Burgess IVe3763372016-12-22 02:50:20 +00007887/// Tests to see if the LValue has a user-specified designator (that isn't
7888/// necessarily valid). Note that this always returns 'true' if the LValue has
7889/// an unsized array as its first designator entry, because there's currently no
7890/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007891static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007892 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007893 return false;
7894
George Burgess IVe3763372016-12-22 02:50:20 +00007895 if (!LVal.Designator.Entries.empty())
7896 return LVal.Designator.isMostDerivedAnUnsizedArray();
7897
George Burgess IVa51c4072015-10-16 01:49:01 +00007898 if (!LVal.InvalidBase)
7899 return true;
7900
George Burgess IVe3763372016-12-22 02:50:20 +00007901 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7902 // the LValueBase.
7903 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7904 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007905}
7906
George Burgess IVe3763372016-12-22 02:50:20 +00007907/// Attempts to detect a user writing into a piece of memory that's impossible
7908/// to figure out the size of by just using types.
7909static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7910 const SubobjectDesignator &Designator = LVal.Designator;
7911 // Notes:
7912 // - Users can only write off of the end when we have an invalid base. Invalid
7913 // bases imply we don't know where the memory came from.
7914 // - We used to be a bit more aggressive here; we'd only be conservative if
7915 // the array at the end was flexible, or if it had 0 or 1 elements. This
7916 // broke some common standard library extensions (PR30346), but was
7917 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7918 // with some sort of whitelist. OTOH, it seems that GCC is always
7919 // conservative with the last element in structs (if it's an array), so our
7920 // current behavior is more compatible than a whitelisting approach would
7921 // be.
7922 return LVal.InvalidBase &&
7923 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7924 Designator.MostDerivedIsArrayElement &&
7925 isDesignatorAtObjectEnd(Ctx, LVal);
7926}
7927
7928/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7929/// Fails if the conversion would cause loss of precision.
7930static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7931 CharUnits &Result) {
7932 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7933 if (Int.ugt(CharUnitsMax))
7934 return false;
7935 Result = CharUnits::fromQuantity(Int.getZExtValue());
7936 return true;
7937}
7938
7939/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7940/// determine how many bytes exist from the beginning of the object to either
7941/// the end of the current subobject, or the end of the object itself, depending
7942/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007943///
George Burgess IVe3763372016-12-22 02:50:20 +00007944/// If this returns false, the value of Result is undefined.
7945static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7946 unsigned Type, const LValue &LVal,
7947 CharUnits &EndOffset) {
7948 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007949
George Burgess IV7fb7e362017-01-03 23:35:19 +00007950 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7951 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7952 return false;
7953 return HandleSizeof(Info, ExprLoc, Ty, Result);
7954 };
7955
George Burgess IVe3763372016-12-22 02:50:20 +00007956 // We want to evaluate the size of the entire object. This is a valid fallback
7957 // for when Type=1 and the designator is invalid, because we're asked for an
7958 // upper-bound.
7959 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7960 // Type=3 wants a lower bound, so we can't fall back to this.
7961 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007962 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007963
7964 llvm::APInt APEndOffset;
7965 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7966 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7967 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7968
7969 if (LVal.InvalidBase)
7970 return false;
7971
7972 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007973 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007974 }
7975
George Burgess IVe3763372016-12-22 02:50:20 +00007976 // We want to evaluate the size of a subobject.
7977 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007978
7979 // The following is a moderately common idiom in C:
7980 //
7981 // struct Foo { int a; char c[1]; };
7982 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7983 // strcpy(&F->c[0], Bar);
7984 //
George Burgess IVe3763372016-12-22 02:50:20 +00007985 // In order to not break too much legacy code, we need to support it.
7986 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7987 // If we can resolve this to an alloc_size call, we can hand that back,
7988 // because we know for certain how many bytes there are to write to.
7989 llvm::APInt APEndOffset;
7990 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7991 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7992 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7993
7994 // If we cannot determine the size of the initial allocation, then we can't
7995 // given an accurate upper-bound. However, we are still able to give
7996 // conservative lower-bounds for Type=3.
7997 if (Type == 1)
7998 return false;
7999 }
8000
8001 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008002 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008003 return false;
8004
George Burgess IVe3763372016-12-22 02:50:20 +00008005 // According to the GCC documentation, we want the size of the subobject
8006 // denoted by the pointer. But that's not quite right -- what we actually
8007 // want is the size of the immediately-enclosing array, if there is one.
8008 int64_t ElemsRemaining;
8009 if (Designator.MostDerivedIsArrayElement &&
8010 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8011 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8012 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8013 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8014 } else {
8015 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8016 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008017
George Burgess IVe3763372016-12-22 02:50:20 +00008018 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8019 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008020}
8021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008022/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008023/// returns true and stores the result in @p Size.
8024///
8025/// If @p WasError is non-null, this will report whether the failure to evaluate
8026/// is to be treated as an Error in IntExprEvaluator.
8027static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8028 EvalInfo &Info, uint64_t &Size) {
8029 // Determine the denoted object.
8030 LValue LVal;
8031 {
8032 // The operand of __builtin_object_size is never evaluated for side-effects.
8033 // If there are any, but we can determine the pointed-to object anyway, then
8034 // ignore the side-effects.
8035 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008036 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008037
8038 if (E->isGLValue()) {
8039 // It's possible for us to be given GLValues if we're called via
8040 // Expr::tryEvaluateObjectSize.
8041 APValue RVal;
8042 if (!EvaluateAsRValue(Info, E, RVal))
8043 return false;
8044 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008045 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8046 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008047 return false;
8048 }
8049
8050 // If we point to before the start of the object, there are no accessible
8051 // bytes.
8052 if (LVal.getLValueOffset().isNegative()) {
8053 Size = 0;
8054 return true;
8055 }
8056
8057 CharUnits EndOffset;
8058 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8059 return false;
8060
8061 // If we've fallen outside of the end offset, just pretend there's nothing to
8062 // write to/read from.
8063 if (EndOffset <= LVal.getLValueOffset())
8064 Size = 0;
8065 else
8066 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8067 return true;
John McCall95007602010-05-10 23:27:23 +00008068}
8069
Peter Collingbournee9200682011-05-13 03:29:01 +00008070bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008071 if (unsigned BuiltinOp = E->getBuiltinCallee())
8072 return VisitBuiltinCallExpr(E, BuiltinOp);
8073
8074 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8075}
8076
8077bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8078 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008079 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008080 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008081 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008082
8083 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008084 // The type was checked when we built the expression.
8085 unsigned Type =
8086 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8087 assert(Type <= 3 && "unexpected type");
8088
George Burgess IVe3763372016-12-22 02:50:20 +00008089 uint64_t Size;
8090 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8091 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008092
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008093 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008094 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008095
Richard Smith01ade172012-05-23 04:13:20 +00008096 // Expression had no side effects, but we couldn't statically determine the
8097 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008098 switch (Info.EvalMode) {
8099 case EvalInfo::EM_ConstantExpression:
8100 case EvalInfo::EM_PotentialConstantExpression:
8101 case EvalInfo::EM_ConstantFold:
8102 case EvalInfo::EM_EvaluateForOverflow:
8103 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008104 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008105 return Error(E);
8106 case EvalInfo::EM_ConstantExpressionUnevaluated:
8107 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008108 // Reduce it to a constant now.
8109 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008110 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008111
8112 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008113 }
8114
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008115 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008116 case Builtin::BI__builtin_bswap32:
8117 case Builtin::BI__builtin_bswap64: {
8118 APSInt Val;
8119 if (!EvaluateInteger(E->getArg(0), Val, Info))
8120 return false;
8121
8122 return Success(Val.byteSwap(), E);
8123 }
8124
Richard Smith8889a3d2013-06-13 06:26:32 +00008125 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008126 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008127
Craig Topperf95a6d92018-08-08 22:31:12 +00008128 case Builtin::BI__builtin_clrsb:
8129 case Builtin::BI__builtin_clrsbl:
8130 case Builtin::BI__builtin_clrsbll: {
8131 APSInt Val;
8132 if (!EvaluateInteger(E->getArg(0), Val, Info))
8133 return false;
8134
8135 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8136 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008137
Richard Smith80b3c8e2013-06-13 05:04:16 +00008138 case Builtin::BI__builtin_clz:
8139 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008140 case Builtin::BI__builtin_clzll:
8141 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008142 APSInt Val;
8143 if (!EvaluateInteger(E->getArg(0), Val, Info))
8144 return false;
8145 if (!Val)
8146 return Error(E);
8147
8148 return Success(Val.countLeadingZeros(), E);
8149 }
8150
Richard Smith8889a3d2013-06-13 06:26:32 +00008151 case Builtin::BI__builtin_constant_p:
8152 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
8153
Richard Smith80b3c8e2013-06-13 05:04:16 +00008154 case Builtin::BI__builtin_ctz:
8155 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008156 case Builtin::BI__builtin_ctzll:
8157 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008158 APSInt Val;
8159 if (!EvaluateInteger(E->getArg(0), Val, Info))
8160 return false;
8161 if (!Val)
8162 return Error(E);
8163
8164 return Success(Val.countTrailingZeros(), E);
8165 }
8166
Richard Smith8889a3d2013-06-13 06:26:32 +00008167 case Builtin::BI__builtin_eh_return_data_regno: {
8168 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8169 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8170 return Success(Operand, E);
8171 }
8172
8173 case Builtin::BI__builtin_expect:
8174 return Visit(E->getArg(0));
8175
8176 case Builtin::BI__builtin_ffs:
8177 case Builtin::BI__builtin_ffsl:
8178 case Builtin::BI__builtin_ffsll: {
8179 APSInt Val;
8180 if (!EvaluateInteger(E->getArg(0), Val, Info))
8181 return false;
8182
8183 unsigned N = Val.countTrailingZeros();
8184 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8185 }
8186
8187 case Builtin::BI__builtin_fpclassify: {
8188 APFloat Val(0.0);
8189 if (!EvaluateFloat(E->getArg(5), Val, Info))
8190 return false;
8191 unsigned Arg;
8192 switch (Val.getCategory()) {
8193 case APFloat::fcNaN: Arg = 0; break;
8194 case APFloat::fcInfinity: Arg = 1; break;
8195 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8196 case APFloat::fcZero: Arg = 4; break;
8197 }
8198 return Visit(E->getArg(Arg));
8199 }
8200
8201 case Builtin::BI__builtin_isinf_sign: {
8202 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008203 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008204 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8205 }
8206
Richard Smithea3019d2013-10-15 19:07:14 +00008207 case Builtin::BI__builtin_isinf: {
8208 APFloat Val(0.0);
8209 return EvaluateFloat(E->getArg(0), Val, Info) &&
8210 Success(Val.isInfinity() ? 1 : 0, E);
8211 }
8212
8213 case Builtin::BI__builtin_isfinite: {
8214 APFloat Val(0.0);
8215 return EvaluateFloat(E->getArg(0), Val, Info) &&
8216 Success(Val.isFinite() ? 1 : 0, E);
8217 }
8218
8219 case Builtin::BI__builtin_isnan: {
8220 APFloat Val(0.0);
8221 return EvaluateFloat(E->getArg(0), Val, Info) &&
8222 Success(Val.isNaN() ? 1 : 0, E);
8223 }
8224
8225 case Builtin::BI__builtin_isnormal: {
8226 APFloat Val(0.0);
8227 return EvaluateFloat(E->getArg(0), Val, Info) &&
8228 Success(Val.isNormal() ? 1 : 0, E);
8229 }
8230
Richard Smith8889a3d2013-06-13 06:26:32 +00008231 case Builtin::BI__builtin_parity:
8232 case Builtin::BI__builtin_parityl:
8233 case Builtin::BI__builtin_parityll: {
8234 APSInt Val;
8235 if (!EvaluateInteger(E->getArg(0), Val, Info))
8236 return false;
8237
8238 return Success(Val.countPopulation() % 2, E);
8239 }
8240
Richard Smith80b3c8e2013-06-13 05:04:16 +00008241 case Builtin::BI__builtin_popcount:
8242 case Builtin::BI__builtin_popcountl:
8243 case Builtin::BI__builtin_popcountll: {
8244 APSInt Val;
8245 if (!EvaluateInteger(E->getArg(0), Val, Info))
8246 return false;
8247
8248 return Success(Val.countPopulation(), E);
8249 }
8250
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008251 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008252 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008253 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008254 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008255 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008256 << /*isConstexpr*/0 << /*isConstructor*/0
8257 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008258 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008259 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008260 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008261 case Builtin::BI__builtin_strlen:
8262 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008263 // As an extension, we support __builtin_strlen() as a constant expression,
8264 // and support folding strlen() to a constant.
8265 LValue String;
8266 if (!EvaluatePointer(E->getArg(0), String, Info))
8267 return false;
8268
Richard Smith8110c9d2016-11-29 19:45:17 +00008269 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8270
Richard Smithe6c19f22013-11-15 02:10:04 +00008271 // Fast path: if it's a string literal, search the string value.
8272 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8273 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008274 // The string literal may have embedded null characters. Find the first
8275 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008276 StringRef Str = S->getBytes();
8277 int64_t Off = String.Offset.getQuantity();
8278 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008279 S->getCharByteWidth() == 1 &&
8280 // FIXME: Add fast-path for wchar_t too.
8281 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008282 Str = Str.substr(Off);
8283
8284 StringRef::size_type Pos = Str.find(0);
8285 if (Pos != StringRef::npos)
8286 Str = Str.substr(0, Pos);
8287
8288 return Success(Str.size(), E);
8289 }
8290
8291 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008292 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008293
8294 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008295 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8296 APValue Char;
8297 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8298 !Char.isInt())
8299 return false;
8300 if (!Char.getInt())
8301 return Success(Strlen, E);
8302 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8303 return false;
8304 }
8305 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008306
Richard Smithe151bab2016-11-11 23:43:35 +00008307 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008308 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008309 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008310 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008311 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008312 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008313 // A call to strlen is not a constant expression.
8314 if (Info.getLangOpts().CPlusPlus11)
8315 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8316 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008317 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008318 else
8319 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008320 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008321 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008322 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008323 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008324 case Builtin::BI__builtin_wcsncmp:
8325 case Builtin::BI__builtin_memcmp:
8326 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008327 LValue String1, String2;
8328 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8329 !EvaluatePointer(E->getArg(1), String2, Info))
8330 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008331
8332 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8333
Richard Smithe151bab2016-11-11 23:43:35 +00008334 uint64_t MaxLength = uint64_t(-1);
8335 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008336 BuiltinOp != Builtin::BIwcscmp &&
8337 BuiltinOp != Builtin::BI__builtin_strcmp &&
8338 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008339 APSInt N;
8340 if (!EvaluateInteger(E->getArg(2), N, Info))
8341 return false;
8342 MaxLength = N.getExtValue();
8343 }
8344 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008345 BuiltinOp != Builtin::BIwmemcmp &&
8346 BuiltinOp != Builtin::BI__builtin_memcmp &&
8347 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008348 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8349 BuiltinOp == Builtin::BIwcsncmp ||
8350 BuiltinOp == Builtin::BIwmemcmp ||
8351 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8352 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8353 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008354 for (; MaxLength; --MaxLength) {
8355 APValue Char1, Char2;
8356 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8357 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8358 !Char1.isInt() || !Char2.isInt())
8359 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008360 if (Char1.getInt() != Char2.getInt()) {
8361 if (IsWide) // wmemcmp compares with wchar_t signedness.
8362 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8363 // memcmp always compares unsigned chars.
8364 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8365 }
Richard Smithe151bab2016-11-11 23:43:35 +00008366 if (StopAtNull && !Char1.getInt())
8367 return Success(0, E);
8368 assert(!(StopAtNull && !Char2.getInt()));
8369 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8370 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8371 return false;
8372 }
8373 // We hit the strncmp / memcmp limit.
8374 return Success(0, E);
8375 }
8376
Richard Smith01ba47d2012-04-13 00:45:38 +00008377 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008378 case Builtin::BI__atomic_is_lock_free:
8379 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008380 APSInt SizeVal;
8381 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8382 return false;
8383
8384 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8385 // of two less than the maximum inline atomic width, we know it is
8386 // lock-free. If the size isn't a power of two, or greater than the
8387 // maximum alignment where we promote atomics, we know it is not lock-free
8388 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8389 // the answer can only be determined at runtime; for example, 16-byte
8390 // atomics have lock-free implementations on some, but not all,
8391 // x86-64 processors.
8392
8393 // Check power-of-two.
8394 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008395 if (Size.isPowerOfTwo()) {
8396 // Check against inlining width.
8397 unsigned InlineWidthBits =
8398 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8399 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8400 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8401 Size == CharUnits::One() ||
8402 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8403 Expr::NPC_NeverValueDependent))
8404 // OK, we will inline appropriately-aligned operations of this size,
8405 // and _Atomic(T) is appropriately-aligned.
8406 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008407
Richard Smith01ba47d2012-04-13 00:45:38 +00008408 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8409 castAs<PointerType>()->getPointeeType();
8410 if (!PointeeType->isIncompleteType() &&
8411 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8412 // OK, we will inline operations on this object.
8413 return Success(1, E);
8414 }
8415 }
8416 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008417
Richard Smith01ba47d2012-04-13 00:45:38 +00008418 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8419 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008420 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008421 case Builtin::BIomp_is_initial_device:
8422 // We can decide statically which value the runtime would return if called.
8423 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008424 case Builtin::BI__builtin_add_overflow:
8425 case Builtin::BI__builtin_sub_overflow:
8426 case Builtin::BI__builtin_mul_overflow:
8427 case Builtin::BI__builtin_sadd_overflow:
8428 case Builtin::BI__builtin_uadd_overflow:
8429 case Builtin::BI__builtin_uaddl_overflow:
8430 case Builtin::BI__builtin_uaddll_overflow:
8431 case Builtin::BI__builtin_usub_overflow:
8432 case Builtin::BI__builtin_usubl_overflow:
8433 case Builtin::BI__builtin_usubll_overflow:
8434 case Builtin::BI__builtin_umul_overflow:
8435 case Builtin::BI__builtin_umull_overflow:
8436 case Builtin::BI__builtin_umulll_overflow:
8437 case Builtin::BI__builtin_saddl_overflow:
8438 case Builtin::BI__builtin_saddll_overflow:
8439 case Builtin::BI__builtin_ssub_overflow:
8440 case Builtin::BI__builtin_ssubl_overflow:
8441 case Builtin::BI__builtin_ssubll_overflow:
8442 case Builtin::BI__builtin_smul_overflow:
8443 case Builtin::BI__builtin_smull_overflow:
8444 case Builtin::BI__builtin_smulll_overflow: {
8445 LValue ResultLValue;
8446 APSInt LHS, RHS;
8447
8448 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8449 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8450 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8451 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8452 return false;
8453
8454 APSInt Result;
8455 bool DidOverflow = false;
8456
8457 // If the types don't have to match, enlarge all 3 to the largest of them.
8458 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8459 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8460 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8461 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8462 ResultType->isSignedIntegerOrEnumerationType();
8463 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8464 ResultType->isSignedIntegerOrEnumerationType();
8465 uint64_t LHSSize = LHS.getBitWidth();
8466 uint64_t RHSSize = RHS.getBitWidth();
8467 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8468 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8469
8470 // Add an additional bit if the signedness isn't uniformly agreed to. We
8471 // could do this ONLY if there is a signed and an unsigned that both have
8472 // MaxBits, but the code to check that is pretty nasty. The issue will be
8473 // caught in the shrink-to-result later anyway.
8474 if (IsSigned && !AllSigned)
8475 ++MaxBits;
8476
8477 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8478 !IsSigned);
8479 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8480 !IsSigned);
8481 Result = APSInt(MaxBits, !IsSigned);
8482 }
8483
8484 // Find largest int.
8485 switch (BuiltinOp) {
8486 default:
8487 llvm_unreachable("Invalid value for BuiltinOp");
8488 case Builtin::BI__builtin_add_overflow:
8489 case Builtin::BI__builtin_sadd_overflow:
8490 case Builtin::BI__builtin_saddl_overflow:
8491 case Builtin::BI__builtin_saddll_overflow:
8492 case Builtin::BI__builtin_uadd_overflow:
8493 case Builtin::BI__builtin_uaddl_overflow:
8494 case Builtin::BI__builtin_uaddll_overflow:
8495 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8496 : LHS.uadd_ov(RHS, DidOverflow);
8497 break;
8498 case Builtin::BI__builtin_sub_overflow:
8499 case Builtin::BI__builtin_ssub_overflow:
8500 case Builtin::BI__builtin_ssubl_overflow:
8501 case Builtin::BI__builtin_ssubll_overflow:
8502 case Builtin::BI__builtin_usub_overflow:
8503 case Builtin::BI__builtin_usubl_overflow:
8504 case Builtin::BI__builtin_usubll_overflow:
8505 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8506 : LHS.usub_ov(RHS, DidOverflow);
8507 break;
8508 case Builtin::BI__builtin_mul_overflow:
8509 case Builtin::BI__builtin_smul_overflow:
8510 case Builtin::BI__builtin_smull_overflow:
8511 case Builtin::BI__builtin_smulll_overflow:
8512 case Builtin::BI__builtin_umul_overflow:
8513 case Builtin::BI__builtin_umull_overflow:
8514 case Builtin::BI__builtin_umulll_overflow:
8515 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8516 : LHS.umul_ov(RHS, DidOverflow);
8517 break;
8518 }
8519
8520 // In the case where multiple sizes are allowed, truncate and see if
8521 // the values are the same.
8522 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8523 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8524 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8525 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8526 // since it will give us the behavior of a TruncOrSelf in the case where
8527 // its parameter <= its size. We previously set Result to be at least the
8528 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8529 // will work exactly like TruncOrSelf.
8530 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8531 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8532
8533 if (!APSInt::isSameValue(Temp, Result))
8534 DidOverflow = true;
8535 Result = Temp;
8536 }
8537
8538 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008539 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8540 return false;
Erich Keane00958272018-06-13 20:43:27 +00008541 return Success(DidOverflow, E);
8542 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008543 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008544}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008546/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008547/// object referred to by the lvalue.
8548static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8549 const LValue &LV) {
8550 // A null pointer can be viewed as being "past the end" but we don't
8551 // choose to look at it that way here.
8552 if (!LV.getLValueBase())
8553 return false;
8554
8555 // If the designator is valid and refers to a subobject, we're not pointing
8556 // past the end.
8557 if (!LV.getLValueDesignator().Invalid &&
8558 !LV.getLValueDesignator().isOnePastTheEnd())
8559 return false;
8560
David Majnemerc378ca52015-08-29 08:32:55 +00008561 // A pointer to an incomplete type might be past-the-end if the type's size is
8562 // zero. We cannot tell because the type is incomplete.
8563 QualType Ty = getType(LV.getLValueBase());
8564 if (Ty->isIncompleteType())
8565 return true;
8566
Richard Smithd20f1e62014-10-21 23:01:04 +00008567 // We're a past-the-end pointer if we point to the byte after the object,
8568 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008569 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008570 return LV.getLValueOffset() == Size;
8571}
8572
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008573namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008574
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008575/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008576///
8577/// We use a data recursive algorithm for binary operators so that we are able
8578/// to handle extreme cases of chained binary operators without causing stack
8579/// overflow.
8580class DataRecursiveIntBinOpEvaluator {
8581 struct EvalResult {
8582 APValue Val;
8583 bool Failed;
8584
8585 EvalResult() : Failed(false) { }
8586
8587 void swap(EvalResult &RHS) {
8588 Val.swap(RHS.Val);
8589 Failed = RHS.Failed;
8590 RHS.Failed = false;
8591 }
8592 };
8593
8594 struct Job {
8595 const Expr *E;
8596 EvalResult LHSResult; // meaningful only for binary operator expression.
8597 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008598
David Blaikie73726062015-08-12 23:09:24 +00008599 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008600 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008601
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008602 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008603 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008604 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008605
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008606 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008607 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008608 };
8609
8610 SmallVector<Job, 16> Queue;
8611
8612 IntExprEvaluator &IntEval;
8613 EvalInfo &Info;
8614 APValue &FinalResult;
8615
8616public:
8617 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8618 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008620 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008621 /// data recursively.
8622 /// We handle binary operators that are comma, logical, or that have operands
8623 /// with integral or enumeration type.
8624 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008625 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8626 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008627 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008628 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008629 }
8630
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008631 bool Traverse(const BinaryOperator *E) {
8632 enqueue(E);
8633 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008634 while (!Queue.empty())
8635 process(PrevResult);
8636
8637 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008638
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008639 FinalResult.swap(PrevResult.Val);
8640 return true;
8641 }
8642
8643private:
8644 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8645 return IntEval.Success(Value, E, Result);
8646 }
8647 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8648 return IntEval.Success(Value, E, Result);
8649 }
8650 bool Error(const Expr *E) {
8651 return IntEval.Error(E);
8652 }
8653 bool Error(const Expr *E, diag::kind D) {
8654 return IntEval.Error(E, D);
8655 }
8656
8657 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8658 return Info.CCEDiag(E, D);
8659 }
8660
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008661 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008662 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008663 bool &SuppressRHSDiags);
8664
8665 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8666 const BinaryOperator *E, APValue &Result);
8667
8668 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8669 Result.Failed = !Evaluate(Result.Val, Info, E);
8670 if (Result.Failed)
8671 Result.Val = APValue();
8672 }
8673
Richard Trieuba4d0872012-03-21 23:30:30 +00008674 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008675
8676 void enqueue(const Expr *E) {
8677 E = E->IgnoreParens();
8678 Queue.resize(Queue.size()+1);
8679 Queue.back().E = E;
8680 Queue.back().Kind = Job::AnyExprKind;
8681 }
8682};
8683
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008684}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008685
8686bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008687 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008688 bool &SuppressRHSDiags) {
8689 if (E->getOpcode() == BO_Comma) {
8690 // Ignore LHS but note if we could not evaluate it.
8691 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008692 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008693 return true;
8694 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008695
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008696 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008697 bool LHSAsBool;
8698 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008699 // We were able to evaluate the LHS, see if we can get away with not
8700 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008701 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8702 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008703 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008704 }
8705 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008706 LHSResult.Failed = true;
8707
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008708 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008709 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008710 if (!Info.noteSideEffect())
8711 return false;
8712
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008713 // We can't evaluate the LHS; however, sometimes the result
8714 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8715 // Don't ignore RHS and suppress diagnostics from this arm.
8716 SuppressRHSDiags = true;
8717 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008718
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008719 return true;
8720 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008721
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008722 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8723 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008724
George Burgess IVa145e252016-05-25 22:38:36 +00008725 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008726 return false; // Ignore RHS;
8727
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008728 return true;
8729}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008730
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008731static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8732 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008733 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8734 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8735 // offsets.
8736 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8737 CharUnits &Offset = LVal.getLValueOffset();
8738 uint64_t Offset64 = Offset.getQuantity();
8739 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8740 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8741 : Offset64 + Index64);
8742}
8743
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008744bool DataRecursiveIntBinOpEvaluator::
8745 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8746 const BinaryOperator *E, APValue &Result) {
8747 if (E->getOpcode() == BO_Comma) {
8748 if (RHSResult.Failed)
8749 return false;
8750 Result = RHSResult.Val;
8751 return true;
8752 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008753
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008754 if (E->isLogicalOp()) {
8755 bool lhsResult, rhsResult;
8756 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8757 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008758
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008759 if (LHSIsOK) {
8760 if (RHSIsOK) {
8761 if (E->getOpcode() == BO_LOr)
8762 return Success(lhsResult || rhsResult, E, Result);
8763 else
8764 return Success(lhsResult && rhsResult, E, Result);
8765 }
8766 } else {
8767 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008768 // We can't evaluate the LHS; however, sometimes the result
8769 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8770 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008771 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008772 }
8773 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008774
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008775 return false;
8776 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008777
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008778 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8779 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00008780
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008781 if (LHSResult.Failed || RHSResult.Failed)
8782 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008783
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008784 const APValue &LHSVal = LHSResult.Val;
8785 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00008786
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008787 // Handle cases like (unsigned long)&a + 4.
8788 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8789 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008790 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008791 return true;
8792 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008793
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008794 // Handle cases like 4 + (unsigned long)&a
8795 if (E->getOpcode() == BO_Add &&
8796 RHSVal.isLValue() && LHSVal.isInt()) {
8797 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008798 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008799 return true;
8800 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008801
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008802 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8803 // Handle (intptr_t)&&A - (intptr_t)&&B.
8804 if (!LHSVal.getLValueOffset().isZero() ||
8805 !RHSVal.getLValueOffset().isZero())
8806 return false;
8807 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8808 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8809 if (!LHSExpr || !RHSExpr)
8810 return false;
8811 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8812 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8813 if (!LHSAddrExpr || !RHSAddrExpr)
8814 return false;
8815 // Make sure both labels come from the same function.
8816 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8817 RHSAddrExpr->getLabel()->getDeclContext())
8818 return false;
8819 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8820 return true;
8821 }
Richard Smith43e77732013-05-07 04:50:00 +00008822
8823 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008824 if (!LHSVal.isInt() || !RHSVal.isInt())
8825 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008826
8827 // Set up the width and signedness manually, in case it can't be deduced
8828 // from the operation we're performing.
8829 // FIXME: Don't do this in the cases where we can deduce it.
8830 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8831 E->getType()->isUnsignedIntegerOrEnumerationType());
8832 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8833 RHSVal.getInt(), Value))
8834 return false;
8835 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008836}
8837
Richard Trieuba4d0872012-03-21 23:30:30 +00008838void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008839 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00008840
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008841 switch (job.Kind) {
8842 case Job::AnyExprKind: {
8843 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8844 if (shouldEnqueue(Bop)) {
8845 job.Kind = Job::BinOpKind;
8846 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008847 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008848 }
8849 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008850
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008851 EvaluateExpr(job.E, Result);
8852 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008853 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008854 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008855
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008856 case Job::BinOpKind: {
8857 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008858 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008859 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008860 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008861 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008862 }
8863 if (SuppressRHSDiags)
8864 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008865 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008866 job.Kind = Job::BinOpVisitedLHSKind;
8867 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008868 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008869 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008870
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008871 case Job::BinOpVisitedLHSKind: {
8872 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8873 EvalResult RHS;
8874 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008875 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008876 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008877 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008878 }
8879 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008880
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008881 llvm_unreachable("Invalid Job::Kind!");
8882}
8883
George Burgess IV8c892b52016-05-25 22:31:54 +00008884namespace {
8885/// Used when we determine that we should fail, but can keep evaluating prior to
8886/// noting that we had a failure.
8887class DelayedNoteFailureRAII {
8888 EvalInfo &Info;
8889 bool NoteFailure;
8890
8891public:
8892 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8893 : Info(Info), NoteFailure(NoteFailure) {}
8894 ~DelayedNoteFailureRAII() {
8895 if (NoteFailure) {
8896 bool ContinueAfterFailure = Info.noteFailure();
8897 (void)ContinueAfterFailure;
8898 assert(ContinueAfterFailure &&
8899 "Shouldn't have kept evaluating on failure.");
8900 }
8901 }
8902};
8903}
8904
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008905template <class SuccessCB, class AfterCB>
8906static bool
8907EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8908 SuccessCB &&Success, AfterCB &&DoAfter) {
8909 assert(E->isComparisonOp() && "expected comparison operator");
8910 assert((E->getOpcode() == BO_Cmp ||
8911 E->getType()->isIntegralOrEnumerationType()) &&
8912 "unsupported binary expression evaluation");
8913 auto Error = [&](const Expr *E) {
8914 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8915 return false;
8916 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008917
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008918 using CCR = ComparisonCategoryResult;
8919 bool IsRelational = E->isRelationalOp();
8920 bool IsEquality = E->isEqualityOp();
8921 if (E->getOpcode() == BO_Cmp) {
8922 const ComparisonCategoryInfo &CmpInfo =
8923 Info.Ctx.CompCategories.getInfoForType(E->getType());
8924 IsRelational = CmpInfo.isOrdered();
8925 IsEquality = CmpInfo.isEquality();
8926 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00008927
Anders Carlssonacc79812008-11-16 07:17:21 +00008928 QualType LHSTy = E->getLHS()->getType();
8929 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008930
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008931 if (LHSTy->isIntegralOrEnumerationType() &&
8932 RHSTy->isIntegralOrEnumerationType()) {
8933 APSInt LHS, RHS;
8934 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8935 if (!LHSOK && !Info.noteFailure())
8936 return false;
8937 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8938 return false;
8939 if (LHS < RHS)
8940 return Success(CCR::Less, E);
8941 if (LHS > RHS)
8942 return Success(CCR::Greater, E);
8943 return Success(CCR::Equal, E);
8944 }
8945
Chandler Carruthb29a7432014-10-11 11:03:30 +00008946 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008947 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008948 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008949 if (E->isAssignmentOp()) {
8950 LValue LV;
8951 EvaluateLValue(E->getLHS(), LV, Info);
8952 LHSOK = false;
8953 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008954 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8955 if (LHSOK) {
8956 LHS.makeComplexFloat();
8957 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8958 }
8959 } else {
8960 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8961 }
George Burgess IVa145e252016-05-25 22:38:36 +00008962 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008963 return false;
8964
Chandler Carruthb29a7432014-10-11 11:03:30 +00008965 if (E->getRHS()->getType()->isRealFloatingType()) {
8966 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8967 return false;
8968 RHS.makeComplexFloat();
8969 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8970 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008971 return false;
8972
8973 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008974 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008975 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008976 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008977 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008978 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
8979 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008980 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008981 assert(IsEquality && "invalid complex comparison");
8982 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8983 LHS.getComplexIntImag() == RHS.getComplexIntImag();
8984 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008985 }
8986 }
Mike Stump11289f42009-09-09 15:08:12 +00008987
Anders Carlssonacc79812008-11-16 07:17:21 +00008988 if (LHSTy->isRealFloatingType() &&
8989 RHSTy->isRealFloatingType()) {
8990 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008991
Richard Smith253c2a32012-01-27 01:14:48 +00008992 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008993 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008994 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008995
Richard Smith253c2a32012-01-27 01:14:48 +00008996 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008997 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008998
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008999 assert(E->isComparisonOp() && "Invalid binary operator!");
9000 auto GetCmpRes = [&]() {
9001 switch (LHS.compare(RHS)) {
9002 case APFloat::cmpEqual:
9003 return CCR::Equal;
9004 case APFloat::cmpLessThan:
9005 return CCR::Less;
9006 case APFloat::cmpGreaterThan:
9007 return CCR::Greater;
9008 case APFloat::cmpUnordered:
9009 return CCR::Unordered;
9010 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009011 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009012 };
9013 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009014 }
Mike Stump11289f42009-09-09 15:08:12 +00009015
Eli Friedmana38da572009-04-28 19:17:36 +00009016 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009017 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009018
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009019 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9020 if (!LHSOK && !Info.noteFailure())
9021 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009022
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009023 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9024 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009025
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009026 // Reject differing bases from the normal codepath; we special-case
9027 // comparisons to null.
9028 if (!HasSameBase(LHSValue, RHSValue)) {
9029 // Inequalities and subtractions between unrelated pointers have
9030 // unspecified or undefined behavior.
9031 if (!IsEquality)
9032 return Error(E);
9033 // A constant address may compare equal to the address of a symbol.
9034 // The one exception is that address of an object cannot compare equal
9035 // to a null pointer constant.
9036 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9037 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9038 return Error(E);
9039 // It's implementation-defined whether distinct literals will have
9040 // distinct addresses. In clang, the result of such a comparison is
9041 // unspecified, so it is not a constant expression. However, we do know
9042 // that the address of a literal will be non-null.
9043 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9044 LHSValue.Base && RHSValue.Base)
9045 return Error(E);
9046 // We can't tell whether weak symbols will end up pointing to the same
9047 // object.
9048 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9049 return Error(E);
9050 // We can't compare the address of the start of one object with the
9051 // past-the-end address of another object, per C++ DR1652.
9052 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9053 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9054 (RHSValue.Base && RHSValue.Offset.isZero() &&
9055 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9056 return Error(E);
9057 // We can't tell whether an object is at the same address as another
9058 // zero sized object.
9059 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9060 (LHSValue.Base && isZeroSized(RHSValue)))
9061 return Error(E);
9062 return Success(CCR::Nonequal, E);
9063 }
Eli Friedman64004332009-03-23 04:38:34 +00009064
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009065 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9066 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009067
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009068 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9069 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009070
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009071 // C++11 [expr.rel]p3:
9072 // Pointers to void (after pointer conversions) can be compared, with a
9073 // result defined as follows: If both pointers represent the same
9074 // address or are both the null pointer value, the result is true if the
9075 // operator is <= or >= and false otherwise; otherwise the result is
9076 // unspecified.
9077 // We interpret this as applying to pointers to *cv* void.
9078 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9079 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009080
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009081 // C++11 [expr.rel]p2:
9082 // - If two pointers point to non-static data members of the same object,
9083 // or to subobjects or array elements fo such members, recursively, the
9084 // pointer to the later declared member compares greater provided the
9085 // two members have the same access control and provided their class is
9086 // not a union.
9087 // [...]
9088 // - Otherwise pointer comparisons are unspecified.
9089 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9090 bool WasArrayIndex;
9091 unsigned Mismatch = FindDesignatorMismatch(
9092 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9093 // At the point where the designators diverge, the comparison has a
9094 // specified value if:
9095 // - we are comparing array indices
9096 // - we are comparing fields of a union, or fields with the same access
9097 // Otherwise, the result is unspecified and thus the comparison is not a
9098 // constant expression.
9099 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9100 Mismatch < RHSDesignator.Entries.size()) {
9101 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9102 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9103 if (!LF && !RF)
9104 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9105 else if (!LF)
9106 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009107 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9108 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009109 else if (!RF)
9110 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009111 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9112 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009113 else if (!LF->getParent()->isUnion() &&
9114 LF->getAccess() != RF->getAccess())
9115 Info.CCEDiag(E,
9116 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009117 << LF << LF->getAccess() << RF << RF->getAccess()
9118 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009119 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009120 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009121
9122 // The comparison here must be unsigned, and performed with the same
9123 // width as the pointer.
9124 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9125 uint64_t CompareLHS = LHSOffset.getQuantity();
9126 uint64_t CompareRHS = RHSOffset.getQuantity();
9127 assert(PtrSize <= 64 && "Unexpected pointer width");
9128 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9129 CompareLHS &= Mask;
9130 CompareRHS &= Mask;
9131
9132 // If there is a base and this is a relational operator, we can only
9133 // compare pointers within the object in question; otherwise, the result
9134 // depends on where the object is located in memory.
9135 if (!LHSValue.Base.isNull() && IsRelational) {
9136 QualType BaseTy = getType(LHSValue.Base);
9137 if (BaseTy->isIncompleteType())
9138 return Error(E);
9139 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9140 uint64_t OffsetLimit = Size.getQuantity();
9141 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9142 return Error(E);
9143 }
9144
9145 if (CompareLHS < CompareRHS)
9146 return Success(CCR::Less, E);
9147 if (CompareLHS > CompareRHS)
9148 return Success(CCR::Greater, E);
9149 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009150 }
Richard Smith7bb00672012-02-01 01:42:44 +00009151
9152 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009153 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009154 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9155
9156 MemberPtr LHSValue, RHSValue;
9157
9158 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009159 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009160 return false;
9161
9162 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9163 return false;
9164
9165 // C++11 [expr.eq]p2:
9166 // If both operands are null, they compare equal. Otherwise if only one is
9167 // null, they compare unequal.
9168 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9169 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009170 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009171 }
9172
9173 // Otherwise if either is a pointer to a virtual member function, the
9174 // result is unspecified.
9175 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9176 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009177 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009178 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9179 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009180 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009181
9182 // Otherwise they compare equal if and only if they would refer to the
9183 // same member of the same most derived object or the same subobject if
9184 // they were dereferenced with a hypothetical object of the associated
9185 // class type.
9186 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009187 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009188 }
9189
Richard Smithab44d9b2012-02-14 22:35:28 +00009190 if (LHSTy->isNullPtrType()) {
9191 assert(E->isComparisonOp() && "unexpected nullptr operation");
9192 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9193 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9194 // are compared, the result is true of the operator is <=, >= or ==, and
9195 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009196 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009197 }
9198
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009199 return DoAfter();
9200}
9201
9202bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9203 if (!CheckLiteralType(Info, E))
9204 return false;
9205
9206 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9207 const BinaryOperator *E) {
9208 // Evaluation succeeded. Lookup the information for the comparison category
9209 // type and fetch the VarDecl for the result.
9210 const ComparisonCategoryInfo &CmpInfo =
9211 Info.Ctx.CompCategories.getInfoForType(E->getType());
9212 const VarDecl *VD =
9213 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9214 // Check and evaluate the result as a constant expression.
9215 LValue LV;
9216 LV.set(VD);
9217 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9218 return false;
9219 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9220 };
9221 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9222 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9223 });
9224}
9225
9226bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9227 // We don't call noteFailure immediately because the assignment happens after
9228 // we evaluate LHS and RHS.
9229 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9230 return Error(E);
9231
9232 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9233 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9234 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9235
9236 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9237 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009238 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009239
9240 if (E->isComparisonOp()) {
9241 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9242 // comparisons and then translating the result.
9243 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9244 const BinaryOperator *E) {
9245 using CCR = ComparisonCategoryResult;
9246 bool IsEqual = ResKind == CCR::Equal,
9247 IsLess = ResKind == CCR::Less,
9248 IsGreater = ResKind == CCR::Greater;
9249 auto Op = E->getOpcode();
9250 switch (Op) {
9251 default:
9252 llvm_unreachable("unsupported binary operator");
9253 case BO_EQ:
9254 case BO_NE:
9255 return Success(IsEqual == (Op == BO_EQ), E);
9256 case BO_LT: return Success(IsLess, E);
9257 case BO_GT: return Success(IsGreater, E);
9258 case BO_LE: return Success(IsEqual || IsLess, E);
9259 case BO_GE: return Success(IsEqual || IsGreater, E);
9260 }
9261 };
9262 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9263 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9264 });
9265 }
9266
9267 QualType LHSTy = E->getLHS()->getType();
9268 QualType RHSTy = E->getRHS()->getType();
9269
9270 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9271 E->getOpcode() == BO_Sub) {
9272 LValue LHSValue, RHSValue;
9273
9274 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9275 if (!LHSOK && !Info.noteFailure())
9276 return false;
9277
9278 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9279 return false;
9280
9281 // Reject differing bases from the normal codepath; we special-case
9282 // comparisons to null.
9283 if (!HasSameBase(LHSValue, RHSValue)) {
9284 // Handle &&A - &&B.
9285 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9286 return Error(E);
9287 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9288 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9289 if (!LHSExpr || !RHSExpr)
9290 return Error(E);
9291 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9292 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9293 if (!LHSAddrExpr || !RHSAddrExpr)
9294 return Error(E);
9295 // Make sure both labels come from the same function.
9296 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9297 RHSAddrExpr->getLabel()->getDeclContext())
9298 return Error(E);
9299 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9300 }
9301 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9302 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9303
9304 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9305 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9306
9307 // C++11 [expr.add]p6:
9308 // Unless both pointers point to elements of the same array object, or
9309 // one past the last element of the array object, the behavior is
9310 // undefined.
9311 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9312 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9313 RHSDesignator))
9314 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9315
9316 QualType Type = E->getLHS()->getType();
9317 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9318
9319 CharUnits ElementSize;
9320 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9321 return false;
9322
9323 // As an extension, a type may have zero size (empty struct or union in
9324 // C, array of zero length). Pointer subtraction in such cases has
9325 // undefined behavior, so is not constant.
9326 if (ElementSize.isZero()) {
9327 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9328 << ElementType;
9329 return false;
9330 }
9331
9332 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9333 // and produce incorrect results when it overflows. Such behavior
9334 // appears to be non-conforming, but is common, so perhaps we should
9335 // assume the standard intended for such cases to be undefined behavior
9336 // and check for them.
9337
9338 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9339 // overflow in the final conversion to ptrdiff_t.
9340 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9341 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9342 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9343 false);
9344 APSInt TrueResult = (LHS - RHS) / ElemSize;
9345 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9346
9347 if (Result.extend(65) != TrueResult &&
9348 !HandleOverflow(Info, E, TrueResult, E->getType()))
9349 return false;
9350 return Success(Result, E);
9351 }
9352
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009353 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009354}
9355
Peter Collingbournee190dee2011-03-11 19:24:49 +00009356/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9357/// a result as the expression's type.
9358bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9359 const UnaryExprOrTypeTraitExpr *E) {
9360 switch(E->getKind()) {
9361 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009362 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00009363 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009364 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00009365 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009366 }
Eli Friedman64004332009-03-23 04:38:34 +00009367
Peter Collingbournee190dee2011-03-11 19:24:49 +00009368 case UETT_VecStep: {
9369 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009370
Peter Collingbournee190dee2011-03-11 19:24:49 +00009371 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009372 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009373
Peter Collingbournee190dee2011-03-11 19:24:49 +00009374 // The vec_step built-in functions that take a 3-component
9375 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9376 if (n == 3)
9377 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009378
Peter Collingbournee190dee2011-03-11 19:24:49 +00009379 return Success(n, E);
9380 } else
9381 return Success(1, E);
9382 }
9383
9384 case UETT_SizeOf: {
9385 QualType SrcTy = E->getTypeOfArgument();
9386 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9387 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009388 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9389 SrcTy = Ref->getPointeeType();
9390
Richard Smithd62306a2011-11-10 06:34:14 +00009391 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009392 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009393 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009394 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009395 }
Alexey Bataev00396512015-07-02 03:40:19 +00009396 case UETT_OpenMPRequiredSimdAlign:
9397 assert(E->isArgumentType());
9398 return Success(
9399 Info.Ctx.toCharUnitsFromBits(
9400 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9401 .getQuantity(),
9402 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009403 }
9404
9405 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009406}
9407
Peter Collingbournee9200682011-05-13 03:29:01 +00009408bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009409 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009410 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009411 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009412 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009413 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009414 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009415 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009416 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009417 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009418 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009419 APSInt IdxResult;
9420 if (!EvaluateInteger(Idx, IdxResult, Info))
9421 return false;
9422 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9423 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009424 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009425 CurrentType = AT->getElementType();
9426 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9427 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009428 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009429 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009430
James Y Knight7281c352015-12-29 22:31:18 +00009431 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009432 FieldDecl *MemberDecl = ON.getField();
9433 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009434 if (!RT)
9435 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009436 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009437 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009438 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009439 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009440 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009441 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009442 CurrentType = MemberDecl->getType().getNonReferenceType();
9443 break;
9444 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009445
James Y Knight7281c352015-12-29 22:31:18 +00009446 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009447 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009448
James Y Knight7281c352015-12-29 22:31:18 +00009449 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009450 CXXBaseSpecifier *BaseSpec = ON.getBase();
9451 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009452 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009453
9454 // Find the layout of the class whose base we are looking into.
9455 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009456 if (!RT)
9457 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009458 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009459 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009460 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9461
9462 // Find the base class itself.
9463 CurrentType = BaseSpec->getType();
9464 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9465 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009466 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009467
Douglas Gregord1702062010-04-29 00:18:15 +00009468 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009469 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009470 break;
9471 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009472 }
9473 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009474 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009475}
9476
Chris Lattnere13042c2008-07-11 19:10:17 +00009477bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009478 switch (E->getOpcode()) {
9479 default:
9480 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9481 // See C99 6.6p3.
9482 return Error(E);
9483 case UO_Extension:
9484 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9485 // If so, we could clear the diagnostic ID.
9486 return Visit(E->getSubExpr());
9487 case UO_Plus:
9488 // The result is just the value.
9489 return Visit(E->getSubExpr());
9490 case UO_Minus: {
9491 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009492 return false;
9493 if (!Result.isInt()) return Error(E);
9494 const APSInt &Value = Result.getInt();
9495 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9496 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9497 E->getType()))
9498 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009499 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009500 }
9501 case UO_Not: {
9502 if (!Visit(E->getSubExpr()))
9503 return false;
9504 if (!Result.isInt()) return Error(E);
9505 return Success(~Result.getInt(), E);
9506 }
9507 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009508 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009509 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009510 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009511 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009512 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009513 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009514}
Mike Stump11289f42009-09-09 15:08:12 +00009515
Chris Lattner477c4be2008-07-12 01:15:53 +00009516/// HandleCast - This is used to evaluate implicit or explicit casts where the
9517/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009518bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9519 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009520 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009521 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009522
Eli Friedmanc757de22011-03-25 00:43:55 +00009523 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009524 case CK_BaseToDerived:
9525 case CK_DerivedToBase:
9526 case CK_UncheckedDerivedToBase:
9527 case CK_Dynamic:
9528 case CK_ToUnion:
9529 case CK_ArrayToPointerDecay:
9530 case CK_FunctionToPointerDecay:
9531 case CK_NullToPointer:
9532 case CK_NullToMemberPointer:
9533 case CK_BaseToDerivedMemberPointer:
9534 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009535 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009536 case CK_ConstructorConversion:
9537 case CK_IntegralToPointer:
9538 case CK_ToVoid:
9539 case CK_VectorSplat:
9540 case CK_IntegralToFloating:
9541 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009542 case CK_CPointerToObjCPointerCast:
9543 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009544 case CK_AnyPointerToBlockPointerCast:
9545 case CK_ObjCObjectLValueCast:
9546 case CK_FloatingRealToComplex:
9547 case CK_FloatingComplexToReal:
9548 case CK_FloatingComplexCast:
9549 case CK_FloatingComplexToIntegralComplex:
9550 case CK_IntegralRealToComplex:
9551 case CK_IntegralComplexCast:
9552 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009553 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009554 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009555 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009556 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009557 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009558 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00009559 llvm_unreachable("invalid cast kind for integral value");
9560
Eli Friedman9faf2f92011-03-25 19:07:11 +00009561 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009562 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009563 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009564 case CK_ARCProduceObject:
9565 case CK_ARCConsumeObject:
9566 case CK_ARCReclaimReturnedObject:
9567 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009568 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009569 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009570
Richard Smith4ef685b2012-01-17 21:17:26 +00009571 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009572 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009573 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009574 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009575 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009576
9577 case CK_MemberPointerToBoolean:
9578 case CK_PointerToBoolean:
9579 case CK_IntegralToBoolean:
9580 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009581 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009582 case CK_FloatingComplexToBoolean:
9583 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009584 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009585 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009586 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009587 uint64_t IntResult = BoolResult;
9588 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9589 IntResult = (uint64_t)-1;
9590 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009591 }
9592
Eli Friedmanc757de22011-03-25 00:43:55 +00009593 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009594 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009595 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009596
Eli Friedman742421e2009-02-20 01:15:07 +00009597 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009598 // Allow casts of address-of-label differences if they are no-ops
9599 // or narrowing. (The narrowing case isn't actually guaranteed to
9600 // be constant-evaluatable except in some narrow cases which are hard
9601 // to detect here. We let it through on the assumption the user knows
9602 // what they are doing.)
9603 if (Result.isAddrLabelDiff())
9604 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009605 // Only allow casts of lvalues if they are lossless.
9606 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9607 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009608
Richard Smith911e1422012-01-30 22:27:01 +00009609 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9610 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009611 }
Mike Stump11289f42009-09-09 15:08:12 +00009612
Eli Friedmanc757de22011-03-25 00:43:55 +00009613 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009614 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9615
John McCall45d55e42010-05-07 21:00:08 +00009616 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009617 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009618 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009619
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009620 if (LV.getLValueBase()) {
9621 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009622 // FIXME: Allow a larger integer size than the pointer size, and allow
9623 // narrowing back down to pointer width in subsequent integral casts.
9624 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009625 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009626 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009627
Richard Smithcf74da72011-11-16 07:18:12 +00009628 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009629 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009630 return true;
9631 }
9632
Yaxun Liu402804b2016-12-15 08:09:08 +00009633 uint64_t V;
9634 if (LV.isNullPointer())
9635 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9636 else
9637 V = LV.getLValueOffset().getQuantity();
9638
9639 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009640 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009641 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009642
Eli Friedmanc757de22011-03-25 00:43:55 +00009643 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009644 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009645 if (!EvaluateComplex(SubExpr, C, Info))
9646 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009647 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009648 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009649
Eli Friedmanc757de22011-03-25 00:43:55 +00009650 case CK_FloatingToIntegral: {
9651 APFloat F(0.0);
9652 if (!EvaluateFloat(SubExpr, F, Info))
9653 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009654
Richard Smith357362d2011-12-13 06:39:58 +00009655 APSInt Value;
9656 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9657 return false;
9658 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009659 }
9660 }
Mike Stump11289f42009-09-09 15:08:12 +00009661
Eli Friedmanc757de22011-03-25 00:43:55 +00009662 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009663}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009664
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009665bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9666 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009667 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009668 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9669 return false;
9670 if (!LV.isComplexInt())
9671 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009672 return Success(LV.getComplexIntReal(), E);
9673 }
9674
9675 return Visit(E->getSubExpr());
9676}
9677
Eli Friedman4e7a2412009-02-27 04:45:43 +00009678bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009679 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009680 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009681 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9682 return false;
9683 if (!LV.isComplexInt())
9684 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009685 return Success(LV.getComplexIntImag(), E);
9686 }
9687
Richard Smith4a678122011-10-24 18:44:57 +00009688 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009689 return Success(0, E);
9690}
9691
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009692bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9693 return Success(E->getPackLength(), E);
9694}
9695
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009696bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9697 return Success(E->getValue(), E);
9698}
9699
Leonard Chandb01c3a2018-06-20 17:19:40 +00009700bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9701 switch (E->getOpcode()) {
9702 default:
9703 // Invalid unary operators
9704 return Error(E);
9705 case UO_Plus:
9706 // The result is just the value.
9707 return Visit(E->getSubExpr());
9708 case UO_Minus: {
9709 if (!Visit(E->getSubExpr())) return false;
9710 if (!Result.isInt()) return Error(E);
9711 const APSInt &Value = Result.getInt();
9712 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9713 SmallString<64> S;
9714 FixedPointValueToString(S, Value,
Leonard Chanc03642e2018-08-06 16:05:08 +00009715 Info.Ctx.getTypeInfo(E->getType()).Width);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009716 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9717 if (Info.noteUndefinedBehavior()) return false;
9718 }
9719 return Success(-Value, E);
9720 }
9721 case UO_LNot: {
9722 bool bres;
9723 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9724 return false;
9725 return Success(!bres, E);
9726 }
9727 }
9728}
9729
Chris Lattner05706e882008-07-11 18:11:29 +00009730//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009731// Float Evaluation
9732//===----------------------------------------------------------------------===//
9733
9734namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009735class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009736 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009737 APFloat &Result;
9738public:
9739 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009740 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009741
Richard Smith2e312c82012-03-03 22:46:17 +00009742 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009743 Result = V.getFloat();
9744 return true;
9745 }
Eli Friedman24c01542008-08-22 00:06:13 +00009746
Richard Smithfddd3842011-12-30 21:15:51 +00009747 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009748 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9749 return true;
9750 }
9751
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009752 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009753
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009754 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009755 bool VisitBinaryOperator(const BinaryOperator *E);
9756 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009757 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009758
John McCallb1fb0d32010-05-07 22:08:54 +00009759 bool VisitUnaryReal(const UnaryOperator *E);
9760 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009761
Richard Smithfddd3842011-12-30 21:15:51 +00009762 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009763};
9764} // end anonymous namespace
9765
9766static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009767 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009768 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009769}
9770
Jay Foad39c79802011-01-12 09:06:06 +00009771static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009772 QualType ResultTy,
9773 const Expr *Arg,
9774 bool SNaN,
9775 llvm::APFloat &Result) {
9776 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9777 if (!S) return false;
9778
9779 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9780
9781 llvm::APInt fill;
9782
9783 // Treat empty strings as if they were zero.
9784 if (S->getString().empty())
9785 fill = llvm::APInt(32, 0);
9786 else if (S->getString().getAsInteger(0, fill))
9787 return false;
9788
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009789 if (Context.getTargetInfo().isNan2008()) {
9790 if (SNaN)
9791 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9792 else
9793 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9794 } else {
9795 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9796 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9797 // a different encoding to what became a standard in 2008, and for pre-
9798 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9799 // sNaN. This is now known as "legacy NaN" encoding.
9800 if (SNaN)
9801 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9802 else
9803 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9804 }
9805
John McCall16291492010-02-28 13:00:19 +00009806 return true;
9807}
9808
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009809bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009810 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009811 default:
9812 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9813
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009814 case Builtin::BI__builtin_huge_val:
9815 case Builtin::BI__builtin_huge_valf:
9816 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009817 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009818 case Builtin::BI__builtin_inf:
9819 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009820 case Builtin::BI__builtin_infl:
9821 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009822 const llvm::fltSemantics &Sem =
9823 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009824 Result = llvm::APFloat::getInf(Sem);
9825 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009826 }
Mike Stump11289f42009-09-09 15:08:12 +00009827
John McCall16291492010-02-28 13:00:19 +00009828 case Builtin::BI__builtin_nans:
9829 case Builtin::BI__builtin_nansf:
9830 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009831 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009832 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9833 true, Result))
9834 return Error(E);
9835 return true;
John McCall16291492010-02-28 13:00:19 +00009836
Chris Lattner0b7282e2008-10-06 06:31:58 +00009837 case Builtin::BI__builtin_nan:
9838 case Builtin::BI__builtin_nanf:
9839 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009840 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009841 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009842 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009843 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9844 false, Result))
9845 return Error(E);
9846 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009847
9848 case Builtin::BI__builtin_fabs:
9849 case Builtin::BI__builtin_fabsf:
9850 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009851 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009852 if (!EvaluateFloat(E->getArg(0), Result, Info))
9853 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009854
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009855 if (Result.isNegative())
9856 Result.changeSign();
9857 return true;
9858
Richard Smith8889a3d2013-06-13 06:26:32 +00009859 // FIXME: Builtin::BI__builtin_powi
9860 // FIXME: Builtin::BI__builtin_powif
9861 // FIXME: Builtin::BI__builtin_powil
9862
Mike Stump11289f42009-09-09 15:08:12 +00009863 case Builtin::BI__builtin_copysign:
9864 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009865 case Builtin::BI__builtin_copysignl:
9866 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009867 APFloat RHS(0.);
9868 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9869 !EvaluateFloat(E->getArg(1), RHS, Info))
9870 return false;
9871 Result.copySign(RHS);
9872 return true;
9873 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009874 }
9875}
9876
John McCallb1fb0d32010-05-07 22:08:54 +00009877bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009878 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9879 ComplexValue CV;
9880 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9881 return false;
9882 Result = CV.FloatReal;
9883 return true;
9884 }
9885
9886 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009887}
9888
9889bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009890 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9891 ComplexValue CV;
9892 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9893 return false;
9894 Result = CV.FloatImag;
9895 return true;
9896 }
9897
Richard Smith4a678122011-10-24 18:44:57 +00009898 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009899 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9900 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009901 return true;
9902}
9903
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009904bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009905 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009906 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009907 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009908 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009909 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009910 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9911 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009912 Result.changeSign();
9913 return true;
9914 }
9915}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009916
Eli Friedman24c01542008-08-22 00:06:13 +00009917bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009918 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9919 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009920
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009921 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009922 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009923 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009924 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009925 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9926 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009927}
9928
9929bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9930 Result = E->getValue();
9931 return true;
9932}
9933
Peter Collingbournee9200682011-05-13 03:29:01 +00009934bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9935 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009936
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009937 switch (E->getCastKind()) {
9938 default:
Richard Smith11562c52011-10-28 17:51:58 +00009939 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009940
9941 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009942 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009943 return EvaluateInteger(SubExpr, IntResult, Info) &&
9944 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9945 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009946 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009947
9948 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009949 if (!Visit(SubExpr))
9950 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009951 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9952 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009953 }
John McCalld7646252010-11-14 08:17:51 +00009954
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009955 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009956 ComplexValue V;
9957 if (!EvaluateComplex(SubExpr, V, Info))
9958 return false;
9959 Result = V.getComplexFloatReal();
9960 return true;
9961 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009962 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009963}
9964
Eli Friedman24c01542008-08-22 00:06:13 +00009965//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009966// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009967//===----------------------------------------------------------------------===//
9968
9969namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009970class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009971 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009972 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009973
Anders Carlsson537969c2008-11-16 20:27:53 +00009974public:
John McCall93d91dc2010-05-07 17:22:02 +00009975 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009976 : ExprEvaluatorBaseTy(info), Result(Result) {}
9977
Richard Smith2e312c82012-03-03 22:46:17 +00009978 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009979 Result.setFrom(V);
9980 return true;
9981 }
Mike Stump11289f42009-09-09 15:08:12 +00009982
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009983 bool ZeroInitialization(const Expr *E);
9984
Anders Carlsson537969c2008-11-16 20:27:53 +00009985 //===--------------------------------------------------------------------===//
9986 // Visitor Methods
9987 //===--------------------------------------------------------------------===//
9988
Peter Collingbournee9200682011-05-13 03:29:01 +00009989 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009990 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009991 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009992 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009993 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009994};
9995} // end anonymous namespace
9996
John McCall93d91dc2010-05-07 17:22:02 +00009997static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9998 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009999 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010000 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010001}
10002
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010003bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010004 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010005 if (ElemTy->isRealFloatingType()) {
10006 Result.makeComplexFloat();
10007 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10008 Result.FloatReal = Zero;
10009 Result.FloatImag = Zero;
10010 } else {
10011 Result.makeComplexInt();
10012 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10013 Result.IntReal = Zero;
10014 Result.IntImag = Zero;
10015 }
10016 return true;
10017}
10018
Peter Collingbournee9200682011-05-13 03:29:01 +000010019bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10020 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010021
10022 if (SubExpr->getType()->isRealFloatingType()) {
10023 Result.makeComplexFloat();
10024 APFloat &Imag = Result.FloatImag;
10025 if (!EvaluateFloat(SubExpr, Imag, Info))
10026 return false;
10027
10028 Result.FloatReal = APFloat(Imag.getSemantics());
10029 return true;
10030 } else {
10031 assert(SubExpr->getType()->isIntegerType() &&
10032 "Unexpected imaginary literal.");
10033
10034 Result.makeComplexInt();
10035 APSInt &Imag = Result.IntImag;
10036 if (!EvaluateInteger(SubExpr, Imag, Info))
10037 return false;
10038
10039 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10040 return true;
10041 }
10042}
10043
Peter Collingbournee9200682011-05-13 03:29:01 +000010044bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010045
John McCallfcef3cf2010-12-14 17:51:41 +000010046 switch (E->getCastKind()) {
10047 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010048 case CK_BaseToDerived:
10049 case CK_DerivedToBase:
10050 case CK_UncheckedDerivedToBase:
10051 case CK_Dynamic:
10052 case CK_ToUnion:
10053 case CK_ArrayToPointerDecay:
10054 case CK_FunctionToPointerDecay:
10055 case CK_NullToPointer:
10056 case CK_NullToMemberPointer:
10057 case CK_BaseToDerivedMemberPointer:
10058 case CK_DerivedToBaseMemberPointer:
10059 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010060 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010061 case CK_ConstructorConversion:
10062 case CK_IntegralToPointer:
10063 case CK_PointerToIntegral:
10064 case CK_PointerToBoolean:
10065 case CK_ToVoid:
10066 case CK_VectorSplat:
10067 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010068 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010069 case CK_IntegralToBoolean:
10070 case CK_IntegralToFloating:
10071 case CK_FloatingToIntegral:
10072 case CK_FloatingToBoolean:
10073 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010074 case CK_CPointerToObjCPointerCast:
10075 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010076 case CK_AnyPointerToBlockPointerCast:
10077 case CK_ObjCObjectLValueCast:
10078 case CK_FloatingComplexToReal:
10079 case CK_FloatingComplexToBoolean:
10080 case CK_IntegralComplexToReal:
10081 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010082 case CK_ARCProduceObject:
10083 case CK_ARCConsumeObject:
10084 case CK_ARCReclaimReturnedObject:
10085 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010086 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010087 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000010088 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +000010089 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +000010090 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010091 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010092 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +000010093 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010094
John McCallfcef3cf2010-12-14 17:51:41 +000010095 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010096 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010097 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010098 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010099
10100 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010101 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010102 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010103 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010104
10105 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010106 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010107 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010108 return false;
10109
John McCallfcef3cf2010-12-14 17:51:41 +000010110 Result.makeComplexFloat();
10111 Result.FloatImag = APFloat(Real.getSemantics());
10112 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010113 }
10114
John McCallfcef3cf2010-12-14 17:51:41 +000010115 case CK_FloatingComplexCast: {
10116 if (!Visit(E->getSubExpr()))
10117 return false;
10118
10119 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10120 QualType From
10121 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10122
Richard Smith357362d2011-12-13 06:39:58 +000010123 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10124 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010125 }
10126
10127 case CK_FloatingComplexToIntegralComplex: {
10128 if (!Visit(E->getSubExpr()))
10129 return false;
10130
10131 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10132 QualType From
10133 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10134 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010135 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10136 To, Result.IntReal) &&
10137 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10138 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010139 }
10140
10141 case CK_IntegralRealToComplex: {
10142 APSInt &Real = Result.IntReal;
10143 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10144 return false;
10145
10146 Result.makeComplexInt();
10147 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10148 return true;
10149 }
10150
10151 case CK_IntegralComplexCast: {
10152 if (!Visit(E->getSubExpr()))
10153 return false;
10154
10155 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10156 QualType From
10157 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10158
Richard Smith911e1422012-01-30 22:27:01 +000010159 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10160 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010161 return true;
10162 }
10163
10164 case CK_IntegralComplexToFloatingComplex: {
10165 if (!Visit(E->getSubExpr()))
10166 return false;
10167
Ted Kremenek28831752012-08-23 20:46:57 +000010168 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010169 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010170 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010171 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010172 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10173 To, Result.FloatReal) &&
10174 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10175 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010176 }
10177 }
10178
10179 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010180}
10181
John McCall93d91dc2010-05-07 17:22:02 +000010182bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010183 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010184 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10185
Chandler Carrutha216cad2014-10-11 00:57:18 +000010186 // Track whether the LHS or RHS is real at the type system level. When this is
10187 // the case we can simplify our evaluation strategy.
10188 bool LHSReal = false, RHSReal = false;
10189
10190 bool LHSOK;
10191 if (E->getLHS()->getType()->isRealFloatingType()) {
10192 LHSReal = true;
10193 APFloat &Real = Result.FloatReal;
10194 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10195 if (LHSOK) {
10196 Result.makeComplexFloat();
10197 Result.FloatImag = APFloat(Real.getSemantics());
10198 }
10199 } else {
10200 LHSOK = Visit(E->getLHS());
10201 }
George Burgess IVa145e252016-05-25 22:38:36 +000010202 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010203 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010204
John McCall93d91dc2010-05-07 17:22:02 +000010205 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010206 if (E->getRHS()->getType()->isRealFloatingType()) {
10207 RHSReal = true;
10208 APFloat &Real = RHS.FloatReal;
10209 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10210 return false;
10211 RHS.makeComplexFloat();
10212 RHS.FloatImag = APFloat(Real.getSemantics());
10213 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010214 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010215
Chandler Carrutha216cad2014-10-11 00:57:18 +000010216 assert(!(LHSReal && RHSReal) &&
10217 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010218 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010219 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010220 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010221 if (Result.isComplexFloat()) {
10222 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10223 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010224 if (LHSReal)
10225 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10226 else if (!RHSReal)
10227 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10228 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010229 } else {
10230 Result.getComplexIntReal() += RHS.getComplexIntReal();
10231 Result.getComplexIntImag() += RHS.getComplexIntImag();
10232 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010233 break;
John McCalle3027922010-08-25 11:45:40 +000010234 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010235 if (Result.isComplexFloat()) {
10236 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10237 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010238 if (LHSReal) {
10239 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10240 Result.getComplexFloatImag().changeSign();
10241 } else if (!RHSReal) {
10242 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10243 APFloat::rmNearestTiesToEven);
10244 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010245 } else {
10246 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10247 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10248 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010249 break;
John McCalle3027922010-08-25 11:45:40 +000010250 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010251 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010252 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010253 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010254 // following naming scheme:
10255 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010256 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010257 APFloat &A = LHS.getComplexFloatReal();
10258 APFloat &B = LHS.getComplexFloatImag();
10259 APFloat &C = RHS.getComplexFloatReal();
10260 APFloat &D = RHS.getComplexFloatImag();
10261 APFloat &ResR = Result.getComplexFloatReal();
10262 APFloat &ResI = Result.getComplexFloatImag();
10263 if (LHSReal) {
10264 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10265 ResR = A * C;
10266 ResI = A * D;
10267 } else if (RHSReal) {
10268 ResR = C * A;
10269 ResI = C * B;
10270 } else {
10271 // In the fully general case, we need to handle NaNs and infinities
10272 // robustly.
10273 APFloat AC = A * C;
10274 APFloat BD = B * D;
10275 APFloat AD = A * D;
10276 APFloat BC = B * C;
10277 ResR = AC - BD;
10278 ResI = AD + BC;
10279 if (ResR.isNaN() && ResI.isNaN()) {
10280 bool Recalc = false;
10281 if (A.isInfinity() || B.isInfinity()) {
10282 A = APFloat::copySign(
10283 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10284 B = APFloat::copySign(
10285 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10286 if (C.isNaN())
10287 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10288 if (D.isNaN())
10289 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10290 Recalc = true;
10291 }
10292 if (C.isInfinity() || D.isInfinity()) {
10293 C = APFloat::copySign(
10294 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10295 D = APFloat::copySign(
10296 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10297 if (A.isNaN())
10298 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10299 if (B.isNaN())
10300 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10301 Recalc = true;
10302 }
10303 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10304 AD.isInfinity() || BC.isInfinity())) {
10305 if (A.isNaN())
10306 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10307 if (B.isNaN())
10308 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10309 if (C.isNaN())
10310 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10311 if (D.isNaN())
10312 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10313 Recalc = true;
10314 }
10315 if (Recalc) {
10316 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10317 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10318 }
10319 }
10320 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010321 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010322 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010323 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010324 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10325 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010326 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010327 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10328 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10329 }
10330 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010331 case BO_Div:
10332 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010333 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010334 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010335 // following naming scheme:
10336 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010337 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010338 APFloat &A = LHS.getComplexFloatReal();
10339 APFloat &B = LHS.getComplexFloatImag();
10340 APFloat &C = RHS.getComplexFloatReal();
10341 APFloat &D = RHS.getComplexFloatImag();
10342 APFloat &ResR = Result.getComplexFloatReal();
10343 APFloat &ResI = Result.getComplexFloatImag();
10344 if (RHSReal) {
10345 ResR = A / C;
10346 ResI = B / C;
10347 } else {
10348 if (LHSReal) {
10349 // No real optimizations we can do here, stub out with zero.
10350 B = APFloat::getZero(A.getSemantics());
10351 }
10352 int DenomLogB = 0;
10353 APFloat MaxCD = maxnum(abs(C), abs(D));
10354 if (MaxCD.isFinite()) {
10355 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010356 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10357 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010358 }
10359 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010360 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10361 APFloat::rmNearestTiesToEven);
10362 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10363 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010364 if (ResR.isNaN() && ResI.isNaN()) {
10365 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10366 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10367 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10368 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10369 D.isFinite()) {
10370 A = APFloat::copySign(
10371 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10372 B = APFloat::copySign(
10373 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10374 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10375 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10376 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10377 C = APFloat::copySign(
10378 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10379 D = APFloat::copySign(
10380 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10381 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10382 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10383 }
10384 }
10385 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010386 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010387 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10388 return Error(E, diag::note_expr_divide_by_zero);
10389
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010390 ComplexValue LHS = Result;
10391 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10392 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10393 Result.getComplexIntReal() =
10394 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10395 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10396 Result.getComplexIntImag() =
10397 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10398 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10399 }
10400 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010401 }
10402
John McCall93d91dc2010-05-07 17:22:02 +000010403 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010404}
10405
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010406bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10407 // Get the operand value into 'Result'.
10408 if (!Visit(E->getSubExpr()))
10409 return false;
10410
10411 switch (E->getOpcode()) {
10412 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010413 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010414 case UO_Extension:
10415 return true;
10416 case UO_Plus:
10417 // The result is always just the subexpr.
10418 return true;
10419 case UO_Minus:
10420 if (Result.isComplexFloat()) {
10421 Result.getComplexFloatReal().changeSign();
10422 Result.getComplexFloatImag().changeSign();
10423 }
10424 else {
10425 Result.getComplexIntReal() = -Result.getComplexIntReal();
10426 Result.getComplexIntImag() = -Result.getComplexIntImag();
10427 }
10428 return true;
10429 case UO_Not:
10430 if (Result.isComplexFloat())
10431 Result.getComplexFloatImag().changeSign();
10432 else
10433 Result.getComplexIntImag() = -Result.getComplexIntImag();
10434 return true;
10435 }
10436}
10437
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010438bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10439 if (E->getNumInits() == 2) {
10440 if (E->getType()->isComplexType()) {
10441 Result.makeComplexFloat();
10442 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10443 return false;
10444 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10445 return false;
10446 } else {
10447 Result.makeComplexInt();
10448 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10449 return false;
10450 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10451 return false;
10452 }
10453 return true;
10454 }
10455 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10456}
10457
Anders Carlsson537969c2008-11-16 20:27:53 +000010458//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010459// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10460// implicit conversion.
10461//===----------------------------------------------------------------------===//
10462
10463namespace {
10464class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010465 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010466 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010467 APValue &Result;
10468public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010469 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10470 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010471
10472 bool Success(const APValue &V, const Expr *E) {
10473 Result = V;
10474 return true;
10475 }
10476
10477 bool ZeroInitialization(const Expr *E) {
10478 ImplicitValueInitExpr VIE(
10479 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010480 // For atomic-qualified class (and array) types in C++, initialize the
10481 // _Atomic-wrapped subobject directly, in-place.
10482 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10483 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010484 }
10485
10486 bool VisitCastExpr(const CastExpr *E) {
10487 switch (E->getCastKind()) {
10488 default:
10489 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10490 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010491 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10492 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010493 }
10494 }
10495};
10496} // end anonymous namespace
10497
Richard Smith64cb9ca2017-02-22 22:09:50 +000010498static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10499 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010500 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010501 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010502}
10503
10504//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010505// Void expression evaluation, primarily for a cast to void on the LHS of a
10506// comma operator
10507//===----------------------------------------------------------------------===//
10508
10509namespace {
10510class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010511 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010512public:
10513 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10514
Richard Smith2e312c82012-03-03 22:46:17 +000010515 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010516
Richard Smith7cd577b2017-08-17 19:35:50 +000010517 bool ZeroInitialization(const Expr *E) { return true; }
10518
Richard Smith42d3af92011-12-07 00:43:50 +000010519 bool VisitCastExpr(const CastExpr *E) {
10520 switch (E->getCastKind()) {
10521 default:
10522 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10523 case CK_ToVoid:
10524 VisitIgnoredValue(E->getSubExpr());
10525 return true;
10526 }
10527 }
Hal Finkela8443c32014-07-17 14:49:58 +000010528
10529 bool VisitCallExpr(const CallExpr *E) {
10530 switch (E->getBuiltinCallee()) {
10531 default:
10532 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10533 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010534 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010535 // The argument is not evaluated!
10536 return true;
10537 }
10538 }
Richard Smith42d3af92011-12-07 00:43:50 +000010539};
10540} // end anonymous namespace
10541
10542static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10543 assert(E->isRValue() && E->getType()->isVoidType());
10544 return VoidExprEvaluator(Info).Visit(E);
10545}
10546
10547//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010548// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010549//===----------------------------------------------------------------------===//
10550
Richard Smith2e312c82012-03-03 22:46:17 +000010551static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010552 // In C, function designators are not lvalues, but we evaluate them as if they
10553 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010554 QualType T = E->getType();
10555 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010556 LValue LV;
10557 if (!EvaluateLValue(E, LV, Info))
10558 return false;
10559 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010560 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010561 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010562 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010563 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010564 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010565 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010566 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010567 LValue LV;
10568 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010569 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010570 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010571 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010572 llvm::APFloat F(0.0);
10573 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010574 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010575 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010576 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010577 ComplexValue C;
10578 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010579 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010580 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010581 } else if (T->isFixedPointType()) {
10582 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010583 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010584 MemberPtr P;
10585 if (!EvaluateMemberPointer(E, P, Info))
10586 return false;
10587 P.moveInto(Result);
10588 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010589 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010590 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010591 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010592 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010593 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010594 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010595 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010596 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010597 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010598 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010599 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010600 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010601 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010602 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010603 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010604 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010605 if (!EvaluateVoid(E, Info))
10606 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010607 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010608 QualType Unqual = T.getAtomicUnqualifiedType();
10609 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10610 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010611 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010612 if (!EvaluateAtomic(E, &LV, Value, Info))
10613 return false;
10614 } else {
10615 if (!EvaluateAtomic(E, nullptr, Result, Info))
10616 return false;
10617 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010618 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010619 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010620 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010621 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010622 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010623 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010624 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010625
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010626 return true;
10627}
10628
Richard Smithb228a862012-02-15 02:18:13 +000010629/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10630/// cases, the in-place evaluation is essential, since later initializers for
10631/// an object can indirectly refer to subobjects which were initialized earlier.
10632static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010633 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010634 assert(!E->isValueDependent());
10635
Richard Smith7525ff62013-05-09 07:14:00 +000010636 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010637 return false;
10638
10639 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010640 // Evaluate arrays and record types in-place, so that later initializers can
10641 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010642 QualType T = E->getType();
10643 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010644 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010645 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010646 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010647 else if (T->isAtomicType()) {
10648 QualType Unqual = T.getAtomicUnqualifiedType();
10649 if (Unqual->isArrayType() || Unqual->isRecordType())
10650 return EvaluateAtomic(E, &This, Result, Info);
10651 }
Richard Smithed5165f2011-11-04 05:33:44 +000010652 }
10653
10654 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010655 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010656}
10657
Richard Smithf57d8cb2011-12-09 22:58:01 +000010658/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10659/// lvalue-to-rvalue cast if it is an lvalue.
10660static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010661 if (E->getType().isNull())
10662 return false;
10663
Nick Lewyckyc190f962017-05-02 01:06:16 +000010664 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010665 return false;
10666
Richard Smith2e312c82012-03-03 22:46:17 +000010667 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010668 return false;
10669
10670 if (E->isGLValue()) {
10671 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010672 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010673 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010674 return false;
10675 }
10676
Richard Smith2e312c82012-03-03 22:46:17 +000010677 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010678 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010679}
Richard Smith11562c52011-10-28 17:51:58 +000010680
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010681static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010682 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010683 // Fast-path evaluations of integer literals, since we sometimes see files
10684 // containing vast quantities of these.
10685 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10686 Result.Val = APValue(APSInt(L->getValue(),
10687 L->getType()->isUnsignedIntegerType()));
10688 IsConst = true;
10689 return true;
10690 }
James Dennett0492ef02014-03-14 17:44:10 +000010691
10692 // This case should be rare, but we need to check it before we check on
10693 // the type below.
10694 if (Exp->getType().isNull()) {
10695 IsConst = false;
10696 return true;
10697 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010698
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010699 // FIXME: Evaluating values of large array and record types can cause
10700 // performance problems. Only do so in C++11 for now.
10701 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10702 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010703 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010704 IsConst = false;
10705 return true;
10706 }
10707 return false;
10708}
10709
10710
Richard Smith7b553f12011-10-29 00:50:52 +000010711/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010712/// any crazy technique (that has nothing to do with language standards) that
10713/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010714/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10715/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010716bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010717 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010718 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010719 return IsConst;
Fangrui Song6907ce22018-07-30 19:24:48 +000010720
Richard Smith6d4c6582013-11-05 22:18:15 +000010721 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010722 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010723}
10724
Jay Foad39c79802011-01-12 09:06:06 +000010725bool Expr::EvaluateAsBooleanCondition(bool &Result,
10726 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010727 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010728 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010729 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010730}
10731
Richard Smith3f1d6de2018-05-21 20:36:58 +000010732static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10733 Expr::SideEffectsKind SEK) {
10734 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10735 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10736}
10737
Richard Smith5fab0c92011-12-28 19:48:30 +000010738bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10739 SideEffectsKind AllowSideEffects) const {
10740 if (!getType()->isIntegralOrEnumerationType())
10741 return false;
10742
Richard Smith11562c52011-10-28 17:51:58 +000010743 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010744 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010745 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010746 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010747
Richard Smith11562c52011-10-28 17:51:58 +000010748 Result = ExprResult.Val.getInt();
10749 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010750}
10751
Richard Trieube234c32016-04-21 21:04:55 +000010752bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10753 SideEffectsKind AllowSideEffects) const {
10754 if (!getType()->isRealFloatingType())
10755 return false;
10756
10757 EvalResult ExprResult;
10758 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010759 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010760 return false;
10761
10762 Result = ExprResult.Val.getFloat();
10763 return true;
10764}
10765
Jay Foad39c79802011-01-12 09:06:06 +000010766bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010767 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010768
John McCall45d55e42010-05-07 21:00:08 +000010769 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010770 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10771 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010772 Ctx.getLValueReferenceType(getType()), LV,
10773 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010774 return false;
10775
Richard Smith2e312c82012-03-03 22:46:17 +000010776 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010777 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010778}
10779
Reid Kleckner1a840d22018-05-10 18:57:35 +000010780bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10781 const ASTContext &Ctx) const {
10782 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10783 EvalInfo Info(Ctx, Result, EM);
10784 if (!::Evaluate(Result.Val, Info, this))
10785 return false;
10786
10787 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10788 Usage);
10789}
10790
Richard Smithd0b4dd62011-12-19 06:19:21 +000010791bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10792 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010793 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010794 // FIXME: Evaluating initializers for large array and record types can cause
10795 // performance problems. Only do so in C++11 for now.
10796 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010797 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010798 return false;
10799
Richard Smithd0b4dd62011-12-19 06:19:21 +000010800 Expr::EvalStatus EStatus;
10801 EStatus.Diag = &Notes;
10802
Richard Smith0c6124b2015-12-03 01:36:22 +000010803 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10804 ? EvalInfo::EM_ConstantExpression
10805 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010806 InitInfo.setEvaluatingDecl(VD, Value);
10807
10808 LValue LVal;
10809 LVal.set(VD);
10810
Richard Smithfddd3842011-12-30 21:15:51 +000010811 // C++11 [basic.start.init]p2:
10812 // Variables with static storage duration or thread storage duration shall be
10813 // zero-initialized before any other initialization takes place.
10814 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010815 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010816 !VD->getType()->isReferenceType()) {
10817 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010818 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010819 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010820 return false;
10821 }
10822
Richard Smith7525ff62013-05-09 07:14:00 +000010823 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10824 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010825 EStatus.HasSideEffects)
10826 return false;
10827
10828 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10829 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010830}
10831
Richard Smith7b553f12011-10-29 00:50:52 +000010832/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10833/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010834bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010835 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010836 return EvaluateAsRValue(Result, Ctx) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000010837 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010838}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010839
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010840APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010841 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010842 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010843 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010844 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010845 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010846 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010847 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010848
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010849 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010850}
John McCall864e3962010-05-07 05:32:02 +000010851
Richard Smithe9ff7702013-11-05 22:23:30 +000010852void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010853 bool IsConst;
10854 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010855 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010856 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010857 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10858 }
10859}
10860
Richard Smithe6c01442013-06-05 00:46:14 +000010861bool Expr::EvalResult::isGlobalLValue() const {
10862 assert(Val.isLValue());
10863 return IsGlobalLValue(Val.getLValueBase());
10864}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010865
10866
John McCall864e3962010-05-07 05:32:02 +000010867/// isIntegerConstantExpr - this recursive routine will test if an expression is
10868/// an integer constant expression.
10869
10870/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10871/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010872
10873// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010874// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10875// and a (possibly null) SourceLocation indicating the location of the problem.
10876//
John McCall864e3962010-05-07 05:32:02 +000010877// Note that to reduce code duplication, this helper does no evaluation
10878// itself; the caller checks whether the expression is evaluatable, and
10879// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010880// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010881
Dan Gohman28ade552010-07-26 21:25:24 +000010882namespace {
10883
Richard Smith9e575da2012-12-28 13:25:52 +000010884enum ICEKind {
10885 /// This expression is an ICE.
10886 IK_ICE,
10887 /// This expression is not an ICE, but if it isn't evaluated, it's
10888 /// a legal subexpression for an ICE. This return value is used to handle
10889 /// the comma operator in C99 mode, and non-constant subexpressions.
10890 IK_ICEIfUnevaluated,
10891 /// This expression is not an ICE, and is not a legal subexpression for one.
10892 IK_NotICE
10893};
10894
John McCall864e3962010-05-07 05:32:02 +000010895struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010896 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010897 SourceLocation Loc;
10898
Richard Smith9e575da2012-12-28 13:25:52 +000010899 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010900};
10901
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010902}
Dan Gohman28ade552010-07-26 21:25:24 +000010903
Richard Smith9e575da2012-12-28 13:25:52 +000010904static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10905
10906static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010907
Craig Toppera31a8822013-08-22 07:09:37 +000010908static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010909 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010910 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010911 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010912 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000010913
John McCall864e3962010-05-07 05:32:02 +000010914 return NoDiag();
10915}
10916
Craig Toppera31a8822013-08-22 07:09:37 +000010917static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010918 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010919 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010920 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000010921
10922 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010923#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010924#define STMT(Node, Base) case Expr::Node##Class:
10925#define EXPR(Node, Base)
10926#include "clang/AST/StmtNodes.inc"
10927 case Expr::PredefinedExprClass:
10928 case Expr::FloatingLiteralClass:
10929 case Expr::ImaginaryLiteralClass:
10930 case Expr::StringLiteralClass:
10931 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010932 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010933 case Expr::MemberExprClass:
10934 case Expr::CompoundAssignOperatorClass:
10935 case Expr::CompoundLiteralExprClass:
10936 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010937 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010938 case Expr::ArrayInitLoopExprClass:
10939 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010940 case Expr::NoInitExprClass:
10941 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010942 case Expr::ImplicitValueInitExprClass:
10943 case Expr::ParenListExprClass:
10944 case Expr::VAArgExprClass:
10945 case Expr::AddrLabelExprClass:
10946 case Expr::StmtExprClass:
10947 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010948 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010949 case Expr::CXXDynamicCastExprClass:
10950 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010951 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010952 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010953 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010954 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010955 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010956 case Expr::CXXThisExprClass:
10957 case Expr::CXXThrowExprClass:
10958 case Expr::CXXNewExprClass:
10959 case Expr::CXXDeleteExprClass:
10960 case Expr::CXXPseudoDestructorExprClass:
10961 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010962 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010963 case Expr::DependentScopeDeclRefExprClass:
10964 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010965 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010966 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010967 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010968 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010969 case Expr::CXXTemporaryObjectExprClass:
10970 case Expr::CXXUnresolvedConstructExprClass:
10971 case Expr::CXXDependentScopeMemberExprClass:
10972 case Expr::UnresolvedMemberExprClass:
10973 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010974 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010975 case Expr::ObjCArrayLiteralClass:
10976 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010977 case Expr::ObjCEncodeExprClass:
10978 case Expr::ObjCMessageExprClass:
10979 case Expr::ObjCSelectorExprClass:
10980 case Expr::ObjCProtocolExprClass:
10981 case Expr::ObjCIvarRefExprClass:
10982 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010983 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010984 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010985 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010986 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010987 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010988 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010989 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010990 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010991 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010992 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010993 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010994 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010995 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010996 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010997 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010998 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010999 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011000 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011001 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011002 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011003 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011004 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011005
Richard Smithf137f932014-01-25 20:50:08 +000011006 case Expr::InitListExprClass: {
11007 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11008 // form "T x = { a };" is equivalent to "T x = a;".
11009 // Unless we're initializing a reference, T is a scalar as it is known to be
11010 // of integral or enumeration type.
11011 if (E->isRValue())
11012 if (cast<InitListExpr>(E)->getNumInits() == 1)
11013 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011014 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011015 }
11016
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011017 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011018 case Expr::GNUNullExprClass:
11019 // GCC considers the GNU __null value to be an integral constant expression.
11020 return NoDiag();
11021
John McCall7c454bb2011-07-15 05:09:51 +000011022 case Expr::SubstNonTypeTemplateParmExprClass:
11023 return
11024 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11025
John McCall864e3962010-05-07 05:32:02 +000011026 case Expr::ParenExprClass:
11027 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011028 case Expr::GenericSelectionExprClass:
11029 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011030 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011031 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011032 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011033 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011034 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011035 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011036 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011037 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011038 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011039 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011040 return NoDiag();
11041 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011042 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011043 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11044 // constant expressions, but they can never be ICEs because an ICE cannot
11045 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011046 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011047 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011048 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011049 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011050 }
Richard Smith6365c912012-02-24 22:12:32 +000011051 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011052 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11053 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011054 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011055 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011056 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011057 // Parameter variables are never constants. Without this check,
11058 // getAnyInitializer() can find a default argument, which leads
11059 // to chaos.
11060 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011061 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011062
11063 // C++ 7.1.5.1p2
11064 // A variable of non-volatile const-qualified integral or enumeration
11065 // type initialized by an ICE can be used in ICEs.
11066 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011067 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011068 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011069
Richard Smithd0b4dd62011-12-19 06:19:21 +000011070 const VarDecl *VD;
11071 // Look for a declaration of this variable that has an initializer, and
11072 // check whether it is an ICE.
11073 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11074 return NoDiag();
11075 else
Richard Smith9e575da2012-12-28 13:25:52 +000011076 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011077 }
11078 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011079 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011080 }
John McCall864e3962010-05-07 05:32:02 +000011081 case Expr::UnaryOperatorClass: {
11082 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11083 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011084 case UO_PostInc:
11085 case UO_PostDec:
11086 case UO_PreInc:
11087 case UO_PreDec:
11088 case UO_AddrOf:
11089 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011090 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011091 // C99 6.6/3 allows increment and decrement within unevaluated
11092 // subexpressions of constant expressions, but they can never be ICEs
11093 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011094 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011095 case UO_Extension:
11096 case UO_LNot:
11097 case UO_Plus:
11098 case UO_Minus:
11099 case UO_Not:
11100 case UO_Real:
11101 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011102 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011103 }
Richard Smith9e575da2012-12-28 13:25:52 +000011104
John McCall864e3962010-05-07 05:32:02 +000011105 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000011106 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000011107 }
11108 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011109 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11110 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11111 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11112 // compliance: we should warn earlier for offsetof expressions with
11113 // array subscripts that aren't ICEs, and if the array subscripts
11114 // are ICEs, the value of the offsetof must be an integer constant.
11115 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011116 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011117 case Expr::UnaryExprOrTypeTraitExprClass: {
11118 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11119 if ((Exp->getKind() == UETT_SizeOf) &&
11120 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011121 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011122 return NoDiag();
11123 }
11124 case Expr::BinaryOperatorClass: {
11125 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11126 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011127 case BO_PtrMemD:
11128 case BO_PtrMemI:
11129 case BO_Assign:
11130 case BO_MulAssign:
11131 case BO_DivAssign:
11132 case BO_RemAssign:
11133 case BO_AddAssign:
11134 case BO_SubAssign:
11135 case BO_ShlAssign:
11136 case BO_ShrAssign:
11137 case BO_AndAssign:
11138 case BO_XorAssign:
11139 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011140 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11141 // constant expressions, but they can never be ICEs because an ICE cannot
11142 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011143 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011144
John McCalle3027922010-08-25 11:45:40 +000011145 case BO_Mul:
11146 case BO_Div:
11147 case BO_Rem:
11148 case BO_Add:
11149 case BO_Sub:
11150 case BO_Shl:
11151 case BO_Shr:
11152 case BO_LT:
11153 case BO_GT:
11154 case BO_LE:
11155 case BO_GE:
11156 case BO_EQ:
11157 case BO_NE:
11158 case BO_And:
11159 case BO_Xor:
11160 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011161 case BO_Comma:
11162 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011163 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11164 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011165 if (Exp->getOpcode() == BO_Div ||
11166 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011167 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011168 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011169 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011170 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011171 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011172 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011173 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011174 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011175 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011176 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011177 }
11178 }
11179 }
John McCalle3027922010-08-25 11:45:40 +000011180 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011181 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011182 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11183 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011184 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011185 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011186 } else {
11187 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011188 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011189 }
11190 }
Richard Smith9e575da2012-12-28 13:25:52 +000011191 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011192 }
John McCalle3027922010-08-25 11:45:40 +000011193 case BO_LAnd:
11194 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011195 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11196 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011197 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011198 // Rare case where the RHS has a comma "side-effect"; we need
11199 // to actually check the condition to see whether the side
11200 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011201 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011202 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011203 return RHSResult;
11204 return NoDiag();
11205 }
11206
Richard Smith9e575da2012-12-28 13:25:52 +000011207 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011208 }
11209 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000011210 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000011211 }
11212 case Expr::ImplicitCastExprClass:
11213 case Expr::CStyleCastExprClass:
11214 case Expr::CXXFunctionalCastExprClass:
11215 case Expr::CXXStaticCastExprClass:
11216 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011217 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011218 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011219 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011220 if (isa<ExplicitCastExpr>(E)) {
11221 if (const FloatingLiteral *FL
11222 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11223 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11224 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11225 APSInt IgnoredVal(DestWidth, !DestSigned);
11226 bool Ignored;
11227 // If the value does not fit in the destination type, the behavior is
11228 // undefined, so we are not required to treat it as a constant
11229 // expression.
11230 if (FL->getValue().convertToInteger(IgnoredVal,
11231 llvm::APFloat::rmTowardZero,
11232 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011233 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011234 return NoDiag();
11235 }
11236 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011237 switch (cast<CastExpr>(E)->getCastKind()) {
11238 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011239 case CK_AtomicToNonAtomic:
11240 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011241 case CK_NoOp:
11242 case CK_IntegralToBoolean:
11243 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011244 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011245 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011246 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011247 }
John McCall864e3962010-05-07 05:32:02 +000011248 }
John McCallc07a0c72011-02-17 10:25:35 +000011249 case Expr::BinaryConditionalOperatorClass: {
11250 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11251 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011252 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011253 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011254 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11255 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11256 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011257 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011258 return FalseResult;
11259 }
John McCall864e3962010-05-07 05:32:02 +000011260 case Expr::ConditionalOperatorClass: {
11261 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11262 // If the condition (ignoring parens) is a __builtin_constant_p call,
11263 // then only the true side is actually considered in an integer constant
11264 // expression, and it is fully evaluated. This is an important GNU
11265 // extension. See GCC PR38377 for discussion.
11266 if (const CallExpr *CallCE
11267 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011268 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011269 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011270 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011271 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011272 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011273
Richard Smithf57d8cb2011-12-09 22:58:01 +000011274 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11275 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011276
Richard Smith9e575da2012-12-28 13:25:52 +000011277 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011278 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011279 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011280 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011281 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011282 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011283 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011284 return NoDiag();
11285 // Rare case where the diagnostics depend on which side is evaluated
11286 // Note that if we get here, CondResult is 0, and at least one of
11287 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011288 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011289 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011290 return TrueResult;
11291 }
11292 case Expr::CXXDefaultArgExprClass:
11293 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011294 case Expr::CXXDefaultInitExprClass:
11295 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011296 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011297 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011298 }
11299 }
11300
David Blaikiee4d798f2012-01-20 21:50:17 +000011301 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011302}
11303
Richard Smithf57d8cb2011-12-09 22:58:01 +000011304/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011305static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011306 const Expr *E,
11307 llvm::APSInt *Value,
11308 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011309 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011310 if (Loc) *Loc = E->getExprLoc();
11311 return false;
11312 }
11313
Richard Smith66e05fe2012-01-18 05:21:49 +000011314 APValue Result;
11315 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011316 return false;
11317
Richard Smith98710fc2014-11-13 23:03:19 +000011318 if (!Result.isInt()) {
11319 if (Loc) *Loc = E->getExprLoc();
11320 return false;
11321 }
11322
Richard Smith66e05fe2012-01-18 05:21:49 +000011323 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011324 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011325}
11326
Craig Toppera31a8822013-08-22 07:09:37 +000011327bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11328 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011329 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011330 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011331
Richard Smith9e575da2012-12-28 13:25:52 +000011332 ICEDiag D = CheckICE(this, Ctx);
11333 if (D.Kind != IK_ICE) {
11334 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011335 return false;
11336 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011337 return true;
11338}
11339
Craig Toppera31a8822013-08-22 07:09:37 +000011340bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011341 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011342 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011343 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11344
11345 if (!isIntegerConstantExpr(Ctx, Loc))
11346 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000011347 // The only possible side-effects here are due to UB discovered in the
11348 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11349 // required to treat the expression as an ICE, so we produce the folded
11350 // value.
11351 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000011352 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000011353 return true;
11354}
Richard Smith66e05fe2012-01-18 05:21:49 +000011355
Craig Toppera31a8822013-08-22 07:09:37 +000011356bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011357 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011358}
11359
Craig Toppera31a8822013-08-22 07:09:37 +000011360bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011361 SourceLocation *Loc) const {
11362 // We support this checking in C++98 mode in order to diagnose compatibility
11363 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011364 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011365
Richard Smith98a0a492012-02-14 21:38:30 +000011366 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011367 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011368 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011369 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011370 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011371
11372 APValue Scratch;
11373 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11374
11375 if (!Diags.empty()) {
11376 IsConstExpr = false;
11377 if (Loc) *Loc = Diags[0].first;
11378 } else if (!IsConstExpr) {
11379 // FIXME: This shouldn't happen.
11380 if (Loc) *Loc = getExprLoc();
11381 }
11382
11383 return IsConstExpr;
11384}
Richard Smith253c2a32012-01-27 01:14:48 +000011385
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011386bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11387 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011388 ArrayRef<const Expr*> Args,
11389 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011390 Expr::EvalStatus Status;
11391 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11392
George Burgess IV177399e2017-01-09 04:12:14 +000011393 LValue ThisVal;
11394 const LValue *ThisPtr = nullptr;
11395 if (This) {
11396#ifndef NDEBUG
11397 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11398 assert(MD && "Don't provide `this` for non-methods.");
11399 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11400#endif
11401 if (EvaluateObjectArgument(Info, This, ThisVal))
11402 ThisPtr = &ThisVal;
11403 if (Info.EvalStatus.HasSideEffects)
11404 return false;
11405 }
11406
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011407 ArgVector ArgValues(Args.size());
11408 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11409 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011410 if ((*I)->isValueDependent() ||
11411 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011412 // If evaluation fails, throw away the argument entirely.
11413 ArgValues[I - Args.begin()] = APValue();
11414 if (Info.EvalStatus.HasSideEffects)
11415 return false;
11416 }
11417
11418 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011419 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011420 ArgValues.data());
11421 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11422}
11423
Richard Smith253c2a32012-01-27 01:14:48 +000011424bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011425 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011426 PartialDiagnosticAt> &Diags) {
11427 // FIXME: It would be useful to check constexpr function templates, but at the
11428 // moment the constant expression evaluator cannot cope with the non-rigorous
11429 // ASTs which we build for dependent expressions.
11430 if (FD->isDependentContext())
11431 return true;
11432
11433 Expr::EvalStatus Status;
11434 Status.Diag = &Diags;
11435
Richard Smith6d4c6582013-11-05 22:18:15 +000011436 EvalInfo Info(FD->getASTContext(), Status,
11437 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000011438
11439 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011440 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011441
Richard Smith7525ff62013-05-09 07:14:00 +000011442 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011443 // is a temporary being used as the 'this' pointer.
11444 LValue This;
11445 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011446 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011447
Richard Smith253c2a32012-01-27 01:14:48 +000011448 ArrayRef<const Expr*> Args;
11449
Richard Smith2e312c82012-03-03 22:46:17 +000011450 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011451 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11452 // Evaluate the call as a constant initializer, to allow the construction
11453 // of objects of non-literal types.
11454 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011455 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11456 } else {
11457 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011458 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011459 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011460 }
Richard Smith253c2a32012-01-27 01:14:48 +000011461
11462 return Diags.empty();
11463}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011464
11465bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11466 const FunctionDecl *FD,
11467 SmallVectorImpl<
11468 PartialDiagnosticAt> &Diags) {
11469 Expr::EvalStatus Status;
11470 Status.Diag = &Diags;
11471
11472 EvalInfo Info(FD->getASTContext(), Status,
11473 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11474
11475 // Fabricate a call stack frame to give the arguments a plausible cover story.
11476 ArrayRef<const Expr*> Args;
11477 ArgVector ArgValues(0);
11478 bool Success = EvaluateArgs(Args, ArgValues, Info);
11479 (void)Success;
11480 assert(Success &&
11481 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011482 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011483
11484 APValue ResultScratch;
11485 Evaluate(ResultScratch, Info, E);
11486 return Diags.empty();
11487}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011488
11489bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11490 unsigned Type) const {
11491 if (!getType()->isPointerType())
11492 return false;
11493
11494 Expr::EvalStatus Status;
11495 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011496 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011497}