blob: 8c56a3cc5504d7ad8ff86a768bc44ef09fea9243 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
Nandor Licker950b70d2019-09-13 09:46:16 +000035#include <cstring>
36#include <functional>
37#include "Interp/Context.h"
38#include "Interp/Frame.h"
39#include "Interp/State.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000040#include "clang/AST/APValue.h"
41#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000042#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000043#include "clang/AST/ASTLambda.h"
Nandor Licker7bd0a782019-08-29 21:57:47 +000044#include "clang/AST/CXXInheritance.h"
Ken Dyck40775002010-01-11 17:06:35 +000045#include "clang/AST/CharUnits.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000046#include "clang/AST/CurrentSourceLocExprScope.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000048#include "clang/AST/OSLog.h"
Nandor Licker950b70d2019-09-13 09:46:16 +000049#include "clang/AST/OptionalDiagnostic.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000050#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000051#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000052#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000053#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000054#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000055#include "clang/Basic/TargetInfo.h"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000056#include "llvm/ADT/Optional.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000057#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000058#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000059#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000060
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000061#define DEBUG_TYPE "exprconstant"
62
Anders Carlsson7a241ba2008-07-03 04:20:39 +000063using namespace clang;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000064using llvm::APInt;
Chris Lattner05706e882008-07-11 18:11:29 +000065using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000066using llvm::APFloat;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000067using llvm::Optional;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000068
John McCall93d91dc2010-05-07 17:22:02 +000069namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000070 struct LValue;
Nandor Licker950b70d2019-09-13 09:46:16 +000071 class CallStackFrame;
72 class EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000073
Eric Fiselier708afb52019-05-16 21:04:15 +000074 using SourceLocExprScopeGuard =
75 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
76
Richard Smithb228a862012-02-15 02:18:13 +000077 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000078 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000079 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000080 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000081 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000082 //
83 // extern int arr[]; void f() { extern int arr[3]; };
84 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000085 //
86 // For now, we take the array bound from the most recent declaration.
87 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
88 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
89 QualType T = Redecl->getType();
90 if (!T->isIncompleteArrayType())
91 return T;
92 }
93 return D->getType();
94 }
Richard Smith84401042013-06-03 05:03:02 +000095
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000096 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000097 return B.getTypeInfoType();
98
Richard Smithda1b4342019-09-27 01:26:47 +000099 if (B.is<DynamicAllocLValue>())
100 return B.getDynamicAllocType();
101
Richard Smith84401042013-06-03 05:03:02 +0000102 const Expr *Base = B.get<const Expr*>();
103
104 // For a materialized temporary, the type of the temporary we materialized
105 // may not be the type of the expression.
106 if (const MaterializeTemporaryExpr *MTE =
107 dyn_cast<MaterializeTemporaryExpr>(Base)) {
108 SmallVector<const Expr *, 2> CommaLHSs;
109 SmallVector<SubobjectAdjustment, 2> Adjustments;
110 const Expr *Temp = MTE->GetTemporaryExpr();
111 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
112 Adjustments);
113 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000114 // for it directly. Otherwise use the type after adjustment.
115 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000116 return Inner->getType();
117 }
118
119 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000120 }
121
Richard Smithd62306a2011-11-10 06:34:14 +0000122 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000123 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000125 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127 /// Get an LValue path entry, which is known to not be an array index, as a
128 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000129 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000130 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000131 }
132 /// Determine whether this LValue path entry for a base class names a virtual
133 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000134 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000135 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000136 }
137
Richard Smith457226e2019-09-23 03:48:44 +0000138 /// Given an expression, determine the type used to store the result of
139 /// evaluating that expression.
140 static QualType getStorageType(ASTContext &Ctx, Expr *E) {
141 if (E->isRValue())
142 return E->getType();
143 return Ctx.getLValueReferenceType(E->getType());
144 }
145
George Burgess IVe3763372016-12-22 02:50:20 +0000146 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
147 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
148 const FunctionDecl *Callee = CE->getDirectCallee();
149 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
150 }
151
152 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
153 /// This will look through a single cast.
154 ///
155 /// Returns null if we couldn't unwrap a function with alloc_size.
156 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
157 if (!E->getType()->isPointerType())
158 return nullptr;
159
160 E = E->IgnoreParens();
161 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000162 // probably be a cast of some kind. In exotic cases, we might also see a
163 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000164 if (const auto *FE = dyn_cast<FullExpr>(E))
165 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000166
George Burgess IVe3763372016-12-22 02:50:20 +0000167 if (const auto *Cast = dyn_cast<CastExpr>(E))
168 E = Cast->getSubExpr()->IgnoreParens();
169
170 if (const auto *CE = dyn_cast<CallExpr>(E))
171 return getAllocSizeAttr(CE) ? CE : nullptr;
172 return nullptr;
173 }
174
175 /// Determines whether or not the given Base contains a call to a function
176 /// with the alloc_size attribute.
177 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
178 const auto *E = Base.dyn_cast<const Expr *>();
179 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
180 }
181
Richard Smith6f4f0f12017-10-20 22:56:25 +0000182 /// The bound to claim that an array of unknown bound has.
183 /// The value in MostDerivedArraySize is undefined in this case. So, set it
184 /// to an arbitrary value that's likely to loudly break things if it's used.
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
187
George Burgess IVe3763372016-12-22 02:50:20 +0000188 /// Determines if an LValue with the given LValueBase will have an unsized
189 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 /// Find the path length and type of the most-derived subobject in the given
191 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000192 static unsigned
193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
194 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000195 uint64_t &ArraySize, QualType &Type, bool &IsArray,
196 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000197 // This only accepts LValueBases from APValues, and APValues don't support
198 // arrays that lack size info.
199 assert(!isBaseAnAllocSizeCall(Base) &&
200 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000201 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000202 Type = getType(Base);
203
Richard Smith80815602011-11-07 05:07:52 +0000204 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000205 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000206 const ArrayType *AT = Ctx.getAsArrayType(Type);
207 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000209 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000210
211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getSize().getZExtValue();
213 } else {
214 assert(I == 0 && "unexpected unsized array designator");
215 FirstEntryIsUnsizedArray = true;
216 ArraySize = AssumedSizeForUnsizedArray;
217 }
Richard Smith66c96992012-02-18 22:04:06 +0000218 } else if (Type->isAnyComplexType()) {
219 const ComplexType *CT = Type->castAs<ComplexType>();
220 Type = CT->getElementType();
221 ArraySize = 2;
222 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 } else if (const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
226 ArraySize = 0;
227 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000228 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000229 } else {
Richard Smith80815602011-11-07 05:07:52 +0000230 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000231 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000232 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 }
Richard Smith80815602011-11-07 05:07:52 +0000234 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000236 }
237
Richard Smith96e0c102011-11-04 02:25:55 +0000238 /// A path from a glvalue to a subobject of that glvalue.
239 struct SubobjectDesignator {
240 /// True if the subobject was named in a manner not supported by C++11. Such
241 /// lvalues can still be folded, but they are not core constant expressions
242 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000243 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000244
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000246 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000247
Daniel Jasperffdee092017-05-02 19:21:42 +0000248 /// Indicator of whether the first entry is an unsized array.
249 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000250
George Burgess IVa51c4072015-10-16 01:49:01 +0000251 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000252 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000253
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 /// The length of the path to the most-derived object of which this is a
255 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000256 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
George Burgess IVa51c4072015-10-16 01:49:01 +0000258 /// The size of the array of which the most-derived object is an element.
259 /// This will always be 0 if the most-derived object is not an array
260 /// element. 0 is not an indicator of whether or not the most-derived object
261 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000262 ///
263 /// If the current array is an unsized array, the value of this is
264 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 uint64_t MostDerivedArraySize;
266
267 /// The type of the most derived object referred to by this address.
268 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000269
Richard Smith80815602011-11-07 05:07:52 +0000270 typedef APValue::LValuePathEntry PathEntry;
271
Richard Smith96e0c102011-11-04 02:25:55 +0000272 /// The entries on the path from the glvalue to the designated subobject.
273 SmallVector<PathEntry, 8> Entries;
274
Richard Smitha8105bc2012-01-06 16:39:00 +0000275 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000276
Richard Smitha8105bc2012-01-06 16:39:00 +0000277 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000278 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000280 MostDerivedPathLength(0), MostDerivedArraySize(0),
281 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000282
283 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000286 MostDerivedPathLength(0), MostDerivedArraySize(0) {
287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000288 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000289 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000290 ArrayRef<PathEntry> VEntries = V.getLValuePath();
291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000292 if (V.getLValueBase()) {
293 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000294 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000295 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000297 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000298 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000300 }
Richard Smith80815602011-11-07 05:07:52 +0000301 }
302 }
303
Richard Smith31c69a32019-05-21 23:15:20 +0000304 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305 unsigned NewLength) {
306 if (Invalid)
307 return;
308
309 assert(Base && "cannot truncate path for null pointer");
310 assert(NewLength <= Entries.size() && "not a truncation");
311
312 if (NewLength == Entries.size())
313 return;
314 Entries.resize(NewLength);
315
316 bool IsArray = false;
317 bool FirstIsUnsizedArray = false;
318 MostDerivedPathLength = findMostDerivedSubobject(
319 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320 FirstIsUnsizedArray);
321 MostDerivedIsArrayElement = IsArray;
322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323 }
324
Richard Smith96e0c102011-11-04 02:25:55 +0000325 void setInvalid() {
326 Invalid = true;
327 Entries.clear();
328 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000329
George Burgess IVe3763372016-12-22 02:50:20 +0000330 /// Determine whether the most derived subobject is an array without a
331 /// known bound.
332 bool isMostDerivedAnUnsizedArray() const {
333 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000335 }
336
337 /// Determine what the most derived array's size is. Results in an assertion
338 /// failure if the most derived array lacks a size.
339 uint64_t getMostDerivedArraySize() const {
340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
341 return MostDerivedArraySize;
342 }
343
Richard Smitha8105bc2012-01-06 16:39:00 +0000344 /// Determine whether this is a one-past-the-end pointer.
345 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000346 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000347 if (IsOnePastTheEnd)
348 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000352 return true;
353 return false;
354 }
355
Richard Smith06f71b52018-08-04 00:57:17 +0000356 /// Get the range of valid index adjustments in the form
357 /// {maximum value that can be subtracted from this pointer,
358 /// maximum value that can be added to this pointer}
359 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360 if (Invalid || isMostDerivedAnUnsizedArray())
361 return {0, 0};
362
363 // [expr.add]p4: For the purposes of these operators, a pointer to a
364 // nonarray object behaves the same as a pointer to the first element of
365 // an array of length one with the type of the object as its element type.
366 bool IsArray = MostDerivedPathLength == Entries.size() &&
367 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000370 uint64_t ArraySize =
371 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372 return {ArrayIndex, ArraySize - ArrayIndex};
373 }
374
Richard Smitha8105bc2012-01-06 16:39:00 +0000375 /// Check that this refers to a valid subobject.
376 bool isValidSubobject() const {
377 if (Invalid)
378 return false;
379 return !isOnePastTheEnd();
380 }
381 /// Check that this refers to a valid subobject, and if not, produce a
382 /// relevant diagnostic and set the designator as invalid.
383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
384
Richard Smith06f71b52018-08-04 00:57:17 +0000385 /// Get the type of the designated object.
386 QualType getType(ASTContext &Ctx) const {
387 assert(!Invalid && "invalid designator has no subobject type");
388 return MostDerivedPathLength == Entries.size()
389 ? MostDerivedType
390 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391 }
392
Richard Smitha8105bc2012-01-06 16:39:00 +0000393 /// Update this designator to refer to the first element within this array.
394 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000395 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000396
397 // This is a most-derived object.
398 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000399 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000400 MostDerivedArraySize = CAT->getSize().getZExtValue();
401 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000402 }
George Burgess IVe3763372016-12-22 02:50:20 +0000403 /// Update this designator to refer to the first element within the array of
404 /// elements of type T. This is an array of unknown size.
405 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000406 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000407
408 MostDerivedType = ElemTy;
409 MostDerivedIsArrayElement = true;
410 // The value in MostDerivedArraySize is undefined in this case. So, set it
411 // to an arbitrary value that's likely to loudly break things if it's
412 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000413 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000414 MostDerivedPathLength = Entries.size();
415 }
Richard Smith96e0c102011-11-04 02:25:55 +0000416 /// Update this designator to refer to the given base or member of this
417 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000418 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000420
421 // If this isn't a base class, it's a new most-derived object.
422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000424 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000425 MostDerivedArraySize = 0;
426 MostDerivedPathLength = Entries.size();
427 }
Richard Smith96e0c102011-11-04 02:25:55 +0000428 }
Richard Smith66c96992012-02-18 22:04:06 +0000429 /// Update this designator to refer to the given complex component.
430 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000431 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000432
433 // This is technically a most-derived object, though in practice this
434 // is unlikely to matter.
435 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000436 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000437 MostDerivedArraySize = 2;
438 MostDerivedPathLength = Entries.size();
439 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
442 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000443 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445 if (Invalid || !N) return;
446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000448 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000449 // Can't verify -- trust that the user is doing the right thing (or if
450 // not, trust that the caller will catch the bad behavior).
451 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000452 Entries.back() = PathEntry::ArrayIndex(
453 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000454 return;
455 }
456
457 // [expr.add]p4: For the purposes of these operators, a pointer to a
458 // nonarray object behaves the same as a pointer to the first element of
459 // an array of length one with the type of the object as its element type.
460 bool IsArray = MostDerivedPathLength == Entries.size() &&
461 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000464 uint64_t ArraySize =
465 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
466
467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468 // Calculate the actual index in a wide enough type, so we can include
469 // it in the note.
470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471 (llvm::APInt&)N += ArrayIndex;
472 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
473 diagnosePointerArithmetic(Info, E, N);
474 setInvalid();
475 return;
476 }
477
478 ArrayIndex += TruncatedN;
479 assert(ArrayIndex <= ArraySize &&
480 "bounds check succeeded for out-of-bounds index");
481
482 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000484 else
485 IsOnePastTheEnd = (ArrayIndex != 0);
486 }
Richard Smith96e0c102011-11-04 02:25:55 +0000487 };
488
Richard Smith254a73d2011-10-28 22:34:42 +0000489 /// A stack frame in the constexpr call stack.
Nandor Licker950b70d2019-09-13 09:46:16 +0000490 class CallStackFrame : public interp::Frame {
491 public:
Richard Smith254a73d2011-10-28 22:34:42 +0000492 EvalInfo &Info;
493
494 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000495 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000496
Richard Smithf6f003a2011-12-16 19:06:07 +0000497 /// Callee - The function which was called.
498 const FunctionDecl *Callee;
499
Richard Smithd62306a2011-11-10 06:34:14 +0000500 /// This - The binding for the this pointer in this call, if any.
501 const LValue *This;
502
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000503 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000504 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000505 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000506
Eric Fiselier708afb52019-05-16 21:04:15 +0000507 /// Source location information about the default argument or default
508 /// initializer expression we're evaluating, if any.
509 CurrentSourceLocExprScope CurSourceLocExprScope;
510
Eli Friedman4830ec82012-06-25 21:21:08 +0000511 // Note that we intentionally use std::map here so that references to
512 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000513 typedef std::pair<const void *, unsigned> MapKeyTy;
514 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000515 /// Temporaries - Temporary lvalues materialized within this stack frame.
516 MapTy Temporaries;
517
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000518 /// CallLoc - The location of the call expression for this call.
519 SourceLocation CallLoc;
520
521 /// Index - The call index of this call.
522 unsigned Index;
523
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000524 /// The stack of integers for tracking version numbers for temporaries.
525 SmallVector<unsigned, 2> TempVersionStack = {1};
526 unsigned CurTempVersion = TempVersionStack.back();
527
528 unsigned getTempVersion() const { return TempVersionStack.back(); }
529
530 void pushTempVersion() {
531 TempVersionStack.push_back(++CurTempVersion);
532 }
533
534 void popTempVersion() {
535 TempVersionStack.pop_back();
536 }
537
Faisal Vali051e3a22017-02-16 04:12:21 +0000538 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000539 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000540 // (We should cache this map rather than recomputing it repeatedly.)
541 // But let's try this and see how it goes; we can look into caching the map
542 // as a later change.
543
544 /// LambdaCaptureFields - Mapping from captured variables/this to
545 /// corresponding data members in the closure class.
546 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
547 FieldDecl *LambdaThisCaptureField;
548
Richard Smithf6f003a2011-12-16 19:06:07 +0000549 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
550 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000551 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000552 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000553
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000554 // Return the temporary for Key whose version number is Version.
555 APValue *getTemporary(const void *Key, unsigned Version) {
556 MapKeyTy KV(Key, Version);
557 auto LB = Temporaries.lower_bound(KV);
558 if (LB != Temporaries.end() && LB->first == KV)
559 return &LB->second;
560 // Pair (Key,Version) wasn't found in the map. Check that no elements
561 // in the map have 'Key' as their key.
562 assert((LB == Temporaries.end() || LB->first.first != Key) &&
563 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
564 "Element with key 'Key' found in map");
565 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000566 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000567
568 // Return the current temporary for Key in the map.
569 APValue *getCurrentTemporary(const void *Key) {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return &std::prev(UB)->second;
573 return nullptr;
574 }
575
576 // Return the version number of the current temporary for Key.
577 unsigned getCurrentTemporaryVersion(const void *Key) const {
578 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
579 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
580 return std::prev(UB)->first.second;
581 return 0;
582 }
583
Richard Smith457226e2019-09-23 03:48:44 +0000584 /// Allocate storage for an object of type T in this stack frame.
585 /// Populates LV with a handle to the created object. Key identifies
586 /// the temporary within the stack frame, and must not be reused without
587 /// bumping the temporary version number.
588 template<typename KeyT>
589 APValue &createTemporary(const KeyT *Key, QualType T,
590 bool IsLifetimeExtended, LValue &LV);
Nandor Licker950b70d2019-09-13 09:46:16 +0000591
592 void describe(llvm::raw_ostream &OS) override;
593
594 Frame *getCaller() const override { return Caller; }
595 SourceLocation getCallLocation() const override { return CallLoc; }
596 const FunctionDecl *getCallee() const override { return Callee; }
Richard Smithb5426022019-10-03 00:39:35 +0000597
598 bool isStdFunction() const {
599 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
600 if (DC->isStdNamespace())
601 return true;
602 return false;
603 }
Richard Smith254a73d2011-10-28 22:34:42 +0000604 };
605
Richard Smith852c9db2013-04-20 22:23:05 +0000606 /// Temporarily override 'this'.
607 class ThisOverrideRAII {
608 public:
609 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
610 : Frame(Frame), OldThis(Frame.This) {
611 if (Enable)
612 Frame.This = NewThis;
613 }
614 ~ThisOverrideRAII() {
615 Frame.This = OldThis;
616 }
617 private:
618 CallStackFrame &Frame;
619 const LValue *OldThis;
620 };
Richard Smith457226e2019-09-23 03:48:44 +0000621}
Richard Smith852c9db2013-04-20 22:23:05 +0000622
Richard Smith61422f92019-09-27 20:24:36 +0000623static bool HandleDestruction(EvalInfo &Info, const Expr *E,
624 const LValue &This, QualType ThisType);
625static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
626 APValue::LValueBase LVBase, APValue &Value,
627 QualType T);
Richard Smith457226e2019-09-23 03:48:44 +0000628
629namespace {
Richard Smith08d6a2c2013-07-24 07:11:57 +0000630 /// A cleanup, and a flag indicating whether it is lifetime-extended.
631 class Cleanup {
632 llvm::PointerIntPair<APValue*, 1, bool> Value;
Richard Smith457226e2019-09-23 03:48:44 +0000633 APValue::LValueBase Base;
634 QualType T;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000635
636 public:
Richard Smith457226e2019-09-23 03:48:44 +0000637 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
638 bool IsLifetimeExtended)
639 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
Richard Smith08d6a2c2013-07-24 07:11:57 +0000640
641 bool isLifetimeExtended() const { return Value.getInt(); }
Richard Smith457226e2019-09-23 03:48:44 +0000642 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
Richard Smithda1b4342019-09-27 01:26:47 +0000643 if (RunDestructors) {
644 SourceLocation Loc;
645 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
646 Loc = VD->getLocation();
647 else if (const Expr *E = Base.dyn_cast<const Expr*>())
648 Loc = E->getExprLoc();
Richard Smith61422f92019-09-27 20:24:36 +0000649 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
Richard Smithda1b4342019-09-27 01:26:47 +0000650 }
Richard Smith08d6a2c2013-07-24 07:11:57 +0000651 *Value.getPointer() = APValue();
Richard Smith457226e2019-09-23 03:48:44 +0000652 return true;
653 }
654
655 bool hasSideEffect() {
656 return T.isDestructedType();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000657 }
658 };
659
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000660 /// A reference to an object whose construction we are currently evaluating.
661 struct ObjectUnderConstruction {
662 APValue::LValueBase Base;
663 ArrayRef<APValue::LValuePathEntry> Path;
664 friend bool operator==(const ObjectUnderConstruction &LHS,
665 const ObjectUnderConstruction &RHS) {
666 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
667 }
668 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
669 return llvm::hash_combine(Obj.Base, Obj.Path);
670 }
671 };
Richard Smith457226e2019-09-23 03:48:44 +0000672 enum class ConstructionPhase {
673 None,
674 Bases,
675 AfterBases,
676 Destroying,
677 DestroyingBases
678 };
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000679}
680
681namespace llvm {
682template<> struct DenseMapInfo<ObjectUnderConstruction> {
683 using Base = DenseMapInfo<APValue::LValueBase>;
684 static ObjectUnderConstruction getEmptyKey() {
685 return {Base::getEmptyKey(), {}}; }
686 static ObjectUnderConstruction getTombstoneKey() {
687 return {Base::getTombstoneKey(), {}};
688 }
689 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
690 return hash_value(Object);
691 }
692 static bool isEqual(const ObjectUnderConstruction &LHS,
693 const ObjectUnderConstruction &RHS) {
694 return LHS == RHS;
695 }
696};
697}
698
699namespace {
Richard Smith19ad5232019-10-03 00:39:33 +0000700 /// A dynamically-allocated heap object.
701 struct DynAlloc {
702 /// The value of this heap-allocated object.
703 APValue Value;
704 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
705 /// or a CallExpr (the latter is for direct calls to operator new inside
706 /// std::allocator<T>::allocate).
707 const Expr *AllocExpr = nullptr;
708
709 enum Kind {
710 New,
711 ArrayNew,
712 StdAllocator
713 };
714
715 /// Get the kind of the allocation. This must match between allocation
716 /// and deallocation.
717 Kind getKind() const {
718 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
719 return NE->isArray() ? ArrayNew : New;
720 assert(isa<CallExpr>(AllocExpr));
721 return StdAllocator;
722 }
723 };
724
725 struct DynAllocOrder {
726 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
727 return L.getIndex() < R.getIndex();
728 }
729 };
730
Richard Smithb228a862012-02-15 02:18:13 +0000731 /// EvalInfo - This is a private struct used by the evaluator to capture
732 /// information about a subexpression as it is folded. It retains information
733 /// about the AST context, but also maintains information about the folded
734 /// expression.
735 ///
736 /// If an expression could be evaluated, it is still possible it is not a C
737 /// "integer constant expression" or constant expression. If not, this struct
738 /// captures information about how and why not.
739 ///
740 /// One bit of information passed *into* the request for constant folding
741 /// indicates whether the subexpression is "evaluated" or not according to C
742 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
743 /// evaluate the expression regardless of what the RHS is, but C only allows
744 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000745 class EvalInfo : public interp::State {
746 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000747 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000748
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000749 /// EvalStatus - Contains information about the evaluation.
750 Expr::EvalStatus &EvalStatus;
751
752 /// CurrentCall - The top of the constexpr call stack.
753 CallStackFrame *CurrentCall;
754
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000755 /// CallStackDepth - The number of calls in the call stack right now.
756 unsigned CallStackDepth;
757
Richard Smithb228a862012-02-15 02:18:13 +0000758 /// NextCallIndex - The next call index to assign.
759 unsigned NextCallIndex;
760
Richard Smitha3d3bd22013-05-08 02:12:03 +0000761 /// StepsLeft - The remaining number of evaluation steps we're permitted
762 /// to perform. This is essentially a limit for the number of statements
763 /// we will evaluate.
764 unsigned StepsLeft;
765
Nandor Licker950b70d2019-09-13 09:46:16 +0000766 /// Force the use of the experimental new constant interpreter, bailing out
767 /// with an error if a feature is not supported.
768 bool ForceNewConstInterp;
769
770 /// Enable the experimental new constant interpreter.
771 bool EnableNewConstInterp;
772
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000773 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000774 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000775 CallStackFrame BottomFrame;
776
Richard Smith08d6a2c2013-07-24 07:11:57 +0000777 /// A stack of values whose lifetimes end at the end of some surrounding
778 /// evaluation frame.
779 llvm::SmallVector<Cleanup, 16> CleanupStack;
780
Richard Smithd62306a2011-11-10 06:34:14 +0000781 /// EvaluatingDecl - This is the declaration whose initializer is being
782 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000783 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000784
Richard Smith2b4fa532019-09-29 05:08:46 +0000785 enum class EvaluatingDeclKind {
786 None,
787 /// We're evaluating the construction of EvaluatingDecl.
788 Ctor,
789 /// We're evaluating the destruction of EvaluatingDecl.
790 Dtor,
791 };
792 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
793
Richard Smithd62306a2011-11-10 06:34:14 +0000794 /// EvaluatingDeclValue - This is the value being constructed for the
795 /// declaration whose initializer is being evaluated, if any.
796 APValue *EvaluatingDeclValue;
797
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000798 /// Set of objects that are currently being constructed.
799 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
800 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000801
Richard Smithda1b4342019-09-27 01:26:47 +0000802 /// Current heap allocations, along with the location where each was
803 /// allocated. We use std::map here because we need stable addresses
804 /// for the stored APValues.
805 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
806
807 /// The number of heap allocations performed so far in this evaluation.
808 unsigned NumHeapAllocs = 0;
809
Erik Pilkington42925492017-10-04 00:18:55 +0000810 struct EvaluatingConstructorRAII {
811 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000812 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000813 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000814 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
815 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000816 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000817 DidInsert =
818 EI.ObjectsUnderConstruction
819 .insert({Object, HasBases ? ConstructionPhase::Bases
820 : ConstructionPhase::AfterBases})
821 .second;
822 }
823 void finishedConstructingBases() {
824 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000825 }
826 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000827 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000828 }
829 };
830
Richard Smith457226e2019-09-23 03:48:44 +0000831 struct EvaluatingDestructorRAII {
832 EvalInfo &EI;
833 ObjectUnderConstruction Object;
Richard Smithda1b4342019-09-27 01:26:47 +0000834 bool DidInsert;
Richard Smith457226e2019-09-23 03:48:44 +0000835 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
836 : EI(EI), Object(Object) {
Richard Smithda1b4342019-09-27 01:26:47 +0000837 DidInsert = EI.ObjectsUnderConstruction
838 .insert({Object, ConstructionPhase::Destroying})
839 .second;
Richard Smith457226e2019-09-23 03:48:44 +0000840 }
841 void startedDestroyingBases() {
842 EI.ObjectsUnderConstruction[Object] =
843 ConstructionPhase::DestroyingBases;
844 }
845 ~EvaluatingDestructorRAII() {
Richard Smithda1b4342019-09-27 01:26:47 +0000846 if (DidInsert)
847 EI.ObjectsUnderConstruction.erase(Object);
Richard Smith457226e2019-09-23 03:48:44 +0000848 }
849 };
850
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000851 ConstructionPhase
Richard Smith457226e2019-09-23 03:48:44 +0000852 isEvaluatingCtorDtor(APValue::LValueBase Base,
853 ArrayRef<APValue::LValuePathEntry> Path) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000854 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000855 }
856
Richard Smith37be3362019-05-04 04:00:45 +0000857 /// If we're currently speculatively evaluating, the outermost call stack
858 /// depth at which we can mutate state, otherwise 0.
859 unsigned SpeculativeEvaluationDepth = 0;
860
Richard Smith410306b2016-12-12 02:53:20 +0000861 /// The current array initialization index, if we're performing array
862 /// initialization.
863 uint64_t ArrayInitIndex = -1;
864
Richard Smith357362d2011-12-13 06:39:58 +0000865 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
866 /// notes attached to it will also be stored, otherwise they will not be.
867 bool HasActiveDiagnostic;
868
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000869 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000870 /// fold (not just why it's not strictly a constant expression)?
871 bool HasFoldFailureDiagnostic;
872
Fangrui Song407659a2018-11-30 23:41:18 +0000873 /// Whether or not we're in a context where the front end requires a
874 /// constant value.
875 bool InConstantContext;
876
Richard Smith045b2272019-09-10 21:24:09 +0000877 /// Whether we're checking that an expression is a potential constant
878 /// expression. If so, do not fail on constructs that could become constant
879 /// later on (such as a use of an undefined global).
880 bool CheckingPotentialConstantExpression = false;
881
882 /// Whether we're checking for an expression that has undefined behavior.
883 /// If so, we will produce warnings if we encounter an operation that is
884 /// always undefined.
885 bool CheckingForUndefinedBehavior = false;
886
Richard Smith6d4c6582013-11-05 22:18:15 +0000887 enum EvaluationMode {
888 /// Evaluate as a constant expression. Stop if we find that the expression
889 /// is not a constant expression.
890 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000891
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000892 /// Evaluate as a constant expression. Stop if we find that the expression
893 /// is not a constant expression. Some expressions can be retried in the
894 /// optimizer if we don't constant fold them here, but in an unevaluated
895 /// context we try to fold them immediately since the optimizer never
896 /// gets a chance to look at it.
897 EM_ConstantExpressionUnevaluated,
898
Richard Smith045b2272019-09-10 21:24:09 +0000899 /// Fold the expression to a constant. Stop if we hit a side-effect that
900 /// we can't model.
901 EM_ConstantFold,
902
903 /// Evaluate in any way we know how. Don't worry about side-effects that
904 /// can't be modeled.
905 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000906 } EvalMode;
907
908 /// Are we checking whether the expression is a potential constant
909 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000910 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000911 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000912 }
913
914 /// Are we checking an expression for overflow?
915 // FIXME: We should check for any kind of undefined or suspicious behavior
916 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000917 bool checkingForUndefinedBehavior() const override {
918 return CheckingForUndefinedBehavior;
919 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000920
921 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000922 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
923 CallStackDepth(0), NextCallIndex(1),
924 StepsLeft(getLangOpts().ConstexprStepLimit),
925 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
926 EnableNewConstInterp(ForceNewConstInterp ||
927 getLangOpts().EnableNewConstInterp),
928 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
929 EvaluatingDecl((const ValueDecl *)nullptr),
930 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
931 HasFoldFailureDiagnostic(false), InConstantContext(false),
932 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000933
Richard Smith457226e2019-09-23 03:48:44 +0000934 ~EvalInfo() {
935 discardCleanups();
936 }
937
Richard Smith2b4fa532019-09-29 05:08:46 +0000938 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
939 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
Richard Smith7525ff62013-05-09 07:14:00 +0000940 EvaluatingDecl = Base;
Richard Smith2b4fa532019-09-29 05:08:46 +0000941 IsEvaluatingDecl = EDK;
Richard Smithd62306a2011-11-10 06:34:14 +0000942 EvaluatingDeclValue = &Value;
943 }
944
Richard Smith357362d2011-12-13 06:39:58 +0000945 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000946 // Don't perform any constexpr calls (other than the call we're checking)
947 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000948 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000949 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000950 if (NextCallIndex == 0) {
951 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000952 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000953 return false;
954 }
Richard Smith357362d2011-12-13 06:39:58 +0000955 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
956 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000957 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000958 << getLangOpts().ConstexprCallDepth;
959 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000960 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000961
Richard Smith37be3362019-05-04 04:00:45 +0000962 std::pair<CallStackFrame *, unsigned>
963 getCallFrameAndDepth(unsigned CallIndex) {
964 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000965 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
966 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000967 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000968 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000969 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000970 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000971 --Depth;
972 }
973 if (Frame->Index == CallIndex)
974 return {Frame, Depth};
975 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000976 }
977
Richard Smitha3d3bd22013-05-08 02:12:03 +0000978 bool nextStep(const Stmt *S) {
979 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000980 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000981 return false;
982 }
983 --StepsLeft;
984 return true;
985 }
986
Richard Smithda1b4342019-09-27 01:26:47 +0000987 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
988
989 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
990 Optional<DynAlloc*> Result;
991 auto It = HeapAllocs.find(DA);
992 if (It != HeapAllocs.end())
993 Result = &It->second;
994 return Result;
995 }
996
Richard Smith19ad5232019-10-03 00:39:33 +0000997 /// Information about a stack frame for std::allocator<T>::[de]allocate.
998 struct StdAllocatorCaller {
999 unsigned FrameIndex;
1000 QualType ElemType;
1001 explicit operator bool() const { return FrameIndex != 0; };
1002 };
1003
1004 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1005 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1006 Call = Call->Caller) {
1007 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1008 if (!MD)
1009 continue;
1010 const IdentifierInfo *FnII = MD->getIdentifier();
1011 if (!FnII || !FnII->isStr(FnName))
1012 continue;
1013
1014 const auto *CTSD =
1015 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1016 if (!CTSD)
1017 continue;
1018
1019 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1020 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1021 if (CTSD->isInStdNamespace() && ClassII &&
1022 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1023 TAL[0].getKind() == TemplateArgument::Type)
1024 return {Call->Index, TAL[0].getAsType()};
1025 }
1026
1027 return {};
1028 }
1029
Richard Smith457226e2019-09-23 03:48:44 +00001030 void performLifetimeExtension() {
1031 // Disable the cleanups for lifetime-extended temporaries.
1032 CleanupStack.erase(
1033 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1034 [](Cleanup &C) { return C.isLifetimeExtended(); }),
1035 CleanupStack.end());
1036 }
1037
1038 /// Throw away any remaining cleanups at the end of evaluation. If any
1039 /// cleanups would have had a side-effect, note that as an unmodeled
1040 /// side-effect and return false. Otherwise, return true.
1041 bool discardCleanups() {
1042 for (Cleanup &C : CleanupStack)
1043 if (C.hasSideEffect())
1044 if (!noteSideEffect())
1045 return false;
1046 return true;
1047 }
1048
Richard Smith357362d2011-12-13 06:39:58 +00001049 private:
Nandor Licker950b70d2019-09-13 09:46:16 +00001050 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1051 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1052
1053 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1054 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1055
1056 void setFoldFailureDiagnostic(bool Flag) override {
1057 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +00001058 }
1059
Nandor Licker950b70d2019-09-13 09:46:16 +00001060 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +00001061
Nandor Licker950b70d2019-09-13 09:46:16 +00001062 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +00001063
Nandor Licker950b70d2019-09-13 09:46:16 +00001064 // If we have a prior diagnostic, it will be noting that the expression
1065 // isn't a constant expression. This diagnostic is more important,
1066 // unless we require this evaluation to produce a constant expression.
1067 //
1068 // FIXME: We might want to show both diagnostics to the user in
1069 // EM_ConstantFold mode.
1070 bool hasPriorDiagnostic() override {
1071 if (!EvalStatus.Diag->empty()) {
1072 switch (EvalMode) {
1073 case EM_ConstantFold:
1074 case EM_IgnoreSideEffects:
1075 if (!HasFoldFailureDiagnostic)
1076 break;
1077 // We've already failed to fold something. Keep that diagnostic.
1078 LLVM_FALLTHROUGH;
1079 case EM_ConstantExpression:
1080 case EM_ConstantExpressionUnevaluated:
1081 setActiveDiagnostic(false);
1082 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +00001083 }
Richard Smith92b1ce02011-12-12 09:28:41 +00001084 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001085 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +00001086 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001087
1088 unsigned getCallStackDepth() override { return CallStackDepth; }
1089
Faisal Valie690b7a2016-07-02 22:34:24 +00001090 public:
Richard Smith6d4c6582013-11-05 22:18:15 +00001091 /// Should we continue evaluation after encountering a side-effect that we
1092 /// couldn't model?
1093 bool keepEvaluatingAfterSideEffect() {
1094 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001095 case EM_IgnoreSideEffects:
1096 return true;
1097
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001099 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001100 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +00001101 // By default, assume any side effect might be valid in some other
1102 // evaluation of this expression from a different context.
1103 return checkingPotentialConstantExpression() ||
1104 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001105 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001106 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001107 }
1108
1109 /// Note that we have had a side-effect, and determine whether we should
1110 /// keep evaluating.
1111 bool noteSideEffect() {
1112 EvalStatus.HasSideEffects = true;
1113 return keepEvaluatingAfterSideEffect();
1114 }
1115
Richard Smithce8eca52015-12-08 03:21:47 +00001116 /// Should we continue evaluation after encountering undefined behavior?
1117 bool keepEvaluatingAfterUndefinedBehavior() {
1118 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +00001119 case EM_IgnoreSideEffects:
1120 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001121 return true;
1122
Richard Smithce8eca52015-12-08 03:21:47 +00001123 case EM_ConstantExpression:
1124 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +00001125 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +00001126 }
1127 llvm_unreachable("Missed EvalMode case");
1128 }
1129
1130 /// Note that we hit something that was technically undefined behavior, but
1131 /// that we can evaluate past it (such as signed overflow or floating-point
1132 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +00001133 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +00001134 EvalStatus.HasUndefinedBehavior = true;
1135 return keepEvaluatingAfterUndefinedBehavior();
1136 }
1137
Richard Smith253c2a32012-01-27 01:14:48 +00001138 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001139 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +00001140 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +00001141 if (!StepsLeft)
1142 return false;
1143
1144 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001145 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001146 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001147 case EM_ConstantFold:
1148 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +00001149 return checkingPotentialConstantExpression() ||
1150 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001151 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001152 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001153 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001154
George Burgess IV8c892b52016-05-25 22:31:54 +00001155 /// Notes that we failed to evaluate an expression that other expressions
1156 /// directly depend on, and determine if we should keep evaluating. This
1157 /// should only be called if we actually intend to keep evaluating.
1158 ///
1159 /// Call noteSideEffect() instead if we may be able to ignore the value that
1160 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1161 ///
1162 /// (Foo(), 1) // use noteSideEffect
1163 /// (Foo() || true) // use noteSideEffect
1164 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001165 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001166 // Failure when evaluating some expression often means there is some
1167 // subexpression whose evaluation was skipped. Therefore, (because we
1168 // don't track whether we skipped an expression when unwinding after an
1169 // evaluation failure) every evaluation failure that bubbles up from a
1170 // subexpression implies that a side-effect has potentially happened. We
1171 // skip setting the HasSideEffects flag to true until we decide to
1172 // continue evaluating after that point, which happens here.
1173 bool KeepGoing = keepEvaluatingAfterFailure();
1174 EvalStatus.HasSideEffects |= KeepGoing;
1175 return KeepGoing;
1176 }
1177
Richard Smith410306b2016-12-12 02:53:20 +00001178 class ArrayInitLoopIndex {
1179 EvalInfo &Info;
1180 uint64_t OuterIndex;
1181
1182 public:
1183 ArrayInitLoopIndex(EvalInfo &Info)
1184 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1185 Info.ArrayInitIndex = 0;
1186 }
1187 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1188
1189 operator uint64_t&() { return Info.ArrayInitIndex; }
1190 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001191 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001192
1193 /// Object used to treat all foldable expressions as constant expressions.
1194 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001195 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001196 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001197 bool HadNoPriorDiags;
1198 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001199
Richard Smith6d4c6582013-11-05 22:18:15 +00001200 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1201 : Info(Info),
1202 Enabled(Enabled),
1203 HadNoPriorDiags(Info.EvalStatus.Diag &&
1204 Info.EvalStatus.Diag->empty() &&
1205 !Info.EvalStatus.HasSideEffects),
1206 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001207 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001208 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001209 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001210 void keepDiagnostics() { Enabled = false; }
1211 ~FoldConstant() {
1212 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001213 !Info.EvalStatus.HasSideEffects)
1214 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001215 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001216 }
1217 };
Richard Smith17100ba2012-02-16 02:46:34 +00001218
James Y Knight892b09b2018-10-10 02:53:43 +00001219 /// RAII object used to set the current evaluation mode to ignore
1220 /// side-effects.
1221 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001222 EvalInfo &Info;
1223 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001224 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001225 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001226 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001227 }
1228
James Y Knight892b09b2018-10-10 02:53:43 +00001229 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001230 };
1231
George Burgess IV8c892b52016-05-25 22:31:54 +00001232 /// RAII object used to optionally suppress diagnostics and side-effects from
1233 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001234 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001235 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001236 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001237 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001238
George Burgess IV8c892b52016-05-25 22:31:54 +00001239 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001240 Info = Other.Info;
1241 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001242 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001243 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001244 }
1245
1246 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001247 if (!Info)
1248 return;
1249
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001250 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001251 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001252 }
1253
Richard Smith17100ba2012-02-16 02:46:34 +00001254 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001255 SpeculativeEvaluationRAII() = default;
1256
1257 SpeculativeEvaluationRAII(
1258 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001259 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001260 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001261 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001262 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001263 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001264
1265 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1266 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1267 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001268 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001269
1270 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1271 maybeRestoreState();
1272 moveFromAndCancel(std::move(Other));
1273 return *this;
1274 }
1275
1276 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001277 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001278
1279 /// RAII object wrapping a full-expression or block scope, and handling
1280 /// the ending of the lifetime of temporaries created within it.
1281 template<bool IsFullExpression>
1282 class ScopeRAII {
1283 EvalInfo &Info;
1284 unsigned OldStackSize;
1285 public:
1286 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001287 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1288 // Push a new temporary version. This is needed to distinguish between
1289 // temporaries created in different iterations of a loop.
1290 Info.CurrentCall->pushTempVersion();
1291 }
Richard Smith457226e2019-09-23 03:48:44 +00001292 bool destroy(bool RunDestructors = true) {
1293 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1294 OldStackSize = -1U;
1295 return OK;
1296 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001297 ~ScopeRAII() {
Richard Smith457226e2019-09-23 03:48:44 +00001298 if (OldStackSize != -1U)
1299 destroy(false);
Richard Smith08d6a2c2013-07-24 07:11:57 +00001300 // Body moved to a static method to encourage the compiler to inline away
1301 // instances of this class.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001302 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001303 }
1304 private:
Richard Smithda1b4342019-09-27 01:26:47 +00001305 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1306 unsigned OldStackSize) {
1307 assert(OldStackSize <= Info.CleanupStack.size() &&
1308 "running cleanups out of order?");
1309
Richard Smith457226e2019-09-23 03:48:44 +00001310 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1311 // for a full-expression scope.
Richard Smith49494732019-09-27 05:36:16 +00001312 bool Success = true;
Richard Smith457226e2019-09-23 03:48:44 +00001313 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
Richard Smithda1b4342019-09-27 01:26:47 +00001314 if (!(IsFullExpression &&
1315 Info.CleanupStack[I - 1].isLifetimeExtended())) {
Richard Smith49494732019-09-27 05:36:16 +00001316 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1317 Success = false;
1318 break;
1319 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001320 }
1321 }
Richard Smith457226e2019-09-23 03:48:44 +00001322
1323 // Compact lifetime-extended cleanups.
1324 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1325 if (IsFullExpression)
1326 NewEnd =
1327 std::remove_if(NewEnd, Info.CleanupStack.end(),
1328 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1329 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
Richard Smith49494732019-09-27 05:36:16 +00001330 return Success;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001331 }
1332 };
1333 typedef ScopeRAII<false> BlockScopeRAII;
1334 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001335}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001336
Richard Smitha8105bc2012-01-06 16:39:00 +00001337bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1338 CheckSubobjectKind CSK) {
1339 if (Invalid)
1340 return false;
1341 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001342 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 << CSK;
1344 setInvalid();
1345 return false;
1346 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001347 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1348 // must actually be at least one array element; even a VLA cannot have a
1349 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001350 return true;
1351}
1352
Richard Smith6f4f0f12017-10-20 22:56:25 +00001353void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1354 const Expr *E) {
1355 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1356 // Do not set the designator as invalid: we can represent this situation,
1357 // and correct handling of __builtin_object_size requires us to do so.
1358}
1359
Richard Smitha8105bc2012-01-06 16:39:00 +00001360void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001361 const Expr *E,
1362 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001363 // If we're complaining, we must be able to statically determine the size of
1364 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001365 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001366 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001367 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001368 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001369 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001370 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001371 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001372 setInvalid();
1373}
1374
Richard Smithf6f003a2011-12-16 19:06:07 +00001375CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1376 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001377 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001378 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1379 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001380 Info.CurrentCall = this;
1381 ++Info.CallStackDepth;
1382}
1383
1384CallStackFrame::~CallStackFrame() {
1385 assert(Info.CurrentCall == this && "calls retired out of order");
1386 --Info.CallStackDepth;
1387 Info.CurrentCall = Caller;
1388}
1389
Richard Smithc667cdc2019-09-18 17:37:44 +00001390static bool isRead(AccessKinds AK) {
1391 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1392}
1393
Richard Smithdebad642019-05-12 09:39:08 +00001394static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001395 switch (AK) {
1396 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001397 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001398 case AK_MemberCall:
1399 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001400 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001401 return false;
1402 case AK_Assign:
1403 case AK_Increment:
1404 case AK_Decrement:
Richard Smithb5426022019-10-03 00:39:35 +00001405 case AK_Construct:
Richard Smith61422f92019-09-27 20:24:36 +00001406 case AK_Destroy:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001407 return true;
1408 }
1409 llvm_unreachable("unknown access kind");
1410}
1411
Richard Smith61422f92019-09-27 20:24:36 +00001412static bool isAnyAccess(AccessKinds AK) {
1413 return isRead(AK) || isModification(AK);
1414}
1415
Richard Smith7bd54ab2019-05-15 20:22:21 +00001416/// Is this an access per the C++ definition?
1417static bool isFormalAccess(AccessKinds AK) {
Richard Smithb5426022019-10-03 00:39:35 +00001418 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
Richard Smithdebad642019-05-12 09:39:08 +00001419}
1420
Richard Smithf6f003a2011-12-16 19:06:07 +00001421namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001422 struct ComplexValue {
1423 private:
1424 bool IsInt;
1425
1426 public:
1427 APSInt IntReal, IntImag;
1428 APFloat FloatReal, FloatImag;
1429
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001430 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001431
1432 void makeComplexFloat() { IsInt = false; }
1433 bool isComplexFloat() const { return !IsInt; }
1434 APFloat &getComplexFloatReal() { return FloatReal; }
1435 APFloat &getComplexFloatImag() { return FloatImag; }
1436
1437 void makeComplexInt() { IsInt = true; }
1438 bool isComplexInt() const { return IsInt; }
1439 APSInt &getComplexIntReal() { return IntReal; }
1440 APSInt &getComplexIntImag() { return IntImag; }
1441
Richard Smith2e312c82012-03-03 22:46:17 +00001442 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001443 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001444 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001445 else
Richard Smith2e312c82012-03-03 22:46:17 +00001446 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001447 }
Richard Smith2e312c82012-03-03 22:46:17 +00001448 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001449 assert(v.isComplexFloat() || v.isComplexInt());
1450 if (v.isComplexFloat()) {
1451 makeComplexFloat();
1452 FloatReal = v.getComplexFloatReal();
1453 FloatImag = v.getComplexFloatImag();
1454 } else {
1455 makeComplexInt();
1456 IntReal = v.getComplexIntReal();
1457 IntImag = v.getComplexIntImag();
1458 }
1459 }
John McCall93d91dc2010-05-07 17:22:02 +00001460 };
John McCall45d55e42010-05-07 21:00:08 +00001461
1462 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001463 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001464 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001465 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001466 bool IsNullPtr : 1;
1467 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001468
Richard Smithce40ad62011-11-12 22:28:03 +00001469 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001470 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001471 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001472 SubobjectDesignator &getLValueDesignator() { return Designator; }
1473 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001474 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001475
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001476 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1477 unsigned getLValueVersion() const { return Base.getVersion(); }
1478
Richard Smith2e312c82012-03-03 22:46:17 +00001479 void moveInto(APValue &V) const {
1480 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001481 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001482 else {
1483 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001484 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001485 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001486 }
John McCall45d55e42010-05-07 21:00:08 +00001487 }
Richard Smith2e312c82012-03-03 22:46:17 +00001488 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001489 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001490 Base = V.getLValueBase();
1491 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001492 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001493 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001494 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001495 }
1496
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001497 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001498#ifndef NDEBUG
1499 // We only allow a few types of invalid bases. Enforce that here.
1500 if (BInvalid) {
1501 const auto *E = B.get<const Expr *>();
1502 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1503 "Unexpected type of invalid base");
1504 }
1505#endif
1506
Richard Smithce40ad62011-11-12 22:28:03 +00001507 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001508 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001509 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001510 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001511 IsNullPtr = false;
1512 }
1513
Richard Smith19ad5232019-10-03 00:39:33 +00001514 void setNull(ASTContext &Ctx, QualType PointerTy) {
Tim Northover01503332017-05-26 02:16:00 +00001515 Base = (Expr *)nullptr;
Richard Smith19ad5232019-10-03 00:39:33 +00001516 Offset =
1517 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
Tim Northover01503332017-05-26 02:16:00 +00001518 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001519 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1520 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001521 }
1522
George Burgess IV3a03fab2015-09-04 21:28:13 +00001523 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001524 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001525 }
1526
Richard Smith19ad5232019-10-03 00:39:33 +00001527 std::string toString(ASTContext &Ctx, QualType T) const {
1528 APValue Printable;
1529 moveInto(Printable);
1530 return Printable.getAsString(Ctx, T);
1531 }
1532
Hubert Tong147b7432018-12-12 16:53:43 +00001533 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001534 // Check that this LValue is not based on a null pointer. If it is, produce
1535 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001536 template <typename GenDiagType>
1537 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001538 if (Designator.Invalid)
1539 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001540 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001541 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001542 Designator.setInvalid();
1543 return false;
1544 }
1545 return true;
1546 }
1547
Hubert Tong147b7432018-12-12 16:53:43 +00001548 public:
1549 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1550 CheckSubobjectKind CSK) {
1551 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1552 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1553 });
1554 }
1555
1556 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1557 AccessKinds AK) {
1558 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1559 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1560 });
1561 }
1562
Richard Smitha8105bc2012-01-06 16:39:00 +00001563 // Check this LValue refers to an object. If not, set the designator to be
1564 // invalid and emit a diagnostic.
1565 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001566 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001567 Designator.checkSubobject(Info, E, CSK);
1568 }
1569
1570 void addDecl(EvalInfo &Info, const Expr *E,
1571 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001572 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1573 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001574 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001575 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1576 if (!Designator.Entries.empty()) {
1577 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1578 Designator.setInvalid();
1579 return;
1580 }
Richard Smithefdb5032017-11-15 03:03:56 +00001581 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1582 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1583 Designator.FirstEntryIsAnUnsizedArray = true;
1584 Designator.addUnsizedArrayUnchecked(ElemTy);
1585 }
George Burgess IVe3763372016-12-22 02:50:20 +00001586 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001587 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001588 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1589 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001590 }
Richard Smith66c96992012-02-18 22:04:06 +00001591 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001592 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1593 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001594 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001595 void clearIsNullPointer() {
1596 IsNullPtr = false;
1597 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001598 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1599 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001600 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1601 // but we're not required to diagnose it and it's valid in C++.)
1602 if (!Index)
1603 return;
1604
1605 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1606 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1607 // offsets.
1608 uint64_t Offset64 = Offset.getQuantity();
1609 uint64_t ElemSize64 = ElementSize.getQuantity();
1610 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1611 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1612
1613 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001614 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001615 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001616 }
1617 void adjustOffset(CharUnits N) {
1618 Offset += N;
1619 if (N.getQuantity())
1620 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001621 }
John McCall45d55e42010-05-07 21:00:08 +00001622 };
Richard Smith027bf112011-11-17 22:56:20 +00001623
1624 struct MemberPtr {
1625 MemberPtr() {}
1626 explicit MemberPtr(const ValueDecl *Decl) :
1627 DeclAndIsDerivedMember(Decl, false), Path() {}
1628
1629 /// The member or (direct or indirect) field referred to by this member
1630 /// pointer, or 0 if this is a null member pointer.
1631 const ValueDecl *getDecl() const {
1632 return DeclAndIsDerivedMember.getPointer();
1633 }
1634 /// Is this actually a member of some type derived from the relevant class?
1635 bool isDerivedMember() const {
1636 return DeclAndIsDerivedMember.getInt();
1637 }
1638 /// Get the class which the declaration actually lives in.
1639 const CXXRecordDecl *getContainingRecord() const {
1640 return cast<CXXRecordDecl>(
1641 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1642 }
1643
Richard Smith2e312c82012-03-03 22:46:17 +00001644 void moveInto(APValue &V) const {
1645 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001646 }
Richard Smith2e312c82012-03-03 22:46:17 +00001647 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001648 assert(V.isMemberPointer());
1649 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1650 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1651 Path.clear();
1652 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1653 Path.insert(Path.end(), P.begin(), P.end());
1654 }
1655
1656 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1657 /// whether the member is a member of some class derived from the class type
1658 /// of the member pointer.
1659 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1660 /// Path - The path of base/derived classes from the member declaration's
1661 /// class (exclusive) to the class type of the member pointer (inclusive).
1662 SmallVector<const CXXRecordDecl*, 4> Path;
1663
1664 /// Perform a cast towards the class of the Decl (either up or down the
1665 /// hierarchy).
1666 bool castBack(const CXXRecordDecl *Class) {
1667 assert(!Path.empty());
1668 const CXXRecordDecl *Expected;
1669 if (Path.size() >= 2)
1670 Expected = Path[Path.size() - 2];
1671 else
1672 Expected = getContainingRecord();
1673 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1674 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1675 // if B does not contain the original member and is not a base or
1676 // derived class of the class containing the original member, the result
1677 // of the cast is undefined.
1678 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1679 // (D::*). We consider that to be a language defect.
1680 return false;
1681 }
1682 Path.pop_back();
1683 return true;
1684 }
1685 /// Perform a base-to-derived member pointer cast.
1686 bool castToDerived(const CXXRecordDecl *Derived) {
1687 if (!getDecl())
1688 return true;
1689 if (!isDerivedMember()) {
1690 Path.push_back(Derived);
1691 return true;
1692 }
1693 if (!castBack(Derived))
1694 return false;
1695 if (Path.empty())
1696 DeclAndIsDerivedMember.setInt(false);
1697 return true;
1698 }
1699 /// Perform a derived-to-base member pointer cast.
1700 bool castToBase(const CXXRecordDecl *Base) {
1701 if (!getDecl())
1702 return true;
1703 if (Path.empty())
1704 DeclAndIsDerivedMember.setInt(true);
1705 if (isDerivedMember()) {
1706 Path.push_back(Base);
1707 return true;
1708 }
1709 return castBack(Base);
1710 }
1711 };
Richard Smith357362d2011-12-13 06:39:58 +00001712
Richard Smith7bb00672012-02-01 01:42:44 +00001713 /// Compare two member pointers, which are assumed to be of the same type.
1714 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1715 if (!LHS.getDecl() || !RHS.getDecl())
1716 return !LHS.getDecl() && !RHS.getDecl();
1717 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1718 return false;
1719 return LHS.Path == RHS.Path;
1720 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001721}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001722
Richard Smith2e312c82012-03-03 22:46:17 +00001723static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001724static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1725 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001726 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001727static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1728 bool InvalidBaseOK = false);
1729static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1730 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001731static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1732 EvalInfo &Info);
1733static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001734static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001735static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001736 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001737static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001738static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001739static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1740 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001741static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001742
Leonard Chand3f3e162019-01-18 21:04:25 +00001743/// Evaluate an integer or fixed point expression into an APResult.
1744static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1745 EvalInfo &Info);
1746
1747/// Evaluate only a fixed point expression into an APResult.
1748static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1749 EvalInfo &Info);
1750
Chris Lattner05706e882008-07-11 18:11:29 +00001751//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001752// Misc utilities
1753//===----------------------------------------------------------------------===//
1754
Richard Smithd6cc1982017-01-31 02:23:02 +00001755/// Negate an APSInt in place, converting it to a signed form if necessary, and
1756/// preserving its value (by extending by up to one bit as needed).
1757static void negateAsSigned(APSInt &Int) {
1758 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1759 Int = Int.extend(Int.getBitWidth() + 1);
1760 Int.setIsSigned(true);
1761 }
1762 Int = -Int;
1763}
1764
Richard Smith457226e2019-09-23 03:48:44 +00001765template<typename KeyT>
1766APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1767 bool IsLifetimeExtended, LValue &LV) {
Richard Smithda1b4342019-09-27 01:26:47 +00001768 unsigned Version = getTempVersion();
Richard Smith457226e2019-09-23 03:48:44 +00001769 APValue::LValueBase Base(Key, Index, Version);
1770 LV.set(Base);
1771 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1772 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smithda1b4342019-09-27 01:26:47 +00001773
1774 // If we're creating a temporary immediately in the operand of a speculative
1775 // evaluation, don't register a cleanup to be run outside the speculative
1776 // evaluation context, since we won't actually be able to initialize this
1777 // object.
1778 if (Index <= Info.SpeculativeEvaluationDepth) {
1779 if (T.isDestructedType())
1780 Info.noteSideEffect();
1781 } else {
1782 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1783 }
Richard Smith457226e2019-09-23 03:48:44 +00001784 return Result;
1785}
1786
Richard Smithda1b4342019-09-27 01:26:47 +00001787APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1788 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1789 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1790 return nullptr;
1791 }
1792
1793 DynamicAllocLValue DA(NumHeapAllocs++);
1794 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1795 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1796 std::forward_as_tuple(DA), std::tuple<>());
1797 assert(Result.second && "reused a heap alloc index?");
1798 Result.first->second.AllocExpr = E;
1799 return &Result.first->second.Value;
1800}
1801
Richard Smith84401042013-06-03 05:03:02 +00001802/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001803void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001804 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001805 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1806 !isa<CXXConstructorDecl>(Callee) &&
1807 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001808
1809 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001810 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001811
Nandor Licker950b70d2019-09-13 09:46:16 +00001812 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001813 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001814 This->moveInto(Val);
1815 Val.printPretty(Out, Info.Ctx,
1816 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001817 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001818 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001819 IsMemberCall = false;
1820 }
1821
Nandor Licker950b70d2019-09-13 09:46:16 +00001822 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1823 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001824 if (ArgIndex > (unsigned)IsMemberCall)
1825 Out << ", ";
1826
1827 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001828 const APValue &Arg = Arguments[ArgIndex];
1829 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001830
1831 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001832 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001833 }
1834
1835 Out << ')';
1836}
1837
Richard Smithd9f663b2013-04-22 15:31:51 +00001838/// Evaluate an expression to see if it had side-effects, and discard its
1839/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001840/// \return \c true if the caller should keep evaluating.
1841static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001842 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001843 if (!Evaluate(Scratch, Info, E))
1844 // We don't need the value, but we might have skipped a side effect here.
1845 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001846 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001847}
1848
Richard Smithd62306a2011-11-10 06:34:14 +00001849/// Should this call expression be treated as a string literal?
1850static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001851 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001852 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1853 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1854}
1855
Richard Smithce40ad62011-11-12 22:28:03 +00001856static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001857 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1858 // constant expression of pointer type that evaluates to...
1859
1860 // ... a null pointer value, or a prvalue core constant expression of type
1861 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001862 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001863
Richard Smithce40ad62011-11-12 22:28:03 +00001864 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1865 // ... the address of an object with static storage duration,
1866 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1867 return VD->hasGlobalStorage();
1868 // ... the address of a function,
1869 return isa<FunctionDecl>(D);
1870 }
1871
Richard Smithda1b4342019-09-27 01:26:47 +00001872 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +00001873 return true;
1874
Richard Smithce40ad62011-11-12 22:28:03 +00001875 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001876 switch (E->getStmtClass()) {
1877 default:
1878 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001879 case Expr::CompoundLiteralExprClass: {
1880 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1881 return CLE->isFileScope() && CLE->isLValue();
1882 }
Richard Smithe6c01442013-06-05 00:46:14 +00001883 case Expr::MaterializeTemporaryExprClass:
1884 // A materialized temporary might have been lifetime-extended to static
1885 // storage duration.
1886 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001887 // A string literal has static storage duration.
1888 case Expr::StringLiteralClass:
1889 case Expr::PredefinedExprClass:
1890 case Expr::ObjCStringLiteralClass:
1891 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001892 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001893 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001894 case Expr::ObjCBoxedExprClass:
1895 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001896 case Expr::CallExprClass:
1897 return IsStringLiteralCall(cast<CallExpr>(E));
1898 // For GCC compatibility, &&label has static storage duration.
1899 case Expr::AddrLabelExprClass:
1900 return true;
1901 // A Block literal expression may be used as the initialization value for
1902 // Block variables at global or local static scope.
1903 case Expr::BlockExprClass:
1904 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001905 case Expr::ImplicitValueInitExprClass:
1906 // FIXME:
1907 // We can never form an lvalue with an implicit value initialization as its
1908 // base through expression evaluation, so these only appear in one case: the
1909 // implicit variable declaration we invent when checking whether a constexpr
1910 // constructor can produce a constant expression. We must assume that such
1911 // an expression might be a global lvalue.
1912 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001913 }
John McCall95007602010-05-10 23:27:23 +00001914}
1915
Richard Smith06f71b52018-08-04 00:57:17 +00001916static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1917 return LVal.Base.dyn_cast<const ValueDecl*>();
1918}
1919
1920static bool IsLiteralLValue(const LValue &Value) {
1921 if (Value.getLValueCallIndex())
1922 return false;
1923 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1924 return E && !isa<MaterializeTemporaryExpr>(E);
1925}
1926
1927static bool IsWeakLValue(const LValue &Value) {
1928 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1929 return Decl && Decl->isWeak();
1930}
1931
1932static bool isZeroSized(const LValue &Value) {
1933 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1934 if (Decl && isa<VarDecl>(Decl)) {
1935 QualType Ty = Decl->getType();
1936 if (Ty->isArrayType())
1937 return Ty->isIncompleteType() ||
1938 Decl->getASTContext().getTypeSize(Ty) == 0;
1939 }
1940 return false;
1941}
1942
1943static bool HasSameBase(const LValue &A, const LValue &B) {
1944 if (!A.getLValueBase())
1945 return !B.getLValueBase();
1946 if (!B.getLValueBase())
1947 return false;
1948
1949 if (A.getLValueBase().getOpaqueValue() !=
1950 B.getLValueBase().getOpaqueValue()) {
1951 const Decl *ADecl = GetLValueBaseDecl(A);
1952 if (!ADecl)
1953 return false;
1954 const Decl *BDecl = GetLValueBaseDecl(B);
1955 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1956 return false;
1957 }
1958
1959 return IsGlobalLValue(A.getLValueBase()) ||
1960 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1961 A.getLValueVersion() == B.getLValueVersion());
1962}
1963
Richard Smithb228a862012-02-15 02:18:13 +00001964static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1965 assert(Base && "no location for a null lvalue");
1966 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1967 if (VD)
1968 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001969 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1970 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
Richard Smithda1b4342019-09-27 01:26:47 +00001971 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1972 // FIXME: Produce a note for dangling pointers too.
Richard Smith19ad5232019-10-03 00:39:33 +00001973 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
Richard Smithda1b4342019-09-27 01:26:47 +00001974 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1975 diag::note_constexpr_dynamic_alloc_here);
1976 }
Richard Smithee0ce3022019-05-17 07:06:46 +00001977 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001978}
1979
Richard Smith4566f872019-09-29 05:58:31 +00001980enum class CheckEvaluationResultKind {
1981 ConstantExpression,
1982 FullyInitialized,
1983};
1984
1985/// Materialized temporaries that we've already checked to determine if they're
1986/// initializsed by a constant expression.
1987using CheckedTemporaries =
1988 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
1989
1990static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
1991 EvalInfo &Info, SourceLocation DiagLoc,
1992 QualType Type, const APValue &Value,
1993 Expr::ConstExprUsage Usage,
1994 SourceLocation SubobjectLoc,
1995 CheckedTemporaries &CheckedTemps);
1996
Richard Smith80815602011-11-07 05:07:52 +00001997/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001998/// value for an address or reference constant expression. Return true if we
1999/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00002000static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002001 QualType Type, const LValue &LVal,
Richard Smith4566f872019-09-29 05:58:31 +00002002 Expr::ConstExprUsage Usage,
2003 CheckedTemporaries &CheckedTemps) {
Richard Smithb228a862012-02-15 02:18:13 +00002004 bool IsReferenceType = Type->isReferenceType();
2005
Richard Smith357362d2011-12-13 06:39:58 +00002006 APValue::LValueBase Base = LVal.getLValueBase();
2007 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2008
Richard Smith0dea49e2012-02-18 04:58:18 +00002009 // Check that the object is a global. Note that the fake 'this' object we
2010 // manufacture when checking potential constant expressions is conservatively
2011 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00002012 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002013 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002014 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00002015 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00002016 << IsReferenceType << !Designator.Entries.empty()
2017 << !!VD << VD;
2018 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002019 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002020 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00002021 }
Richard Smith02ab9c22012-01-12 06:08:57 +00002022 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00002023 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002024 }
Richard Smith6d4c6582013-11-05 22:18:15 +00002025 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00002026 LVal.getLValueCallIndex() == 0) &&
2027 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00002028
Richard Smithda1b4342019-09-27 01:26:47 +00002029 if (Base.is<DynamicAllocLValue>()) {
2030 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2031 << IsReferenceType << !Designator.Entries.empty();
2032 NoteLValueLocation(Info, Base);
2033 return false;
2034 }
2035
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002036 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2037 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00002038 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00002039 if (Var->getTLSKind())
Richard Smithda1b4342019-09-27 01:26:47 +00002040 // FIXME: Diagnostic!
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002041 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00002042
Hans Wennborg82dd8772014-06-25 22:19:48 +00002043 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002044 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00002045 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00002046 return false;
2047 }
2048 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2049 // __declspec(dllimport) must be handled very carefully:
2050 // We must never initialize an expression with the thunk in C++.
2051 // Doing otherwise would allow the same id-expression to yield
2052 // different addresses for the same function in different translation
2053 // units. However, this means that we must dynamically initialize the
2054 // expression with the contents of the import address table at runtime.
2055 //
2056 // The C language has no notion of ODR; furthermore, it has no notion of
2057 // dynamic initialization. This means that we are permitted to
2058 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002059 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2060 FD->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00002061 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00002062 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002063 }
Richard Smith4566f872019-09-29 05:58:31 +00002064 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2065 Base.dyn_cast<const Expr *>())) {
2066 if (CheckedTemps.insert(MTE).second) {
Richard Smith1e8c0852019-09-29 06:22:54 +00002067 QualType TempType = getType(Base);
2068 if (TempType.isDestructedType()) {
2069 Info.FFDiag(MTE->getExprLoc(),
2070 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2071 << TempType;
2072 return false;
2073 }
2074
Richard Smith4566f872019-09-29 05:58:31 +00002075 APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2076 assert(V && "evasluation result refers to uninitialised temporary");
2077 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
Richard Smith1e8c0852019-09-29 06:22:54 +00002078 Info, MTE->getExprLoc(), TempType, *V,
Richard Smith4566f872019-09-29 05:58:31 +00002079 Usage, SourceLocation(), CheckedTemps))
2080 return false;
2081 }
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002082 }
2083
Richard Smitha8105bc2012-01-06 16:39:00 +00002084 // Allow address constant expressions to be past-the-end pointers. This is
2085 // an extension: the standard requires them to point to an object.
2086 if (!IsReferenceType)
2087 return true;
2088
2089 // A reference constant expression must refer to an object.
2090 if (!Base) {
2091 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00002092 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00002093 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00002094 }
2095
Richard Smith357362d2011-12-13 06:39:58 +00002096 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00002097 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00002098 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00002099 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00002100 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00002101 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002102 }
2103
Richard Smith80815602011-11-07 05:07:52 +00002104 return true;
2105}
2106
Reid Klecknercd016d82017-07-07 22:04:29 +00002107/// Member pointers are constant expressions unless they point to a
2108/// non-virtual dllimport member function.
2109static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2110 SourceLocation Loc,
2111 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002112 const APValue &Value,
2113 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002114 const ValueDecl *Member = Value.getMemberPointerDecl();
2115 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2116 if (!FD)
2117 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002118 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2119 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002120}
2121
Richard Smithfddd3842011-12-30 21:15:51 +00002122/// Check that this core constant expression is of literal type, and if not,
2123/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002124static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002125 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002126 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002127 return true;
2128
Richard Smith7525ff62013-05-09 07:14:00 +00002129 // C++1y: A constant initializer for an object o [...] may also invoke
2130 // constexpr constructors for o and its subobjects even if those objects
2131 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002132 //
2133 // C++11 missed this detail for aggregates, so classes like this:
2134 // struct foo_t { union { int i; volatile int j; } u; };
2135 // are not (obviously) initializable like so:
2136 // __attribute__((__require_constant_initialization__))
2137 // static const foo_t x = {{0}};
2138 // because "i" is a subobject with non-literal initialization (due to the
2139 // volatile member of the union). See:
2140 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2141 // Therefore, we use the C++1y behavior.
2142 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002143 return true;
2144
Richard Smithfddd3842011-12-30 21:15:51 +00002145 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002146 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002147 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002148 << E->getType();
2149 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002150 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002151 return false;
2152}
2153
Richard Smith4566f872019-09-29 05:58:31 +00002154static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2155 EvalInfo &Info, SourceLocation DiagLoc,
2156 QualType Type, const APValue &Value,
2157 Expr::ConstExprUsage Usage,
2158 SourceLocation SubobjectLoc,
2159 CheckedTemporaries &CheckedTemps) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002160 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002161 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002162 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002163 if (SubobjectLoc.isValid())
2164 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002165 return false;
2166 }
2167
Richard Smith77be48a2014-07-31 06:31:19 +00002168 // We allow _Atomic(T) to be initialized from anything that T can be
2169 // initialized from.
2170 if (const AtomicType *AT = Type->getAs<AtomicType>())
2171 Type = AT->getValueType();
2172
Richard Smithb228a862012-02-15 02:18:13 +00002173 // Core issue 1454: For a literal constant expression of array or class type,
2174 // each subobject of its value shall have been initialized by a constant
2175 // expression.
2176 if (Value.isArray()) {
2177 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2178 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002179 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2180 Value.getArrayInitializedElt(I), Usage,
Richard Smith4566f872019-09-29 05:58:31 +00002181 SubobjectLoc, CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002182 return false;
2183 }
2184 if (!Value.hasArrayFiller())
2185 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00002186 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
Richard Smith4566f872019-09-29 05:58:31 +00002187 Value.getArrayFiller(), Usage, SubobjectLoc,
2188 CheckedTemps);
Richard Smith80815602011-11-07 05:07:52 +00002189 }
Richard Smithb228a862012-02-15 02:18:13 +00002190 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002191 return CheckEvaluationResult(
2192 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
Richard Smith4566f872019-09-29 05:58:31 +00002193 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2194 CheckedTemps);
Richard Smithb228a862012-02-15 02:18:13 +00002195 }
2196 if (Value.isStruct()) {
2197 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2198 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2199 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002200 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002201 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2202 Value.getStructBase(BaseIndex), Usage,
Richard Smith4566f872019-09-29 05:58:31 +00002203 BS.getBeginLoc(), CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002204 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002205 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002206 }
2207 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002208 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002209 if (I->isUnnamedBitfield())
2210 continue;
2211
Richard Smithc667cdc2019-09-18 17:37:44 +00002212 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2213 Value.getStructField(I->getFieldIndex()),
Richard Smith4566f872019-09-29 05:58:31 +00002214 Usage, I->getLocation(), CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002215 return false;
2216 }
2217 }
2218
Richard Smithc667cdc2019-09-18 17:37:44 +00002219 if (Value.isLValue() &&
2220 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00002221 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002222 LVal.setFrom(Info.Ctx, Value);
Richard Smith4566f872019-09-29 05:58:31 +00002223 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2224 CheckedTemps);
Richard Smithb228a862012-02-15 02:18:13 +00002225 }
2226
Richard Smithc667cdc2019-09-18 17:37:44 +00002227 if (Value.isMemberPointer() &&
2228 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00002229 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002230
Richard Smithb228a862012-02-15 02:18:13 +00002231 // Everything else is fine.
2232 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002233}
2234
Richard Smithc667cdc2019-09-18 17:37:44 +00002235/// Check that this core constant expression value is a valid value for a
2236/// constant expression. If not, report an appropriate diagnostic. Does not
2237/// check that the expression is of literal type.
2238static bool
2239CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2240 const APValue &Value,
2241 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith4566f872019-09-29 05:58:31 +00002242 CheckedTemporaries CheckedTemps;
Richard Smithc667cdc2019-09-18 17:37:44 +00002243 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
Richard Smith4566f872019-09-29 05:58:31 +00002244 Info, DiagLoc, Type, Value, Usage,
2245 SourceLocation(), CheckedTemps);
Richard Smithc667cdc2019-09-18 17:37:44 +00002246}
2247
2248/// Check that this evaluated value is fully-initialized and can be loaded by
2249/// an lvalue-to-rvalue conversion.
2250static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2251 QualType Type, const APValue &Value) {
Richard Smith4566f872019-09-29 05:58:31 +00002252 CheckedTemporaries CheckedTemps;
2253 return CheckEvaluationResult(
2254 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2255 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
Richard Smithc667cdc2019-09-18 17:37:44 +00002256}
2257
Richard Smithda1b4342019-09-27 01:26:47 +00002258/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2259/// "the allocated storage is deallocated within the evaluation".
2260static bool CheckMemoryLeaks(EvalInfo &Info) {
2261 if (!Info.HeapAllocs.empty()) {
2262 // We can still fold to a constant despite a compile-time memory leak,
2263 // so long as the heap allocation isn't referenced in the result (we check
2264 // that in CheckConstantExpression).
2265 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2266 diag::note_constexpr_memory_leak)
2267 << unsigned(Info.HeapAllocs.size() - 1);
2268 }
2269 return true;
2270}
2271
Richard Smith2e312c82012-03-03 22:46:17 +00002272static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002273 // A null base expression indicates a null pointer. These are always
2274 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002275 if (!Value.getLValueBase()) {
2276 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002277 return true;
2278 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002279
Richard Smith027bf112011-11-17 22:56:20 +00002280 // We have a non-null base. These are generally known to be true, but if it's
2281 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002282 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002283 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002284 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002285}
2286
Richard Smith2e312c82012-03-03 22:46:17 +00002287static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002288 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002289 case APValue::None:
2290 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002291 return false;
2292 case APValue::Int:
2293 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002294 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002295 case APValue::FixedPoint:
2296 Result = Val.getFixedPoint().getBoolValue();
2297 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002298 case APValue::Float:
2299 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002300 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002301 case APValue::ComplexInt:
2302 Result = Val.getComplexIntReal().getBoolValue() ||
2303 Val.getComplexIntImag().getBoolValue();
2304 return true;
2305 case APValue::ComplexFloat:
2306 Result = !Val.getComplexFloatReal().isZero() ||
2307 !Val.getComplexFloatImag().isZero();
2308 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002309 case APValue::LValue:
2310 return EvalPointerValueAsBool(Val, Result);
2311 case APValue::MemberPointer:
2312 Result = Val.getMemberPointerDecl();
2313 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002314 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002315 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002316 case APValue::Struct:
2317 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002318 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002319 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002320 }
2321
Richard Smith11562c52011-10-28 17:51:58 +00002322 llvm_unreachable("unknown APValue kind");
2323}
2324
2325static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2326 EvalInfo &Info) {
2327 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002328 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002329 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002330 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002331 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002332}
2333
Richard Smith357362d2011-12-13 06:39:58 +00002334template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002335static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002336 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002337 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002338 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002339 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002340}
2341
2342static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2343 QualType SrcType, const APFloat &Value,
2344 QualType DestType, APSInt &Result) {
2345 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002346 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002347 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002348
Richard Smith357362d2011-12-13 06:39:58 +00002349 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002350 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002351 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2352 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002353 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002354 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002355}
2356
Richard Smith357362d2011-12-13 06:39:58 +00002357static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2358 QualType SrcType, QualType DestType,
2359 APFloat &Result) {
2360 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002361 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002362 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2363 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002364 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002365}
2366
Richard Smith911e1422012-01-30 22:27:01 +00002367static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2368 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002369 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002370 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002371 // Figure out if this is a truncate, extend or noop cast.
2372 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002373 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002374 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002375 if (DestType->isBooleanType())
2376 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002377 return Result;
2378}
2379
Richard Smith357362d2011-12-13 06:39:58 +00002380static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2381 QualType SrcType, const APSInt &Value,
2382 QualType DestType, APFloat &Result) {
2383 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002384 Result.convertFromAPInt(Value, Value.isSigned(),
2385 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002386 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002387}
2388
Richard Smith49ca8aa2013-08-06 07:09:20 +00002389static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2390 APValue &Value, const FieldDecl *FD) {
2391 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2392
2393 if (!Value.isInt()) {
2394 // Trying to store a pointer-cast-to-integer into a bitfield.
2395 // FIXME: In this case, we should provide the diagnostic for casting
2396 // a pointer to an integer.
2397 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002398 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002399 return false;
2400 }
2401
2402 APSInt &Int = Value.getInt();
2403 unsigned OldBitWidth = Int.getBitWidth();
2404 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2405 if (NewBitWidth < OldBitWidth)
2406 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2407 return true;
2408}
2409
Eli Friedman803acb32011-12-22 03:51:45 +00002410static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2411 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002412 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002413 if (!Evaluate(SVal, Info, E))
2414 return false;
2415 if (SVal.isInt()) {
2416 Res = SVal.getInt();
2417 return true;
2418 }
2419 if (SVal.isFloat()) {
2420 Res = SVal.getFloat().bitcastToAPInt();
2421 return true;
2422 }
2423 if (SVal.isVector()) {
2424 QualType VecTy = E->getType();
2425 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2426 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2427 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2428 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2429 Res = llvm::APInt::getNullValue(VecSize);
2430 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2431 APValue &Elt = SVal.getVectorElt(i);
2432 llvm::APInt EltAsInt;
2433 if (Elt.isInt()) {
2434 EltAsInt = Elt.getInt();
2435 } else if (Elt.isFloat()) {
2436 EltAsInt = Elt.getFloat().bitcastToAPInt();
2437 } else {
2438 // Don't try to handle vectors of anything other than int or float
2439 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002440 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002441 return false;
2442 }
2443 unsigned BaseEltSize = EltAsInt.getBitWidth();
2444 if (BigEndian)
2445 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2446 else
2447 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2448 }
2449 return true;
2450 }
2451 // Give up if the input isn't an int, float, or vector. For example, we
2452 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002453 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002454 return false;
2455}
2456
Richard Smith43e77732013-05-07 04:50:00 +00002457/// Perform the given integer operation, which is known to need at most BitWidth
2458/// bits, and check for overflow in the original type (if that type was not an
2459/// unsigned type).
2460template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002461static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2462 const APSInt &LHS, const APSInt &RHS,
2463 unsigned BitWidth, Operation Op,
2464 APSInt &Result) {
2465 if (LHS.isUnsigned()) {
2466 Result = Op(LHS, RHS);
2467 return true;
2468 }
Richard Smith43e77732013-05-07 04:50:00 +00002469
2470 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002471 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002472 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002473 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002474 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002475 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002476 << Result.toString(10) << E->getType();
2477 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002478 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002479 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002480 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002481}
2482
2483/// Perform the given binary integer operation.
2484static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2485 BinaryOperatorKind Opcode, APSInt RHS,
2486 APSInt &Result) {
2487 switch (Opcode) {
2488 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002489 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002490 return false;
2491 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002492 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2493 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002494 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002495 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2496 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002497 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002498 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2499 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002500 case BO_And: Result = LHS & RHS; return true;
2501 case BO_Xor: Result = LHS ^ RHS; return true;
2502 case BO_Or: Result = LHS | RHS; return true;
2503 case BO_Div:
2504 case BO_Rem:
2505 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002506 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002507 return false;
2508 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002509 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2510 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2511 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002512 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2513 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002514 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2515 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002516 return true;
2517 case BO_Shl: {
2518 if (Info.getLangOpts().OpenCL)
2519 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2520 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2521 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2522 RHS.isUnsigned());
2523 else if (RHS.isSigned() && RHS.isNegative()) {
2524 // During constant-folding, a negative shift is an opposite shift. Such
2525 // a shift is not a constant expression.
2526 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2527 RHS = -RHS;
2528 goto shift_right;
2529 }
2530 shift_left:
2531 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2532 // the shifted type.
2533 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2534 if (SA != RHS) {
2535 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2536 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002537 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002538 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2539 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002540 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2541 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002542 if (LHS.isNegative())
2543 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2544 else if (LHS.countLeadingZeros() < SA)
2545 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2546 }
2547 Result = LHS << SA;
2548 return true;
2549 }
2550 case BO_Shr: {
2551 if (Info.getLangOpts().OpenCL)
2552 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2553 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2554 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2555 RHS.isUnsigned());
2556 else if (RHS.isSigned() && RHS.isNegative()) {
2557 // During constant-folding, a negative shift is an opposite shift. Such a
2558 // shift is not a constant expression.
2559 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2560 RHS = -RHS;
2561 goto shift_left;
2562 }
2563 shift_right:
2564 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2565 // shifted type.
2566 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2567 if (SA != RHS)
2568 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2569 << RHS << E->getType() << LHS.getBitWidth();
2570 Result = LHS >> SA;
2571 return true;
2572 }
2573
2574 case BO_LT: Result = LHS < RHS; return true;
2575 case BO_GT: Result = LHS > RHS; return true;
2576 case BO_LE: Result = LHS <= RHS; return true;
2577 case BO_GE: Result = LHS >= RHS; return true;
2578 case BO_EQ: Result = LHS == RHS; return true;
2579 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002580 case BO_Cmp:
2581 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002582 }
2583}
2584
Richard Smith861b5b52013-05-07 23:34:45 +00002585/// Perform the given binary floating-point operation, in-place, on LHS.
2586static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2587 APFloat &LHS, BinaryOperatorKind Opcode,
2588 const APFloat &RHS) {
2589 switch (Opcode) {
2590 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002591 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002592 return false;
2593 case BO_Mul:
2594 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2595 break;
2596 case BO_Add:
2597 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2598 break;
2599 case BO_Sub:
2600 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2601 break;
2602 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002603 // [expr.mul]p4:
2604 // If the second operand of / or % is zero the behavior is undefined.
2605 if (RHS.isZero())
2606 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002607 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2608 break;
2609 }
2610
Richard Smith9e52c432019-07-06 21:05:52 +00002611 // [expr.pre]p4:
2612 // If during the evaluation of an expression, the result is not
2613 // mathematically defined [...], the behavior is undefined.
2614 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2615 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002616 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002617 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002618 }
Richard Smith861b5b52013-05-07 23:34:45 +00002619 return true;
2620}
2621
Richard Smitha8105bc2012-01-06 16:39:00 +00002622/// Cast an lvalue referring to a base subobject to a derived class, by
2623/// truncating the lvalue's path to the given length.
2624static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2625 const RecordDecl *TruncatedType,
2626 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002627 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002628
2629 // Check we actually point to a derived class object.
2630 if (TruncatedElements == D.Entries.size())
2631 return true;
2632 assert(TruncatedElements >= D.MostDerivedPathLength &&
2633 "not casting to a derived class");
2634 if (!Result.checkSubobject(Info, E, CSK_Derived))
2635 return false;
2636
2637 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002638 const RecordDecl *RD = TruncatedType;
2639 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002640 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002641 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2642 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002643 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002644 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002645 else
Richard Smithd62306a2011-11-10 06:34:14 +00002646 Result.Offset -= Layout.getBaseClassOffset(Base);
2647 RD = Base;
2648 }
Richard Smith027bf112011-11-17 22:56:20 +00002649 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002650 return true;
2651}
2652
John McCalld7bca762012-05-01 00:38:49 +00002653static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002654 const CXXRecordDecl *Derived,
2655 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002656 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002657 if (!RL) {
2658 if (Derived->isInvalidDecl()) return false;
2659 RL = &Info.Ctx.getASTRecordLayout(Derived);
2660 }
2661
Richard Smithd62306a2011-11-10 06:34:14 +00002662 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002663 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002664 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002665}
2666
Richard Smitha8105bc2012-01-06 16:39:00 +00002667static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002668 const CXXRecordDecl *DerivedDecl,
2669 const CXXBaseSpecifier *Base) {
2670 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2671
John McCalld7bca762012-05-01 00:38:49 +00002672 if (!Base->isVirtual())
2673 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002674
Richard Smitha8105bc2012-01-06 16:39:00 +00002675 SubobjectDesignator &D = Obj.Designator;
2676 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002677 return false;
2678
Richard Smitha8105bc2012-01-06 16:39:00 +00002679 // Extract most-derived object and corresponding type.
2680 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2681 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2682 return false;
2683
2684 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002685 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002686 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2687 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002688 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002689 return true;
2690}
2691
Richard Smith84401042013-06-03 05:03:02 +00002692static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2693 QualType Type, LValue &Result) {
2694 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2695 PathE = E->path_end();
2696 PathI != PathE; ++PathI) {
2697 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2698 *PathI))
2699 return false;
2700 Type = (*PathI)->getType();
2701 }
2702 return true;
2703}
2704
Richard Smith921f1322019-05-13 23:35:21 +00002705/// Cast an lvalue referring to a derived class to a known base subobject.
2706static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2707 const CXXRecordDecl *DerivedRD,
2708 const CXXRecordDecl *BaseRD) {
2709 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2710 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2711 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2712 llvm_unreachable("Class must be derived from the passed in base class!");
2713
2714 for (CXXBasePathElement &Elem : Paths.front())
2715 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2716 return false;
2717 return true;
2718}
2719
Richard Smithd62306a2011-11-10 06:34:14 +00002720/// Update LVal to refer to the given field, which must be a member of the type
2721/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002722static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002723 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002724 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002725 if (!RL) {
2726 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002727 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002728 }
Richard Smithd62306a2011-11-10 06:34:14 +00002729
2730 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002731 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002732 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002733 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002734}
2735
Richard Smith1b78b3d2012-01-25 22:15:11 +00002736/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002737static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002738 LValue &LVal,
2739 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002740 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002741 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002742 return false;
2743 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002744}
2745
Richard Smithd62306a2011-11-10 06:34:14 +00002746/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002747static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2748 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002749 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2750 // extension.
2751 if (Type->isVoidType() || Type->isFunctionType()) {
2752 Size = CharUnits::One();
2753 return true;
2754 }
2755
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002756 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002757 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002758 return false;
2759 }
2760
Richard Smithd62306a2011-11-10 06:34:14 +00002761 if (!Type->isConstantSizeType()) {
2762 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002763 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002764 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002765 return false;
2766 }
2767
2768 Size = Info.Ctx.getTypeSizeInChars(Type);
2769 return true;
2770}
2771
2772/// Update a pointer value to model pointer arithmetic.
2773/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002774/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002775/// \param LVal - The pointer value to be updated.
2776/// \param EltTy - The pointee type represented by LVal.
2777/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002778static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2779 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002780 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002781 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002782 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002783 return false;
2784
Yaxun Liu402804b2016-12-15 08:09:08 +00002785 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002786 return true;
2787}
2788
Richard Smithd6cc1982017-01-31 02:23:02 +00002789static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2790 LValue &LVal, QualType EltTy,
2791 int64_t Adjustment) {
2792 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2793 APSInt::get(Adjustment));
2794}
2795
Richard Smith66c96992012-02-18 22:04:06 +00002796/// Update an lvalue to refer to a component of a complex number.
2797/// \param Info - Information about the ongoing evaluation.
2798/// \param LVal - The lvalue to be updated.
2799/// \param EltTy - The complex number's component type.
2800/// \param Imag - False for the real component, true for the imaginary.
2801static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2802 LValue &LVal, QualType EltTy,
2803 bool Imag) {
2804 if (Imag) {
2805 CharUnits SizeOfComponent;
2806 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2807 return false;
2808 LVal.Offset += SizeOfComponent;
2809 }
2810 LVal.addComplex(Info, E, EltTy, Imag);
2811 return true;
2812}
2813
Richard Smith27908702011-10-24 17:54:18 +00002814/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002815///
2816/// \param Info Information about the ongoing evaluation.
2817/// \param E An expression to be used when printing diagnostics.
2818/// \param VD The variable whose initializer should be obtained.
2819/// \param Frame The frame in which the variable was created. Must be null
2820/// if this variable is not local to the evaluation.
2821/// \param Result Filled in with a pointer to the value of the variable.
2822static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2823 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002824 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002825
Richard Smith254a73d2011-10-28 22:34:42 +00002826 // If this is a parameter to an active constexpr function call, perform
2827 // argument substitution.
2828 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002829 // Assume arguments of a potential constant expression are unknown
2830 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002831 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002832 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002833 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002834 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002835 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002836 }
Richard Smith3229b742013-05-05 21:17:10 +00002837 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002838 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002839 }
Richard Smith27908702011-10-24 17:54:18 +00002840
Richard Smithd9f663b2013-04-22 15:31:51 +00002841 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002842 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002843 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2844 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002845 if (!Result) {
2846 // Assume variables referenced within a lambda's call operator that were
2847 // not declared within the call operator are captures and during checking
2848 // of a potential constant expression, assume they are unknown constant
2849 // expressions.
2850 assert(isLambdaCallOperator(Frame->Callee) &&
2851 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2852 "missing value for local variable");
2853 if (Info.checkingPotentialConstantExpression())
2854 return false;
2855 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002856 Info.FFDiag(E->getBeginLoc(),
2857 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002858 << "captures not currently allowed";
2859 return false;
2860 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002861 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002862 }
2863
Richard Smithd0b4dd62011-12-19 06:19:21 +00002864 // Dig out the initializer, and use the declaration which it's attached to.
2865 const Expr *Init = VD->getAnyInitializer(VD);
2866 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002867 // If we're checking a potential constant expression, the variable could be
2868 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002869 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002870 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002871 return false;
2872 }
2873
Richard Smithd62306a2011-11-10 06:34:14 +00002874 // If we're currently evaluating the initializer of this declaration, use that
2875 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002876 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002877 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002878 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002879 }
2880
Richard Smithcecf1842011-11-01 21:06:14 +00002881 // Never evaluate the initializer of a weak variable. We can't be sure that
2882 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002883 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002884 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002885 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002886 }
Richard Smithcecf1842011-11-01 21:06:14 +00002887
Richard Smithd0b4dd62011-12-19 06:19:21 +00002888 // Check that we can fold the initializer. In C++, we will have already done
2889 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002890 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002891 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002892 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002893 Notes.size() + 1) << VD;
2894 Info.Note(VD->getLocation(), diag::note_declared_at);
2895 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002896 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002897 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002898 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002899 Notes.size() + 1) << VD;
2900 Info.Note(VD->getLocation(), diag::note_declared_at);
2901 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002902 }
Richard Smith27908702011-10-24 17:54:18 +00002903
Richard Smith3229b742013-05-05 21:17:10 +00002904 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002905 return true;
Richard Smith27908702011-10-24 17:54:18 +00002906}
2907
Richard Smith11562c52011-10-28 17:51:58 +00002908static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002909 Qualifiers Quals = T.getQualifiers();
2910 return Quals.hasConst() && !Quals.hasVolatile();
2911}
2912
Richard Smithe97cbd72011-11-11 04:05:33 +00002913/// Get the base index of the given base class within an APValue representing
2914/// the given derived class.
2915static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2916 const CXXRecordDecl *Base) {
2917 Base = Base->getCanonicalDecl();
2918 unsigned Index = 0;
2919 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2920 E = Derived->bases_end(); I != E; ++I, ++Index) {
2921 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2922 return Index;
2923 }
2924
2925 llvm_unreachable("base class missing from derived class's bases list");
2926}
2927
Richard Smith3da88fa2013-04-26 14:36:30 +00002928/// Extract the value of a character from a string literal.
2929static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2930 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002931 assert(!isa<SourceLocExpr>(Lit) &&
2932 "SourceLocExpr should have already been converted to a StringLiteral");
2933
Akira Hatanakabc332642017-01-31 02:31:39 +00002934 // FIXME: Support MakeStringConstant
2935 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2936 std::string Str;
2937 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2938 assert(Index <= Str.size() && "Index too large");
2939 return APSInt::getUnsigned(Str.c_str()[Index]);
2940 }
2941
Alexey Bataevec474782014-10-09 08:45:04 +00002942 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2943 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002944 const StringLiteral *S = cast<StringLiteral>(Lit);
2945 const ConstantArrayType *CAT =
2946 Info.Ctx.getAsConstantArrayType(S->getType());
2947 assert(CAT && "string literal isn't an array");
2948 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002949 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002950
2951 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002952 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002953 if (Index < S->getLength())
2954 Value = S->getCodeUnit(Index);
2955 return Value;
2956}
2957
Richard Smith3da88fa2013-04-26 14:36:30 +00002958// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002959//
2960// FIXME: This is inefficient; we should probably introduce something similar
2961// to the LLVM ConstantDataArray to make this cheaper.
2962static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smithda1b4342019-09-27 01:26:47 +00002963 APValue &Result,
2964 QualType AllocType = QualType()) {
2965 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2966 AllocType.isNull() ? S->getType() : AllocType);
Richard Smith3da88fa2013-04-26 14:36:30 +00002967 assert(CAT && "string literal isn't an array");
2968 QualType CharType = CAT->getElementType();
2969 assert(CharType->isIntegerType() && "unexpected character type");
2970
2971 unsigned Elts = CAT->getSize().getZExtValue();
2972 Result = APValue(APValue::UninitArray(),
2973 std::min(S->getLength(), Elts), Elts);
2974 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2975 CharType->isUnsignedIntegerType());
2976 if (Result.hasArrayFiller())
2977 Result.getArrayFiller() = APValue(Value);
2978 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2979 Value = S->getCodeUnit(I);
2980 Result.getArrayInitializedElt(I) = APValue(Value);
2981 }
2982}
2983
2984// Expand an array so that it has more than Index filled elements.
2985static void expandArray(APValue &Array, unsigned Index) {
2986 unsigned Size = Array.getArraySize();
2987 assert(Index < Size);
2988
2989 // Always at least double the number of elements for which we store a value.
2990 unsigned OldElts = Array.getArrayInitializedElts();
2991 unsigned NewElts = std::max(Index+1, OldElts * 2);
2992 NewElts = std::min(Size, std::max(NewElts, 8u));
2993
2994 // Copy the data across.
2995 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2996 for (unsigned I = 0; I != OldElts; ++I)
2997 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2998 for (unsigned I = OldElts; I != NewElts; ++I)
2999 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3000 if (NewValue.hasArrayFiller())
3001 NewValue.getArrayFiller() = Array.getArrayFiller();
3002 Array.swap(NewValue);
3003}
3004
Richard Smithb01fe402014-09-16 01:24:02 +00003005/// Determine whether a type would actually be read by an lvalue-to-rvalue
3006/// conversion. If it's of class type, we may assume that the copy operation
3007/// is trivial. Note that this is never true for a union type with fields
3008/// (because the copy always "reads" the active member) and always true for
3009/// a non-class type.
3010static bool isReadByLvalueToRvalueConversion(QualType T) {
3011 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3012 if (!RD || (RD->isUnion() && !RD->field_empty()))
3013 return true;
3014 if (RD->isEmpty())
3015 return false;
3016
3017 for (auto *Field : RD->fields())
3018 if (isReadByLvalueToRvalueConversion(Field->getType()))
3019 return true;
3020
3021 for (auto &BaseSpec : RD->bases())
3022 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3023 return true;
3024
3025 return false;
3026}
3027
3028/// Diagnose an attempt to read from any unreadable field within the specified
3029/// type, which might be a class type.
Richard Smith2b4fa532019-09-29 05:08:46 +00003030static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3031 QualType T) {
Richard Smithb01fe402014-09-16 01:24:02 +00003032 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3033 if (!RD)
3034 return false;
3035
3036 if (!RD->hasMutableFields())
3037 return false;
3038
3039 for (auto *Field : RD->fields()) {
3040 // If we're actually going to read this field in some way, then it can't
3041 // be mutable. If we're in a union, then assigning to a mutable field
3042 // (even an empty one) can change the active member, so that's not OK.
3043 // FIXME: Add core issue number for the union case.
3044 if (Field->isMutable() &&
3045 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003046 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00003047 Info.Note(Field->getLocation(), diag::note_declared_at);
3048 return true;
3049 }
3050
Richard Smith2b4fa532019-09-29 05:08:46 +00003051 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00003052 return true;
3053 }
3054
3055 for (auto &BaseSpec : RD->bases())
Richard Smith2b4fa532019-09-29 05:08:46 +00003056 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00003057 return true;
3058
3059 // All mutable fields were empty, and thus not actually read.
3060 return false;
3061}
3062
Richard Smithdebad642019-05-12 09:39:08 +00003063static bool lifetimeStartedInEvaluation(EvalInfo &Info,
Richard Smith2b4fa532019-09-29 05:08:46 +00003064 APValue::LValueBase Base,
3065 bool MutableSubobject = false) {
Richard Smithdebad642019-05-12 09:39:08 +00003066 // A temporary we created.
3067 if (Base.getCallIndex())
3068 return true;
3069
3070 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3071 if (!Evaluating)
3072 return false;
3073
Richard Smith2b4fa532019-09-29 05:08:46 +00003074 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
Richard Smithdebad642019-05-12 09:39:08 +00003075
Richard Smith2b4fa532019-09-29 05:08:46 +00003076 switch (Info.IsEvaluatingDecl) {
3077 case EvalInfo::EvaluatingDeclKind::None:
3078 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003079
Richard Smith2b4fa532019-09-29 05:08:46 +00003080 case EvalInfo::EvaluatingDeclKind::Ctor:
3081 // The variable whose initializer we're evaluating.
3082 if (BaseD)
3083 return declaresSameEntity(Evaluating, BaseD);
3084
3085 // A temporary lifetime-extended by the variable whose initializer we're
3086 // evaluating.
3087 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3088 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3089 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3090 return false;
3091
3092 case EvalInfo::EvaluatingDeclKind::Dtor:
3093 // C++2a [expr.const]p6:
3094 // [during constant destruction] the lifetime of a and its non-mutable
3095 // subobjects (but not its mutable subobjects) [are] considered to start
3096 // within e.
3097 //
3098 // FIXME: We can meaningfully extend this to cover non-const objects, but
3099 // we will need special handling: we should be able to access only
3100 // subobjects of such objects that are themselves declared const.
3101 if (!BaseD ||
3102 !(BaseD->getType().isConstQualified() ||
3103 BaseD->getType()->isReferenceType()) ||
3104 MutableSubobject)
3105 return false;
3106 return declaresSameEntity(Evaluating, BaseD);
3107 }
3108
3109 llvm_unreachable("unknown evaluating decl kind");
Richard Smithdebad642019-05-12 09:39:08 +00003110}
3111
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003112namespace {
Richard Smith3229b742013-05-05 21:17:10 +00003113/// A handle to a complete object (an object that is not a subobject of
3114/// another object).
3115struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003116 /// The identity of the object.
3117 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00003118 /// The value of the complete object.
3119 APValue *Value;
3120 /// The type of the complete object.
3121 QualType Type;
3122
Craig Topper36250ad2014-05-12 05:36:57 +00003123 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00003124 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3125 : Base(Base), Value(Value), Type(Type) {}
3126
Richard Smith2b4fa532019-09-29 05:08:46 +00003127 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
Richard Smithdebad642019-05-12 09:39:08 +00003128 // In C++14 onwards, it is permitted to read a mutable member whose
3129 // lifetime began within the evaluation.
3130 // FIXME: Should we also allow this in C++11?
3131 if (!Info.getLangOpts().CPlusPlus14)
3132 return false;
Richard Smith2b4fa532019-09-29 05:08:46 +00003133 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
Richard Smith3229b742013-05-05 21:17:10 +00003134 }
3135
Richard Smithdebad642019-05-12 09:39:08 +00003136 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00003137};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003138} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00003139
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003140static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3141 bool IsMutable = false) {
3142 // C++ [basic.type.qualifier]p1:
3143 // - A const object is an object of type const T or a non-mutable subobject
3144 // of a const object.
3145 if (ObjType.isConstQualified() && !IsMutable)
3146 SubobjType.addConst();
3147 // - A volatile object is an object of type const T or a subobject of a
3148 // volatile object.
3149 if (ObjType.isVolatileQualified())
3150 SubobjType.addVolatile();
3151 return SubobjType;
3152}
3153
Richard Smith3da88fa2013-04-26 14:36:30 +00003154/// Find the designated sub-object of an rvalue.
3155template<typename SubobjectHandler>
3156typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00003157findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003158 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003159 if (Sub.Invalid)
3160 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00003161 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00003162 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003163 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00003164 Info.FFDiag(E, Sub.isOnePastTheEnd()
3165 ? diag::note_constexpr_access_past_end
3166 : diag::note_constexpr_access_unsized_array)
3167 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003168 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003169 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003170 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00003171 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003172
Richard Smith3229b742013-05-05 21:17:10 +00003173 APValue *O = Obj.Value;
3174 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00003175 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003176 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003177
Richard Smithd62306a2011-11-10 06:34:14 +00003178 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003179 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003180 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithb5426022019-10-03 00:39:35 +00003181 if ((O->isAbsent() && handler.AccessKind != AK_Construct) ||
3182 (O->isIndeterminate() && handler.AccessKind != AK_Construct &&
3183 handler.AccessKind != AK_Assign &&
Richard Smithc667cdc2019-09-18 17:37:44 +00003184 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003185 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003186 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003187 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003188 return handler.failed();
3189 }
3190
Richard Smith457226e2019-09-23 03:48:44 +00003191 // C++ [class.ctor]p5, C++ [class.dtor]p5:
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003192 // const and volatile semantics are not applied on an object under
Richard Smith457226e2019-09-23 03:48:44 +00003193 // {con,de}struction.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003194 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3195 ObjType->isRecordType() &&
Richard Smith457226e2019-09-23 03:48:44 +00003196 Info.isEvaluatingCtorDtor(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003197 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3198 Sub.Entries.begin() + I)) !=
3199 ConstructionPhase::None) {
3200 ObjType = Info.Ctx.getCanonicalType(ObjType);
3201 ObjType.removeLocalConst();
3202 ObjType.removeLocalVolatile();
3203 }
3204
3205 // If this is our last pass, check that the final object type is OK.
3206 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3207 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003208 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003209 if (Info.getLangOpts().CPlusPlus) {
3210 int DiagKind;
3211 SourceLocation Loc;
3212 const NamedDecl *Decl = nullptr;
3213 if (VolatileField) {
3214 DiagKind = 2;
3215 Loc = VolatileField->getLocation();
3216 Decl = VolatileField;
3217 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3218 DiagKind = 1;
3219 Loc = VD->getLocation();
3220 Decl = VD;
3221 } else {
3222 DiagKind = 0;
3223 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3224 Loc = E->getExprLoc();
3225 }
3226 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3227 << handler.AccessKind << DiagKind << Decl;
3228 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3229 } else {
3230 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3231 }
3232 return handler.failed();
3233 }
3234
Richard Smithb01fe402014-09-16 01:24:02 +00003235 // If we are reading an object of class type, there may still be more
3236 // things we need to check: if there are any mutable subobjects, we
3237 // cannot perform this read. (This only happens when performing a trivial
3238 // copy or assignment.)
Richard Smith2b4fa532019-09-29 05:08:46 +00003239 if (ObjType->isRecordType() &&
3240 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3241 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003242 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003243 }
Richard Smithb01fe402014-09-16 01:24:02 +00003244
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003245 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003246 if (!handler.found(*O, ObjType))
3247 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003248
Richard Smith49ca8aa2013-08-06 07:09:20 +00003249 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003250 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003251 LastField && LastField->isBitField() &&
3252 !truncateBitfieldValue(Info, E, *O, LastField))
3253 return false;
3254
3255 return true;
3256 }
3257
Craig Topper36250ad2014-05-12 05:36:57 +00003258 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003259 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003260 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003261 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003262 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003263 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003264 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003265 // Note, it should not be possible to form a pointer with a valid
3266 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003267 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003268 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003269 << handler.AccessKind;
3270 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003271 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003272 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003273 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003274
3275 ObjType = CAT->getElementType();
3276
Richard Smith3da88fa2013-04-26 14:36:30 +00003277 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003278 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00003279 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003280 expandArray(*O, Index);
3281 O = &O->getArrayInitializedElt(Index);
3282 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003283 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003284 } else if (ObjType->isAnyComplexType()) {
3285 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003286 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003287 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003288 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003289 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003290 << handler.AccessKind;
3291 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003292 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003293 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003294 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003295
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003296 ObjType = getSubobjectType(
3297 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003298
Richard Smith66c96992012-02-18 22:04:06 +00003299 assert(I == N - 1 && "extracting subobject of scalar?");
3300 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003301 return handler.found(Index ? O->getComplexIntImag()
3302 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003303 } else {
3304 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003305 return handler.found(Index ? O->getComplexFloatImag()
3306 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003307 }
Richard Smithd62306a2011-11-10 06:34:14 +00003308 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003309 if (Field->isMutable() &&
3310 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3311 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3312 << handler.AccessKind << Field;
Richard Smith5a294e62012-02-09 03:29:58 +00003313 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003314 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003315 }
3316
Richard Smithd62306a2011-11-10 06:34:14 +00003317 // Next subobject is a class, struct or union field.
3318 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3319 if (RD->isUnion()) {
3320 const FieldDecl *UnionField = O->getUnionField();
3321 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003322 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithb5426022019-10-03 00:39:35 +00003323 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3324 // Placement new onto an inactive union member makes it active.
3325 O->setUnion(Field, APValue());
3326 } else {
3327 // FIXME: If O->getUnionValue() is absent, report that there's no
3328 // active union member rather than reporting the prior active union
3329 // member. We'll need to fix nullptr_t to not use APValue() as its
3330 // representation first.
3331 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3332 << handler.AccessKind << Field << !UnionField << UnionField;
3333 return handler.failed();
3334 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003335 }
Richard Smithd62306a2011-11-10 06:34:14 +00003336 O = &O->getUnionValue();
3337 } else
3338 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003339
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003340 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003341 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003342 if (Field->getType().isVolatileQualified())
3343 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003344 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003345 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003346 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3347 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3348 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003349
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003350 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003351 }
3352 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003353}
3354
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003355namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003356struct ExtractSubobjectHandler {
3357 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003358 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003359 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003360 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003361
3362 typedef bool result_type;
3363 bool failed() { return false; }
3364 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003365 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003366 if (AccessKind == AK_ReadObjectRepresentation)
3367 return true;
3368 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003369 }
3370 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003371 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003372 return true;
3373 }
3374 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003375 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003376 return true;
3377 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003378};
Richard Smith3229b742013-05-05 21:17:10 +00003379} // end anonymous namespace
3380
Richard Smith3da88fa2013-04-26 14:36:30 +00003381/// Extract the designated sub-object of an rvalue.
3382static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003383 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003384 const SubobjectDesignator &Sub, APValue &Result,
3385 AccessKinds AK = AK_Read) {
3386 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3387 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003388 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003389}
3390
Richard Smith3229b742013-05-05 21:17:10 +00003391namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003392struct ModifySubobjectHandler {
3393 EvalInfo &Info;
3394 APValue &NewVal;
3395 const Expr *E;
3396
3397 typedef bool result_type;
3398 static const AccessKinds AccessKind = AK_Assign;
3399
3400 bool checkConst(QualType QT) {
3401 // Assigning to a const object has undefined behavior.
3402 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003403 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003404 return false;
3405 }
3406 return true;
3407 }
3408
3409 bool failed() { return false; }
3410 bool found(APValue &Subobj, QualType SubobjType) {
3411 if (!checkConst(SubobjType))
3412 return false;
3413 // We've been given ownership of NewVal, so just swap it in.
3414 Subobj.swap(NewVal);
3415 return true;
3416 }
3417 bool found(APSInt &Value, QualType SubobjType) {
3418 if (!checkConst(SubobjType))
3419 return false;
3420 if (!NewVal.isInt()) {
3421 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003422 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003423 return false;
3424 }
3425 Value = NewVal.getInt();
3426 return true;
3427 }
3428 bool found(APFloat &Value, QualType SubobjType) {
3429 if (!checkConst(SubobjType))
3430 return false;
3431 Value = NewVal.getFloat();
3432 return true;
3433 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003434};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003435} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003436
Richard Smith3229b742013-05-05 21:17:10 +00003437const AccessKinds ModifySubobjectHandler::AccessKind;
3438
Richard Smith3da88fa2013-04-26 14:36:30 +00003439/// Update the designated sub-object of an rvalue to the given value.
3440static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003441 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003442 const SubobjectDesignator &Sub,
3443 APValue &NewVal) {
3444 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003445 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003446}
3447
Richard Smith84f6dcf2012-02-02 01:16:57 +00003448/// Find the position where two subobject designators diverge, or equivalently
3449/// the length of the common initial subsequence.
3450static unsigned FindDesignatorMismatch(QualType ObjType,
3451 const SubobjectDesignator &A,
3452 const SubobjectDesignator &B,
3453 bool &WasArrayIndex) {
3454 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3455 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003456 if (!ObjType.isNull() &&
3457 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003458 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003459 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003460 WasArrayIndex = true;
3461 return I;
3462 }
Richard Smith66c96992012-02-18 22:04:06 +00003463 if (ObjType->isAnyComplexType())
3464 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3465 else
3466 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003467 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003468 if (A.Entries[I].getAsBaseOrMember() !=
3469 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003470 WasArrayIndex = false;
3471 return I;
3472 }
3473 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3474 // Next subobject is a field.
3475 ObjType = FD->getType();
3476 else
3477 // Next subobject is a base class.
3478 ObjType = QualType();
3479 }
3480 }
3481 WasArrayIndex = false;
3482 return I;
3483}
3484
3485/// Determine whether the given subobject designators refer to elements of the
3486/// same array object.
3487static bool AreElementsOfSameArray(QualType ObjType,
3488 const SubobjectDesignator &A,
3489 const SubobjectDesignator &B) {
3490 if (A.Entries.size() != B.Entries.size())
3491 return false;
3492
George Burgess IVa51c4072015-10-16 01:49:01 +00003493 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003494 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3495 // A is a subobject of the array element.
3496 return false;
3497
3498 // If A (and B) designates an array element, the last entry will be the array
3499 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3500 // of length 1' case, and the entire path must match.
3501 bool WasArrayIndex;
3502 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3503 return CommonLength >= A.Entries.size() - IsArray;
3504}
3505
Richard Smith3229b742013-05-05 21:17:10 +00003506/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003507static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3508 AccessKinds AK, const LValue &LVal,
3509 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003510 if (LVal.InvalidBase) {
3511 Info.FFDiag(E);
3512 return CompleteObject();
3513 }
3514
Richard Smith3229b742013-05-05 21:17:10 +00003515 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003516 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003517 return CompleteObject();
3518 }
3519
Craig Topper36250ad2014-05-12 05:36:57 +00003520 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003521 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003522 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003523 std::tie(Frame, Depth) =
3524 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003525 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003526 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003527 << AK << LVal.Base.is<const ValueDecl*>();
3528 NoteLValueLocation(Info, LVal.Base);
3529 return CompleteObject();
3530 }
Richard Smith3229b742013-05-05 21:17:10 +00003531 }
3532
Richard Smith61422f92019-09-27 20:24:36 +00003533 bool IsAccess = isAnyAccess(AK);
Richard Smith7bd54ab2019-05-15 20:22:21 +00003534
Richard Smith3229b742013-05-05 21:17:10 +00003535 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3536 // is not a constant expression (even if the object is non-volatile). We also
3537 // apply this rule to C++98, in order to conform to the expected 'volatile'
3538 // semantics.
Richard Smith61422f92019-09-27 20:24:36 +00003539 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003540 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003541 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003542 << AK << LValType;
3543 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003544 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003545 return CompleteObject();
3546 }
3547
3548 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003549 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003550 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003551
3552 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3553 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3554 // In C++11, constexpr, non-volatile variables initialized with constant
3555 // expressions are constant expressions too. Inside constexpr functions,
3556 // parameters are constant expressions even if they're non-const.
3557 // In C++1y, objects local to a constant expression (those with a Frame) are
3558 // both readable and writable inside constant expressions.
3559 // In C, such things can also be folded, although they are not ICEs.
3560 const VarDecl *VD = dyn_cast<VarDecl>(D);
3561 if (VD) {
3562 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3563 VD = VDef;
3564 }
3565 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003566 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003567 return CompleteObject();
3568 }
3569
Richard Smith3229b742013-05-05 21:17:10 +00003570 // Unless we're looking at a local variable or argument in a constexpr call,
3571 // the variable we're reading must be const.
3572 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003573 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003574 lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003575 // OK, we can read and modify an object if we're in the process of
3576 // evaluating its initializer, because its lifetime began in this
3577 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003578 } else if (isModification(AK)) {
3579 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003580 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003581 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003582 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003583 // OK, we can read this variable.
3584 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003585 // In OpenCL if a variable is in constant address space it is a const
3586 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003587 if (!(BaseType.isConstQualified() ||
3588 (Info.getLangOpts().OpenCL &&
3589 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003590 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003591 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003592 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003593 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003594 Info.Note(VD->getLocation(), diag::note_declared_at);
3595 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003596 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003597 }
3598 return CompleteObject();
3599 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003600 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003601 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003602 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3603 // We support folding of const floating-point types, in order to make
3604 // static const data members of such types (supported as an extension)
3605 // more useful.
3606 if (Info.getLangOpts().CPlusPlus11) {
3607 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3608 Info.Note(VD->getLocation(), diag::note_declared_at);
3609 } else {
3610 Info.CCEDiag(E);
3611 }
George Burgess IVb5316982016-12-27 05:33:20 +00003612 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3613 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3614 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003615 } else {
3616 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003617 if (Info.checkingPotentialConstantExpression() &&
3618 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3619 // The definition of this variable could be constexpr. We can't
3620 // access it right now, but may be able to in future.
3621 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003622 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003623 Info.Note(VD->getLocation(), diag::note_declared_at);
3624 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003625 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003626 }
3627 return CompleteObject();
3628 }
3629 }
3630
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003631 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003632 return CompleteObject();
Richard Smithda1b4342019-09-27 01:26:47 +00003633 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
Richard Smith19ad5232019-10-03 00:39:33 +00003634 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
Richard Smithda1b4342019-09-27 01:26:47 +00003635 if (!Alloc) {
3636 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3637 return CompleteObject();
3638 }
3639 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3640 LVal.Base.getDynamicAllocType());
Richard Smith3229b742013-05-05 21:17:10 +00003641 } else {
3642 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3643
3644 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003645 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003646 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003647 assert(MTE->getStorageDuration() == SD_Static &&
3648 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003649
Richard Smithe6c01442013-06-05 00:46:14 +00003650 // Per C++1y [expr.const]p2:
3651 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3652 // - a [...] glvalue of integral or enumeration type that refers to
3653 // a non-volatile const object [...]
3654 // [...]
3655 // - a [...] glvalue of literal type that refers to a non-volatile
3656 // object whose lifetime began within the evaluation of e.
3657 //
3658 // C++11 misses the 'began within the evaluation of e' check and
3659 // instead allows all temporaries, including things like:
3660 // int &&r = 1;
3661 // int x = ++r;
3662 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003663 // Therefore we use the C++14 rules in C++11 too.
Richard Smith2b4fa532019-09-29 05:08:46 +00003664 //
3665 // Note that temporaries whose lifetimes began while evaluating a
3666 // variable's constructor are not usable while evaluating the
3667 // corresponding destructor, not even if they're of const-qualified
3668 // types.
Richard Smithe6c01442013-06-05 00:46:14 +00003669 if (!(BaseType.isConstQualified() &&
3670 BaseType->isIntegralOrEnumerationType()) &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003671 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003672 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003673 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003674 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003675 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3676 return CompleteObject();
3677 }
3678
3679 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3680 assert(BaseVal && "got reference to unevaluated temporary");
3681 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003682 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003683 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003684 APValue Val;
3685 LVal.moveInto(Val);
3686 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3687 << AK
3688 << Val.getAsString(Info.Ctx,
3689 Info.Ctx.getLValueReferenceType(LValType));
3690 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003691 return CompleteObject();
3692 }
3693 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003694 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003695 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003696 }
Richard Smith7525ff62013-05-09 07:14:00 +00003697 }
3698
Richard Smith9defb7d2018-02-21 03:38:30 +00003699 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003700 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003701 //
3702 // FIXME: Not all local state is mutable. Allow local constant subobjects
3703 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003704 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3705 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003706 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003707 return CompleteObject();
3708
Richard Smithdebad642019-05-12 09:39:08 +00003709 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003710}
3711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003712/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003713/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3714/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003715///
3716/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003717/// \param Conv - The expression for which we are performing the conversion.
3718/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003719/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3720/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003721/// \param LVal - The glvalue on which we are attempting to perform this action.
3722/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003723/// \param WantObjectRepresentation - If true, we're looking for the object
3724/// representation rather than the value, and in particular,
3725/// there is no requirement that the result be fully initialized.
3726static bool
3727handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3728 const LValue &LVal, APValue &RVal,
3729 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003730 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003731 return false;
3732
Richard Smith3229b742013-05-05 21:17:10 +00003733 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003734 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003735
Richard Smithc667cdc2019-09-18 17:37:44 +00003736 AccessKinds AK =
3737 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3738
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003739 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003740 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3741 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3742 // initializer until now for such expressions. Such an expression can't be
3743 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003744 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003745 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003746 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003747 }
Richard Smith3229b742013-05-05 21:17:10 +00003748 APValue Lit;
3749 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3750 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003751 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003752 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003753 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003754 // Special-case character extraction so we don't have to construct an
3755 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003756 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003757 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003758 if (LVal.Designator.Entries.empty()) {
3759 // Fail for now for LValue to RValue conversion of an array.
3760 // (This shouldn't show up in C/C++, but it could be triggered by a
3761 // weird EvaluateAsRValue call from a tool.)
3762 Info.FFDiag(Conv);
3763 return false;
3764 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003765 if (LVal.Designator.isOnePastTheEnd()) {
3766 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003767 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003768 else
3769 Info.FFDiag(Conv);
3770 return false;
3771 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003772 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003773 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3774 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003775 }
Richard Smith11562c52011-10-28 17:51:58 +00003776 }
3777
Richard Smithc667cdc2019-09-18 17:37:44 +00003778 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3779 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003780}
3781
3782/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003783static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003784 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003785 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003786 return false;
3787
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003788 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003789 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003790 return false;
3791 }
3792
Richard Smith3229b742013-05-05 21:17:10 +00003793 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003794 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3795}
3796
3797namespace {
3798struct CompoundAssignSubobjectHandler {
3799 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003800 const Expr *E;
3801 QualType PromotedLHSType;
3802 BinaryOperatorKind Opcode;
3803 const APValue &RHS;
3804
3805 static const AccessKinds AccessKind = AK_Assign;
3806
3807 typedef bool result_type;
3808
3809 bool checkConst(QualType QT) {
3810 // Assigning to a const object has undefined behavior.
3811 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003812 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003813 return false;
3814 }
3815 return true;
3816 }
3817
3818 bool failed() { return false; }
3819 bool found(APValue &Subobj, QualType SubobjType) {
3820 switch (Subobj.getKind()) {
3821 case APValue::Int:
3822 return found(Subobj.getInt(), SubobjType);
3823 case APValue::Float:
3824 return found(Subobj.getFloat(), SubobjType);
3825 case APValue::ComplexInt:
3826 case APValue::ComplexFloat:
3827 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003828 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003829 return false;
3830 case APValue::LValue:
3831 return foundPointer(Subobj, SubobjType);
3832 default:
3833 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003834 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003835 return false;
3836 }
3837 }
3838 bool found(APSInt &Value, QualType SubobjType) {
3839 if (!checkConst(SubobjType))
3840 return false;
3841
Tan S. B.9f935e82018-12-18 07:38:06 +00003842 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003843 // We don't support compound assignment on integer-cast-to-pointer
3844 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003845 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003846 return false;
3847 }
3848
Tan S. B.9f935e82018-12-18 07:38:06 +00003849 if (RHS.isInt()) {
3850 APSInt LHS =
3851 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3852 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3853 return false;
3854 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3855 return true;
3856 } else if (RHS.isFloat()) {
3857 APFloat FValue(0.0);
3858 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3859 FValue) &&
3860 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3861 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3862 Value);
3863 }
3864
3865 Info.FFDiag(E);
3866 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003867 }
3868 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003869 return checkConst(SubobjType) &&
3870 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3871 Value) &&
3872 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3873 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003874 }
3875 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3876 if (!checkConst(SubobjType))
3877 return false;
3878
3879 QualType PointeeType;
3880 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3881 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003882
3883 if (PointeeType.isNull() || !RHS.isInt() ||
3884 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003885 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003886 return false;
3887 }
3888
Richard Smithd6cc1982017-01-31 02:23:02 +00003889 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003890 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003891 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003892
3893 LValue LVal;
3894 LVal.setFrom(Info.Ctx, Subobj);
3895 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3896 return false;
3897 LVal.moveInto(Subobj);
3898 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003899 }
Richard Smith43e77732013-05-07 04:50:00 +00003900};
3901} // end anonymous namespace
3902
3903const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3904
3905/// Perform a compound assignment of LVal <op>= RVal.
3906static bool handleCompoundAssignment(
3907 EvalInfo &Info, const Expr *E,
3908 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3909 BinaryOperatorKind Opcode, const APValue &RVal) {
3910 if (LVal.Designator.Invalid)
3911 return false;
3912
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003913 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003914 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003915 return false;
3916 }
3917
3918 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3919 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3920 RVal };
3921 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3922}
3923
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003924namespace {
3925struct IncDecSubobjectHandler {
3926 EvalInfo &Info;
3927 const UnaryOperator *E;
3928 AccessKinds AccessKind;
3929 APValue *Old;
3930
Richard Smith243ef902013-05-05 23:31:59 +00003931 typedef bool result_type;
3932
3933 bool checkConst(QualType QT) {
3934 // Assigning to a const object has undefined behavior.
3935 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003936 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003937 return false;
3938 }
3939 return true;
3940 }
3941
3942 bool failed() { return false; }
3943 bool found(APValue &Subobj, QualType SubobjType) {
3944 // Stash the old value. Also clear Old, so we don't clobber it later
3945 // if we're post-incrementing a complex.
3946 if (Old) {
3947 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003948 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003949 }
3950
3951 switch (Subobj.getKind()) {
3952 case APValue::Int:
3953 return found(Subobj.getInt(), SubobjType);
3954 case APValue::Float:
3955 return found(Subobj.getFloat(), SubobjType);
3956 case APValue::ComplexInt:
3957 return found(Subobj.getComplexIntReal(),
3958 SubobjType->castAs<ComplexType>()->getElementType()
3959 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3960 case APValue::ComplexFloat:
3961 return found(Subobj.getComplexFloatReal(),
3962 SubobjType->castAs<ComplexType>()->getElementType()
3963 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3964 case APValue::LValue:
3965 return foundPointer(Subobj, SubobjType);
3966 default:
3967 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003968 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003969 return false;
3970 }
3971 }
3972 bool found(APSInt &Value, QualType SubobjType) {
3973 if (!checkConst(SubobjType))
3974 return false;
3975
3976 if (!SubobjType->isIntegerType()) {
3977 // We don't support increment / decrement on integer-cast-to-pointer
3978 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003979 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003980 return false;
3981 }
3982
3983 if (Old) *Old = APValue(Value);
3984
3985 // bool arithmetic promotes to int, and the conversion back to bool
3986 // doesn't reduce mod 2^n, so special-case it.
3987 if (SubobjType->isBooleanType()) {
3988 if (AccessKind == AK_Increment)
3989 Value = 1;
3990 else
3991 Value = !Value;
3992 return true;
3993 }
3994
3995 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003996 if (AccessKind == AK_Increment) {
3997 ++Value;
3998
3999 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4000 APSInt ActualValue(Value, /*IsUnsigned*/true);
4001 return HandleOverflow(Info, E, ActualValue, SubobjType);
4002 }
4003 } else {
4004 --Value;
4005
4006 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4007 unsigned BitWidth = Value.getBitWidth();
4008 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4009 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00004010 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00004011 }
4012 }
4013 return true;
4014 }
4015 bool found(APFloat &Value, QualType SubobjType) {
4016 if (!checkConst(SubobjType))
4017 return false;
4018
4019 if (Old) *Old = APValue(Value);
4020
4021 APFloat One(Value.getSemantics(), 1);
4022 if (AccessKind == AK_Increment)
4023 Value.add(One, APFloat::rmNearestTiesToEven);
4024 else
4025 Value.subtract(One, APFloat::rmNearestTiesToEven);
4026 return true;
4027 }
4028 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4029 if (!checkConst(SubobjType))
4030 return false;
4031
4032 QualType PointeeType;
4033 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4034 PointeeType = PT->getPointeeType();
4035 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004036 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00004037 return false;
4038 }
4039
4040 LValue LVal;
4041 LVal.setFrom(Info.Ctx, Subobj);
4042 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4043 AccessKind == AK_Increment ? 1 : -1))
4044 return false;
4045 LVal.moveInto(Subobj);
4046 return true;
4047 }
Richard Smith243ef902013-05-05 23:31:59 +00004048};
4049} // end anonymous namespace
4050
4051/// Perform an increment or decrement on LVal.
4052static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4053 QualType LValType, bool IsIncrement, APValue *Old) {
4054 if (LVal.Designator.Invalid)
4055 return false;
4056
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004057 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004058 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00004059 return false;
4060 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00004061
4062 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4063 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4064 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4065 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4066}
4067
Richard Smithe97cbd72011-11-11 04:05:33 +00004068/// Build an lvalue for the object argument of a member function call.
4069static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4070 LValue &This) {
Richard Smith5e18f4d2019-10-02 01:13:57 +00004071 if (Object->getType()->isPointerType() && Object->isRValue())
Richard Smithe97cbd72011-11-11 04:05:33 +00004072 return EvaluatePointer(Object, This, Info);
4073
4074 if (Object->isGLValue())
4075 return EvaluateLValue(Object, This, Info);
4076
Richard Smithd9f663b2013-04-22 15:31:51 +00004077 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00004078 return EvaluateTemporary(Object, This, Info);
4079
Faisal Valie690b7a2016-07-02 22:34:24 +00004080 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004081 return false;
4082}
4083
4084/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4085/// lvalue referring to the result.
4086///
4087/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00004088/// \param LV - An lvalue referring to the base of the member pointer.
4089/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00004090/// \param IncludeMember - Specifies whether the member itself is included in
4091/// the resulting LValue subobject designator. This is not possible when
4092/// creating a bound member function.
4093/// \return The field or method declaration to which the member pointer refers,
4094/// or 0 if evaluation fails.
4095static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00004096 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00004097 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00004098 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00004099 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00004100 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00004101 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00004102 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004103
4104 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4105 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00004106 if (!MemPtr.getDecl()) {
4107 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00004108 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004109 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004110 }
Richard Smith253c2a32012-01-27 01:14:48 +00004111
Richard Smith027bf112011-11-17 22:56:20 +00004112 if (MemPtr.isDerivedMember()) {
4113 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00004114 // The end of the derived-to-base path for the base object must match the
4115 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00004116 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00004117 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004118 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004119 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004120 }
Richard Smith027bf112011-11-17 22:56:20 +00004121 unsigned PathLengthToMember =
4122 LV.Designator.Entries.size() - MemPtr.Path.size();
4123 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4124 const CXXRecordDecl *LVDecl = getAsBaseClass(
4125 LV.Designator.Entries[PathLengthToMember + I]);
4126 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00004127 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004128 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004129 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004130 }
Richard Smith027bf112011-11-17 22:56:20 +00004131 }
4132
4133 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00004134 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004135 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00004136 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004137 } else if (!MemPtr.Path.empty()) {
4138 // Extend the LValue path with the member pointer's path.
4139 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4140 MemPtr.Path.size() + IncludeMember);
4141
4142 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00004143 if (const PointerType *PT = LVType->getAs<PointerType>())
4144 LVType = PT->getPointeeType();
4145 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4146 assert(RD && "member pointer access on non-class-type expression");
4147 // The first class in the path is that of the lvalue.
4148 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4149 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00004150 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00004151 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004152 RD = Base;
4153 }
4154 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00004155 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4156 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00004157 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004158 }
4159
4160 // Add the member. Note that we cannot build bound member functions here.
4161 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00004162 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004163 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00004164 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004165 } else if (const IndirectFieldDecl *IFD =
4166 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004167 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00004168 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004169 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004170 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00004171 }
Richard Smith027bf112011-11-17 22:56:20 +00004172 }
4173
4174 return MemPtr.getDecl();
4175}
4176
Richard Smith84401042013-06-03 05:03:02 +00004177static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4178 const BinaryOperator *BO,
4179 LValue &LV,
4180 bool IncludeMember = true) {
4181 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4182
4183 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00004184 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00004185 MemberPtr MemPtr;
4186 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4187 }
Craig Topper36250ad2014-05-12 05:36:57 +00004188 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004189 }
4190
4191 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4192 BO->getRHS(), IncludeMember);
4193}
4194
Richard Smith027bf112011-11-17 22:56:20 +00004195/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4196/// the provided lvalue, which currently refers to the base object.
4197static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4198 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00004199 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00004200 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00004201 return false;
4202
Richard Smitha8105bc2012-01-06 16:39:00 +00004203 QualType TargetQT = E->getType();
4204 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4205 TargetQT = PT->getPointeeType();
4206
4207 // Check this cast lands within the final derived-to-base subobject path.
4208 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004209 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004210 << D.MostDerivedType << TargetQT;
4211 return false;
4212 }
4213
Richard Smith027bf112011-11-17 22:56:20 +00004214 // Check the type of the final cast. We don't need to check the path,
4215 // since a cast can only be formed if the path is unique.
4216 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004217 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4218 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004219 if (NewEntriesSize == D.MostDerivedPathLength)
4220 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4221 else
Richard Smith027bf112011-11-17 22:56:20 +00004222 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004223 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004224 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004225 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004226 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004227 }
Richard Smith027bf112011-11-17 22:56:20 +00004228
4229 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004230 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004231}
4232
Richard Smithc667cdc2019-09-18 17:37:44 +00004233/// Get the value to use for a default-initialized object of type T.
4234static APValue getDefaultInitValue(QualType T) {
4235 if (auto *RD = T->getAsCXXRecordDecl()) {
4236 if (RD->isUnion())
4237 return APValue((const FieldDecl*)nullptr);
4238
4239 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4240 std::distance(RD->field_begin(), RD->field_end()));
4241
4242 unsigned Index = 0;
4243 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4244 End = RD->bases_end(); I != End; ++I, ++Index)
4245 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4246
4247 for (const auto *I : RD->fields()) {
4248 if (I->isUnnamedBitfield())
4249 continue;
4250 Struct.getStructField(I->getFieldIndex()) =
4251 getDefaultInitValue(I->getType());
4252 }
4253 return Struct;
4254 }
4255
4256 if (auto *AT =
4257 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4258 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4259 if (Array.hasArrayFiller())
4260 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4261 return Array;
4262 }
4263
4264 return APValue::IndeterminateValue();
4265}
4266
Mike Stump876387b2009-10-27 22:09:17 +00004267namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004268enum EvalStmtResult {
4269 /// Evaluation failed.
4270 ESR_Failed,
4271 /// Hit a 'return' statement.
4272 ESR_Returned,
4273 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004274 ESR_Succeeded,
4275 /// Hit a 'continue' statement.
4276 ESR_Continue,
4277 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004278 ESR_Break,
4279 /// Still scanning for 'case' or 'default' statement.
4280 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004281};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004282}
Richard Smith254a73d2011-10-28 22:34:42 +00004283
Richard Smith97fcf4b2016-08-14 23:15:52 +00004284static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4285 // We don't need to evaluate the initializer for a static local.
4286 if (!VD->hasLocalStorage())
4287 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004288
Richard Smith97fcf4b2016-08-14 23:15:52 +00004289 LValue Result;
Richard Smith457226e2019-09-23 03:48:44 +00004290 APValue &Val =
4291 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
Richard Smithd9f663b2013-04-22 15:31:51 +00004292
Richard Smith97fcf4b2016-08-14 23:15:52 +00004293 const Expr *InitE = VD->getInit();
4294 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00004295 Val = getDefaultInitValue(VD->getType());
4296 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00004297 }
Richard Smith51f03172013-06-20 03:00:05 +00004298
Richard Smith97fcf4b2016-08-14 23:15:52 +00004299 if (InitE->isValueDependent())
4300 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004301
Richard Smith97fcf4b2016-08-14 23:15:52 +00004302 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4303 // Wipe out any partially-computed value, to allow tracking that this
4304 // evaluation failed.
4305 Val = APValue();
4306 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004307 }
4308
4309 return true;
4310}
4311
Richard Smith97fcf4b2016-08-14 23:15:52 +00004312static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4313 bool OK = true;
4314
4315 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4316 OK &= EvaluateVarDecl(Info, VD);
4317
4318 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4319 for (auto *BD : DD->bindings())
4320 if (auto *VD = BD->getHoldingVar())
4321 OK &= EvaluateDecl(Info, VD);
4322
4323 return OK;
4324}
4325
4326
Richard Smith4e18ca52013-05-06 05:56:11 +00004327/// Evaluate a condition (either a variable declaration or an expression).
4328static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4329 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004330 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004331 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4332 return false;
Richard Smith457226e2019-09-23 03:48:44 +00004333 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4334 return false;
4335 return Scope.destroy();
Richard Smith4e18ca52013-05-06 05:56:11 +00004336}
4337
Richard Smith89210072016-04-04 23:29:43 +00004338namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004339/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004340/// statement should be stored.
4341struct StmtResult {
4342 /// The APValue that should be filled in with the returned value.
4343 APValue &Value;
4344 /// The location containing the result, if any (used to support RVO).
4345 const LValue *Slot;
4346};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004347
4348struct TempVersionRAII {
4349 CallStackFrame &Frame;
4350
4351 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4352 Frame.pushTempVersion();
4353 }
4354
4355 ~TempVersionRAII() {
4356 Frame.popTempVersion();
4357 }
4358};
4359
Richard Smith89210072016-04-04 23:29:43 +00004360}
Richard Smith52a980a2015-08-28 02:43:42 +00004361
4362static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004363 const Stmt *S,
4364 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004365
4366/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004367static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004368 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004369 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004370 BlockScopeRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004371
4372 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4373 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4374 ESR = ESR_Failed;
4375
4376 switch (ESR) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004377 case ESR_Break:
4378 return ESR_Succeeded;
4379 case ESR_Succeeded:
4380 case ESR_Continue:
4381 return ESR_Continue;
4382 case ESR_Failed:
4383 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004384 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004385 return ESR;
4386 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004387 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004388}
4389
Richard Smith496ddcf2013-05-12 17:32:42 +00004390/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004391static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004392 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004393 BlockScopeRAII Scope(Info);
4394
Richard Smith496ddcf2013-05-12 17:32:42 +00004395 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004396 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004397 {
Richard Smitha547eb22016-07-14 00:11:03 +00004398 if (const Stmt *Init = SS->getInit()) {
4399 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004400 if (ESR != ESR_Succeeded) {
4401 if (ESR != ESR_Failed && !Scope.destroy())
4402 ESR = ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004403 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004404 }
Richard Smitha547eb22016-07-14 00:11:03 +00004405 }
Richard Smith457226e2019-09-23 03:48:44 +00004406
4407 FullExpressionRAII CondScope(Info);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004408 if (SS->getConditionVariable() &&
4409 !EvaluateDecl(Info, SS->getConditionVariable()))
4410 return ESR_Failed;
4411 if (!EvaluateInteger(SS->getCond(), Value, Info))
4412 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004413 if (!CondScope.destroy())
4414 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004415 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004416
4417 // Find the switch case corresponding to the value of the condition.
4418 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004419 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004420 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4421 SC = SC->getNextSwitchCase()) {
4422 if (isa<DefaultStmt>(SC)) {
4423 Found = SC;
4424 continue;
4425 }
4426
4427 const CaseStmt *CS = cast<CaseStmt>(SC);
4428 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4429 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4430 : LHS;
4431 if (LHS <= Value && Value <= RHS) {
4432 Found = SC;
4433 break;
4434 }
4435 }
4436
4437 if (!Found)
Richard Smith457226e2019-09-23 03:48:44 +00004438 return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
Richard Smith496ddcf2013-05-12 17:32:42 +00004439
4440 // Search the switch body for the switch case and evaluate it from there.
Richard Smith457226e2019-09-23 03:48:44 +00004441 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4442 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4443 return ESR_Failed;
4444
4445 switch (ESR) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004446 case ESR_Break:
4447 return ESR_Succeeded;
4448 case ESR_Succeeded:
4449 case ESR_Continue:
4450 case ESR_Failed:
4451 case ESR_Returned:
4452 return ESR;
4453 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004454 // This can only happen if the switch case is nested within a statement
4455 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004456 Info.FFDiag(Found->getBeginLoc(),
4457 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004458 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004459 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004460 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004461}
4462
Richard Smith254a73d2011-10-28 22:34:42 +00004463// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004464static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004465 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004466 if (!Info.nextStep(S))
4467 return ESR_Failed;
4468
Richard Smith496ddcf2013-05-12 17:32:42 +00004469 // If we're hunting down a 'case' or 'default' label, recurse through
4470 // substatements until we hit the label.
4471 if (Case) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004472 switch (S->getStmtClass()) {
4473 case Stmt::CompoundStmtClass:
4474 // FIXME: Precompute which substatement of a compound statement we
4475 // would jump to, and go straight there rather than performing a
4476 // linear scan each time.
4477 case Stmt::LabelStmtClass:
4478 case Stmt::AttributedStmtClass:
4479 case Stmt::DoStmtClass:
4480 break;
4481
4482 case Stmt::CaseStmtClass:
4483 case Stmt::DefaultStmtClass:
4484 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004485 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004486 break;
4487
4488 case Stmt::IfStmtClass: {
4489 // FIXME: Precompute which side of an 'if' we would jump to, and go
4490 // straight there rather than scanning both sides.
4491 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004492
4493 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4494 // preceded by our switch label.
4495 BlockScopeRAII Scope(Info);
4496
Richard Smith397a6862019-09-20 23:08:59 +00004497 // Step into the init statement in case it brings an (uninitialized)
4498 // variable into scope.
4499 if (const Stmt *Init = IS->getInit()) {
4500 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4501 if (ESR != ESR_CaseNotFound) {
4502 assert(ESR != ESR_Succeeded);
4503 return ESR;
4504 }
4505 }
4506
4507 // Condition variable must be initialized if it exists.
4508 // FIXME: We can skip evaluating the body if there's a condition
4509 // variable, as there can't be any case labels within it.
4510 // (The same is true for 'for' statements.)
4511
Richard Smith496ddcf2013-05-12 17:32:42 +00004512 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
Richard Smith457226e2019-09-23 03:48:44 +00004513 if (ESR == ESR_Failed)
Richard Smith496ddcf2013-05-12 17:32:42 +00004514 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004515 if (ESR != ESR_CaseNotFound)
4516 return Scope.destroy() ? ESR : ESR_Failed;
4517 if (!IS->getElse())
4518 return ESR_CaseNotFound;
4519
4520 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4521 if (ESR == ESR_Failed)
4522 return ESR;
4523 if (ESR != ESR_CaseNotFound)
4524 return Scope.destroy() ? ESR : ESR_Failed;
4525 return ESR_CaseNotFound;
Richard Smith496ddcf2013-05-12 17:32:42 +00004526 }
4527
4528 case Stmt::WhileStmtClass: {
4529 EvalStmtResult ESR =
4530 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4531 if (ESR != ESR_Continue)
4532 return ESR;
4533 break;
4534 }
4535
4536 case Stmt::ForStmtClass: {
4537 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith397a6862019-09-20 23:08:59 +00004538 BlockScopeRAII Scope(Info);
4539
4540 // Step into the init statement in case it brings an (uninitialized)
4541 // variable into scope.
4542 if (const Stmt *Init = FS->getInit()) {
4543 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4544 if (ESR != ESR_CaseNotFound) {
4545 assert(ESR != ESR_Succeeded);
4546 return ESR;
4547 }
4548 }
4549
Richard Smith496ddcf2013-05-12 17:32:42 +00004550 EvalStmtResult ESR =
4551 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4552 if (ESR != ESR_Continue)
4553 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004554 if (FS->getInc()) {
4555 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004556 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004557 return ESR_Failed;
4558 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004559 break;
4560 }
4561
Richard Smithc667cdc2019-09-18 17:37:44 +00004562 case Stmt::DeclStmtClass: {
4563 // Start the lifetime of any uninitialized variables we encounter. They
4564 // might be used by the selected branch of the switch.
4565 const DeclStmt *DS = cast<DeclStmt>(S);
4566 for (const auto *D : DS->decls()) {
4567 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4568 if (VD->hasLocalStorage() && !VD->getInit())
4569 if (!EvaluateVarDecl(Info, VD))
4570 return ESR_Failed;
4571 // FIXME: If the variable has initialization that can't be jumped
4572 // over, bail out of any immediately-surrounding compound-statement
4573 // too. There can't be any case labels here.
4574 }
4575 }
4576 return ESR_CaseNotFound;
4577 }
4578
Richard Smith496ddcf2013-05-12 17:32:42 +00004579 default:
4580 return ESR_CaseNotFound;
4581 }
4582 }
4583
Richard Smith254a73d2011-10-28 22:34:42 +00004584 switch (S->getStmtClass()) {
4585 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004586 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004587 // Don't bother evaluating beyond an expression-statement which couldn't
4588 // be evaluated.
Richard Smith457226e2019-09-23 03:48:44 +00004589 // FIXME: Do we need the FullExpressionRAII object here?
4590 // VisitExprWithCleanups should create one when necessary.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004591 FullExpressionRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004592 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
Richard Smithd9f663b2013-04-22 15:31:51 +00004593 return ESR_Failed;
4594 return ESR_Succeeded;
4595 }
4596
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004597 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004598 return ESR_Failed;
4599
4600 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004601 return ESR_Succeeded;
4602
Richard Smithd9f663b2013-04-22 15:31:51 +00004603 case Stmt::DeclStmtClass: {
4604 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004605 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004606 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004607 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004608 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004609 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004610 if (!Scope.destroy())
4611 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004612 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004613 return ESR_Succeeded;
4614 }
4615
Richard Smith357362d2011-12-13 06:39:58 +00004616 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004617 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004618 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004619 if (RetExpr &&
4620 !(Result.Slot
4621 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4622 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004623 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004624 return Scope.destroy() ? ESR_Returned : ESR_Failed;
Richard Smith357362d2011-12-13 06:39:58 +00004625 }
Richard Smith254a73d2011-10-28 22:34:42 +00004626
4627 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004628 BlockScopeRAII Scope(Info);
4629
Richard Smith254a73d2011-10-28 22:34:42 +00004630 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004631 for (const auto *BI : CS->body()) {
4632 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004633 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004634 Case = nullptr;
Richard Smith457226e2019-09-23 03:48:44 +00004635 else if (ESR != ESR_CaseNotFound) {
4636 if (ESR != ESR_Failed && !Scope.destroy())
4637 return ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004638 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004639 }
Richard Smith254a73d2011-10-28 22:34:42 +00004640 }
Richard Smith457226e2019-09-23 03:48:44 +00004641 if (Case)
4642 return ESR_CaseNotFound;
4643 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004644 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004645
4646 case Stmt::IfStmtClass: {
4647 const IfStmt *IS = cast<IfStmt>(S);
4648
4649 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004650 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004651 if (const Stmt *Init = IS->getInit()) {
4652 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004653 if (ESR != ESR_Succeeded) {
4654 if (ESR != ESR_Failed && !Scope.destroy())
4655 return ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004656 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004657 }
Richard Smitha547eb22016-07-14 00:11:03 +00004658 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004659 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004660 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004661 return ESR_Failed;
4662
4663 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4664 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
Richard Smith457226e2019-09-23 03:48:44 +00004665 if (ESR != ESR_Succeeded) {
4666 if (ESR != ESR_Failed && !Scope.destroy())
4667 return ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004668 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004669 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004670 }
Richard Smith457226e2019-09-23 03:48:44 +00004671 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004672 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004673
4674 case Stmt::WhileStmtClass: {
4675 const WhileStmt *WS = cast<WhileStmt>(S);
4676 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004677 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004678 bool Continue;
4679 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4680 Continue))
4681 return ESR_Failed;
4682 if (!Continue)
4683 break;
4684
4685 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004686 if (ESR != ESR_Continue) {
4687 if (ESR != ESR_Failed && !Scope.destroy())
4688 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004689 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004690 }
4691 if (!Scope.destroy())
4692 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004693 }
4694 return ESR_Succeeded;
4695 }
4696
4697 case Stmt::DoStmtClass: {
4698 const DoStmt *DS = cast<DoStmt>(S);
4699 bool Continue;
4700 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004701 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004702 if (ESR != ESR_Continue)
4703 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004704 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004705
Richard Smith08d6a2c2013-07-24 07:11:57 +00004706 FullExpressionRAII CondScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004707 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4708 !CondScope.destroy())
Richard Smith4e18ca52013-05-06 05:56:11 +00004709 return ESR_Failed;
4710 } while (Continue);
4711 return ESR_Succeeded;
4712 }
4713
4714 case Stmt::ForStmtClass: {
4715 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith457226e2019-09-23 03:48:44 +00004716 BlockScopeRAII ForScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004717 if (FS->getInit()) {
4718 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004719 if (ESR != ESR_Succeeded) {
4720 if (ESR != ESR_Failed && !ForScope.destroy())
4721 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004722 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004723 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004724 }
4725 while (true) {
Richard Smith457226e2019-09-23 03:48:44 +00004726 BlockScopeRAII IterScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004727 bool Continue = true;
4728 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4729 FS->getCond(), Continue))
4730 return ESR_Failed;
4731 if (!Continue)
4732 break;
4733
4734 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004735 if (ESR != ESR_Continue) {
4736 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4737 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004738 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004739 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004740
Richard Smith08d6a2c2013-07-24 07:11:57 +00004741 if (FS->getInc()) {
4742 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004743 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004744 return ESR_Failed;
4745 }
Richard Smith457226e2019-09-23 03:48:44 +00004746
4747 if (!IterScope.destroy())
4748 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004749 }
Richard Smith457226e2019-09-23 03:48:44 +00004750 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004751 }
4752
Richard Smith896e0d72013-05-06 06:51:17 +00004753 case Stmt::CXXForRangeStmtClass: {
4754 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004755 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004756
Richard Smith8baa5002018-09-28 18:44:09 +00004757 // Evaluate the init-statement if present.
4758 if (FS->getInit()) {
4759 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004760 if (ESR != ESR_Succeeded) {
4761 if (ESR != ESR_Failed && !Scope.destroy())
4762 return ESR_Failed;
Richard Smith8baa5002018-09-28 18:44:09 +00004763 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004764 }
Richard Smith8baa5002018-09-28 18:44:09 +00004765 }
4766
Richard Smith896e0d72013-05-06 06:51:17 +00004767 // Initialize the __range variable.
4768 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004769 if (ESR != ESR_Succeeded) {
4770 if (ESR != ESR_Failed && !Scope.destroy())
4771 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004772 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004773 }
Richard Smith896e0d72013-05-06 06:51:17 +00004774
4775 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004776 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004777 if (ESR != ESR_Succeeded) {
4778 if (ESR != ESR_Failed && !Scope.destroy())
4779 return ESR_Failed;
Richard Smith01694c32016-03-20 10:33:40 +00004780 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004781 }
Richard Smith01694c32016-03-20 10:33:40 +00004782 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004783 if (ESR != ESR_Succeeded) {
4784 if (ESR != ESR_Failed && !Scope.destroy())
4785 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004786 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004787 }
Richard Smith896e0d72013-05-06 06:51:17 +00004788
4789 while (true) {
4790 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004791 {
4792 bool Continue = true;
4793 FullExpressionRAII CondExpr(Info);
4794 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4795 return ESR_Failed;
4796 if (!Continue)
4797 break;
4798 }
Richard Smith896e0d72013-05-06 06:51:17 +00004799
4800 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004801 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004802 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004803 if (ESR != ESR_Succeeded) {
4804 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4805 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004806 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004807 }
Richard Smith896e0d72013-05-06 06:51:17 +00004808
4809 // Loop body.
4810 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004811 if (ESR != ESR_Continue) {
4812 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4813 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004814 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004815 }
Richard Smith896e0d72013-05-06 06:51:17 +00004816
4817 // Increment: ++__begin
4818 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4819 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004820
4821 if (!InnerScope.destroy())
4822 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004823 }
4824
Richard Smith457226e2019-09-23 03:48:44 +00004825 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004826 }
4827
Richard Smith496ddcf2013-05-12 17:32:42 +00004828 case Stmt::SwitchStmtClass:
4829 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4830
Richard Smith4e18ca52013-05-06 05:56:11 +00004831 case Stmt::ContinueStmtClass:
4832 return ESR_Continue;
4833
4834 case Stmt::BreakStmtClass:
4835 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004836
4837 case Stmt::LabelStmtClass:
4838 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4839
4840 case Stmt::AttributedStmtClass:
4841 // As a general principle, C++11 attributes can be ignored without
4842 // any semantic impact.
4843 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4844 Case);
4845
4846 case Stmt::CaseStmtClass:
4847 case Stmt::DefaultStmtClass:
4848 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004849 case Stmt::CXXTryStmtClass:
4850 // Evaluate try blocks by evaluating all sub statements.
4851 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004852 }
4853}
4854
Richard Smithcc36f692011-12-22 02:22:31 +00004855/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4856/// default constructor. If so, we'll fold it whether or not it's marked as
4857/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4858/// so we need special handling.
4859static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004860 const CXXConstructorDecl *CD,
4861 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004862 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4863 return false;
4864
Richard Smith66e05fe2012-01-18 05:21:49 +00004865 // Value-initialization does not call a trivial default constructor, so such a
4866 // call is a core constant expression whether or not the constructor is
4867 // constexpr.
4868 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004869 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004870 // FIXME: If DiagDecl is an implicitly-declared special member function,
4871 // we should be much more explicit about why it's not constexpr.
4872 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4873 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4874 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004875 } else {
4876 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4877 }
4878 }
4879 return true;
4880}
4881
Richard Smith357362d2011-12-13 06:39:58 +00004882/// CheckConstexprFunction - Check that a function can be called in a constant
4883/// expression.
4884static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4885 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004886 const FunctionDecl *Definition,
4887 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004888 // Potential constant expressions can contain calls to declared, but not yet
4889 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004890 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004891 Declaration->isConstexpr())
4892 return false;
4893
James Y Knightc7d3e602018-10-05 17:49:48 +00004894 // Bail out if the function declaration itself is invalid. We will
4895 // have produced a relevant diagnostic while parsing it, so just
4896 // note the problematic sub-expression.
4897 if (Declaration->isInvalidDecl()) {
4898 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004899 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004900 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004901
Richard Smithd9c6b032019-05-09 19:45:49 +00004902 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004903 // constant expression (prior to C++20). We can still constant-fold such a
4904 // call.
4905 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4906 cast<CXXMethodDecl>(Declaration)->isVirtual())
4907 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4908
4909 if (Definition && Definition->isInvalidDecl()) {
4910 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004911 return false;
4912 }
4913
Richard Smith357362d2011-12-13 06:39:58 +00004914 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004915 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004916 return true;
4917
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004918 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004919 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004920
Richard Smith5179eb72016-06-28 19:03:57 +00004921 // If this function is not constexpr because it is an inherited
4922 // non-constexpr constructor, diagnose that directly.
4923 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4924 if (CD && CD->isInheritingConstructor()) {
4925 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004926 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004927 DiagDecl = CD = Inherited;
4928 }
4929
4930 // FIXME: If DiagDecl is an implicitly-declared special member function
4931 // or an inheriting constructor, we should be much more explicit about why
4932 // it's not constexpr.
4933 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004934 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004935 << CD->getInheritedConstructor().getConstructor()->getParent();
4936 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004937 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004938 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004939 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4940 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004941 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004942 }
4943 return false;
4944}
4945
Richard Smithdebad642019-05-12 09:39:08 +00004946namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004947struct CheckDynamicTypeHandler {
4948 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004949 typedef bool result_type;
4950 bool failed() { return false; }
4951 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4952 bool found(APSInt &Value, QualType SubobjType) { return true; }
4953 bool found(APFloat &Value, QualType SubobjType) { return true; }
4954};
4955} // end anonymous namespace
4956
Richard Smith7bd54ab2019-05-15 20:22:21 +00004957/// Check that we can access the notional vptr of an object / determine its
4958/// dynamic type.
4959static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4960 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004961 if (This.Designator.Invalid)
4962 return false;
4963
Richard Smith7bd54ab2019-05-15 20:22:21 +00004964 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004965
4966 if (!Obj)
4967 return false;
4968
4969 if (!Obj.Value) {
4970 // The object is not usable in constant expressions, so we can't inspect
4971 // its value to see if it's in-lifetime or what the active union members
4972 // are. We can still check for a one-past-the-end lvalue.
4973 if (This.Designator.isOnePastTheEnd() ||
4974 This.Designator.isMostDerivedAnUnsizedArray()) {
4975 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4976 ? diag::note_constexpr_access_past_end
4977 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004978 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004979 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004980 } else if (Polymorphic) {
4981 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004982 // not be able to read a notional 'vptr' value.
4983 APValue Val;
4984 This.moveInto(Val);
4985 QualType StarThisType =
4986 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004987 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4988 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004989 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004990 }
4991 return true;
4992 }
4993
Richard Smith7bd54ab2019-05-15 20:22:21 +00004994 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004995 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4996}
4997
Richard Smith7bd54ab2019-05-15 20:22:21 +00004998/// Check that the pointee of the 'this' pointer in a member function call is
4999/// either within its lifetime or in its period of construction or destruction.
Richard Smith61422f92019-09-27 20:24:36 +00005000static bool
5001checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5002 const LValue &This,
5003 const CXXMethodDecl *NamedMember) {
5004 return checkDynamicType(
5005 Info, E, This,
5006 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005007}
5008
Richard Smith921f1322019-05-13 23:35:21 +00005009struct DynamicType {
5010 /// The dynamic class type of the object.
5011 const CXXRecordDecl *Type;
5012 /// The corresponding path length in the lvalue.
5013 unsigned PathLength;
5014};
5015
5016static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5017 unsigned PathLength) {
5018 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5019 Designator.Entries.size() && "invalid path length");
5020 return (PathLength == Designator.MostDerivedPathLength)
5021 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5022 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5023}
5024
5025/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00005026static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5027 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00005028 // If we don't have an lvalue denoting an object of class type, there is no
5029 // meaningful dynamic type. (We consider objects of non-class type to have no
5030 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00005031 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00005032 return None;
5033
Richard Smith7bd54ab2019-05-15 20:22:21 +00005034 // Refuse to compute a dynamic type in the presence of virtual bases. This
5035 // shouldn't happen other than in constant-folding situations, since literal
5036 // types can't have virtual bases.
5037 //
5038 // Note that consumers of DynamicType assume that the type has no virtual
5039 // bases, and will need modifications if this restriction is relaxed.
5040 const CXXRecordDecl *Class =
5041 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5042 if (!Class || Class->getNumVBases()) {
5043 Info.FFDiag(E);
5044 return None;
5045 }
5046
Richard Smith921f1322019-05-13 23:35:21 +00005047 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5048 // binary search here instead. But the overwhelmingly common case is that
5049 // we're not in the middle of a constructor, so it probably doesn't matter
5050 // in practice.
5051 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5052 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5053 PathLength <= Path.size(); ++PathLength) {
Richard Smith457226e2019-09-23 03:48:44 +00005054 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5055 Path.slice(0, PathLength))) {
Richard Smith921f1322019-05-13 23:35:21 +00005056 case ConstructionPhase::Bases:
Richard Smith457226e2019-09-23 03:48:44 +00005057 case ConstructionPhase::DestroyingBases:
5058 // We're constructing or destroying a base class. This is not the dynamic
5059 // type.
Richard Smith921f1322019-05-13 23:35:21 +00005060 break;
5061
5062 case ConstructionPhase::None:
5063 case ConstructionPhase::AfterBases:
Richard Smith457226e2019-09-23 03:48:44 +00005064 case ConstructionPhase::Destroying:
5065 // We've finished constructing the base classes and not yet started
5066 // destroying them again, so this is the dynamic type.
Richard Smith921f1322019-05-13 23:35:21 +00005067 return DynamicType{getBaseClassType(This.Designator, PathLength),
5068 PathLength};
5069 }
5070 }
5071
5072 // CWG issue 1517: we're constructing a base class of the object described by
5073 // 'This', so that object has not yet begun its period of construction and
5074 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00005075 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00005076 return None;
5077}
5078
5079/// Perform virtual dispatch.
5080static const CXXMethodDecl *HandleVirtualDispatch(
5081 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5082 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith61422f92019-09-27 20:24:36 +00005083 Optional<DynamicType> DynType = ComputeDynamicType(
5084 Info, E, This,
5085 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005086 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00005087 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00005088
5089 // Find the final overrider. It must be declared in one of the classes on the
5090 // path from the dynamic type to the static type.
5091 // FIXME: If we ever allow literal types to have virtual base classes, that
5092 // won't be true.
5093 const CXXMethodDecl *Callee = Found;
5094 unsigned PathLength = DynType->PathLength;
5095 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5096 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00005097 const CXXMethodDecl *Overrider =
5098 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5099 if (Overrider) {
5100 Callee = Overrider;
5101 break;
5102 }
5103 }
5104
5105 // C++2a [class.abstract]p6:
5106 // the effect of making a virtual call to a pure virtual function [...] is
5107 // undefined
5108 if (Callee->isPure()) {
5109 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5110 Info.Note(Callee->getLocation(), diag::note_declared_at);
5111 return nullptr;
5112 }
5113
5114 // If necessary, walk the rest of the path to determine the sequence of
5115 // covariant adjustment steps to apply.
5116 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5117 Found->getReturnType())) {
5118 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5119 for (unsigned CovariantPathLength = PathLength + 1;
5120 CovariantPathLength != This.Designator.Entries.size();
5121 ++CovariantPathLength) {
5122 const CXXRecordDecl *NextClass =
5123 getBaseClassType(This.Designator, CovariantPathLength);
5124 const CXXMethodDecl *Next =
5125 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5126 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5127 Next->getReturnType(), CovariantAdjustmentPath.back()))
5128 CovariantAdjustmentPath.push_back(Next->getReturnType());
5129 }
5130 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5131 CovariantAdjustmentPath.back()))
5132 CovariantAdjustmentPath.push_back(Found->getReturnType());
5133 }
5134
5135 // Perform 'this' adjustment.
5136 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5137 return nullptr;
5138
5139 return Callee;
5140}
5141
5142/// Perform the adjustment from a value returned by a virtual function to
5143/// a value of the statically expected type, which may be a pointer or
5144/// reference to a base class of the returned type.
5145static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5146 APValue &Result,
5147 ArrayRef<QualType> Path) {
5148 assert(Result.isLValue() &&
5149 "unexpected kind of APValue for covariant return");
5150 if (Result.isNullPointer())
5151 return true;
5152
5153 LValue LVal;
5154 LVal.setFrom(Info.Ctx, Result);
5155
5156 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5157 for (unsigned I = 1; I != Path.size(); ++I) {
5158 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5159 assert(OldClass && NewClass && "unexpected kind of covariant return");
5160 if (OldClass != NewClass &&
5161 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5162 return false;
5163 OldClass = NewClass;
5164 }
5165
5166 LVal.moveInto(Result);
5167 return true;
5168}
5169
Richard Smith7bd54ab2019-05-15 20:22:21 +00005170/// Determine whether \p Base, which is known to be a direct base class of
5171/// \p Derived, is a public base class.
5172static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5173 const CXXRecordDecl *Base) {
5174 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5175 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5176 if (BaseClass && declaresSameEntity(BaseClass, Base))
5177 return BaseSpec.getAccessSpecifier() == AS_public;
5178 }
5179 llvm_unreachable("Base is not a direct base of Derived");
5180}
5181
5182/// Apply the given dynamic cast operation on the provided lvalue.
5183///
5184/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5185/// to find a suitable target subobject.
5186static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5187 LValue &Ptr) {
5188 // We can't do anything with a non-symbolic pointer value.
5189 SubobjectDesignator &D = Ptr.Designator;
5190 if (D.Invalid)
5191 return false;
5192
5193 // C++ [expr.dynamic.cast]p6:
5194 // If v is a null pointer value, the result is a null pointer value.
5195 if (Ptr.isNullPointer() && !E->isGLValue())
5196 return true;
5197
5198 // For all the other cases, we need the pointer to point to an object within
5199 // its lifetime / period of construction / destruction, and we need to know
5200 // its dynamic type.
5201 Optional<DynamicType> DynType =
5202 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5203 if (!DynType)
5204 return false;
5205
5206 // C++ [expr.dynamic.cast]p7:
5207 // If T is "pointer to cv void", then the result is a pointer to the most
5208 // derived object
5209 if (E->getType()->isVoidPointerType())
5210 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5211
5212 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5213 assert(C && "dynamic_cast target is not void pointer nor class");
5214 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5215
5216 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5217 // C++ [expr.dynamic.cast]p9:
5218 if (!E->isGLValue()) {
5219 // The value of a failed cast to pointer type is the null pointer value
5220 // of the required result type.
Richard Smith19ad5232019-10-03 00:39:33 +00005221 Ptr.setNull(Info.Ctx, E->getType());
Richard Smith7bd54ab2019-05-15 20:22:21 +00005222 return true;
5223 }
5224
5225 // A failed cast to reference type throws [...] std::bad_cast.
5226 unsigned DiagKind;
5227 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5228 DynType->Type->isDerivedFrom(C)))
5229 DiagKind = 0;
5230 else if (!Paths || Paths->begin() == Paths->end())
5231 DiagKind = 1;
5232 else if (Paths->isAmbiguous(CQT))
5233 DiagKind = 2;
5234 else {
5235 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5236 DiagKind = 3;
5237 }
5238 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5239 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5240 << Info.Ctx.getRecordType(DynType->Type)
5241 << E->getType().getUnqualifiedType();
5242 return false;
5243 };
5244
5245 // Runtime check, phase 1:
5246 // Walk from the base subobject towards the derived object looking for the
5247 // target type.
5248 for (int PathLength = Ptr.Designator.Entries.size();
5249 PathLength >= (int)DynType->PathLength; --PathLength) {
5250 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5251 if (declaresSameEntity(Class, C))
5252 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5253 // We can only walk across public inheritance edges.
5254 if (PathLength > (int)DynType->PathLength &&
5255 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5256 Class))
5257 return RuntimeCheckFailed(nullptr);
5258 }
5259
5260 // Runtime check, phase 2:
5261 // Search the dynamic type for an unambiguous public base of type C.
5262 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5263 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5264 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5265 Paths.front().Access == AS_public) {
5266 // Downcast to the dynamic type...
5267 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5268 return false;
5269 // ... then upcast to the chosen base class subobject.
5270 for (CXXBasePathElement &Elem : Paths.front())
5271 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5272 return false;
5273 return true;
5274 }
5275
5276 // Otherwise, the runtime check fails.
5277 return RuntimeCheckFailed(&Paths);
5278}
5279
Richard Smith31c69a32019-05-21 23:15:20 +00005280namespace {
5281struct StartLifetimeOfUnionMemberHandler {
5282 const FieldDecl *Field;
5283
5284 static const AccessKinds AccessKind = AK_Assign;
5285
Richard Smith31c69a32019-05-21 23:15:20 +00005286 typedef bool result_type;
5287 bool failed() { return false; }
5288 bool found(APValue &Subobj, QualType SubobjType) {
5289 // We are supposed to perform no initialization but begin the lifetime of
5290 // the object. We interpret that as meaning to do what default
5291 // initialization of the object would do if all constructors involved were
5292 // trivial:
5293 // * All base, non-variant member, and array element subobjects' lifetimes
5294 // begin
5295 // * No variant members' lifetimes begin
5296 // * All scalar subobjects whose lifetimes begin have indeterminate values
5297 assert(SubobjType->isUnionType());
Richard Smith61422f92019-09-27 20:24:36 +00005298 if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5299 !Subobj.getUnionValue().hasValue())
Richard Smith31c69a32019-05-21 23:15:20 +00005300 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5301 return true;
5302 }
5303 bool found(APSInt &Value, QualType SubobjType) {
5304 llvm_unreachable("wrong value kind for union object");
5305 }
5306 bool found(APFloat &Value, QualType SubobjType) {
5307 llvm_unreachable("wrong value kind for union object");
5308 }
5309};
5310} // end anonymous namespace
5311
5312const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5313
5314/// Handle a builtin simple-assignment or a call to a trivial assignment
5315/// operator whose left-hand side might involve a union member access. If it
5316/// does, implicitly start the lifetime of any accessed union elements per
5317/// C++20 [class.union]5.
5318static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5319 const LValue &LHS) {
5320 if (LHS.InvalidBase || LHS.Designator.Invalid)
5321 return false;
5322
5323 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5324 // C++ [class.union]p5:
5325 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00005326 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005327 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005328 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5329 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5330 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
Richard Smith9a84dc02019-10-01 00:07:14 +00005331 // Note that we can't implicitly start the lifetime of a reference,
5332 // so we don't need to proceed any further if we reach one.
5333 if (!FD || FD->getType()->isReferenceType())
Richard Smith31c69a32019-05-21 23:15:20 +00005334 break;
5335
5336 // ... and also contains A.B if B names a union member
5337 if (FD->getParent()->isUnion())
5338 UnionPathLengths.push_back({PathLength - 1, FD});
5339
5340 E = ME->getBase();
5341 --PathLength;
5342 assert(declaresSameEntity(FD,
5343 LHS.Designator.Entries[PathLength]
5344 .getAsBaseOrMember().getPointer()));
5345
5346 // -- If E is of the form A[B] and is interpreted as a built-in array
5347 // subscripting operator, S(E) is [S(the array operand, if any)].
5348 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5349 // Step over an ArrayToPointerDecay implicit cast.
5350 auto *Base = ASE->getBase()->IgnoreImplicit();
5351 if (!Base->getType()->isArrayType())
5352 break;
5353
5354 E = Base;
5355 --PathLength;
5356
5357 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5358 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005359 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005360 if (ICE->getCastKind() == CK_NoOp)
5361 continue;
5362 if (ICE->getCastKind() != CK_DerivedToBase &&
5363 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5364 break;
Richard Smitha481b012019-05-30 20:45:12 +00005365 // Walk path backwards as we walk up from the base to the derived class.
5366 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005367 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005368 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005369 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5370 LHS.Designator.Entries[PathLength]
5371 .getAsBaseOrMember().getPointer()));
5372 }
Richard Smith31c69a32019-05-21 23:15:20 +00005373
5374 // -- Otherwise, S(E) is empty.
5375 } else {
5376 break;
5377 }
5378 }
5379
5380 // Common case: no unions' lifetimes are started.
5381 if (UnionPathLengths.empty())
5382 return true;
5383
5384 // if modification of X [would access an inactive union member], an object
5385 // of the type of X is implicitly created
5386 CompleteObject Obj =
5387 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5388 if (!Obj)
5389 return false;
5390 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5391 llvm::reverse(UnionPathLengths)) {
5392 // Form a designator for the union object.
5393 SubobjectDesignator D = LHS.Designator;
5394 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5395
5396 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5397 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5398 return false;
5399 }
5400
5401 return true;
5402}
5403
Richard Smithbe6dd812014-11-19 21:27:17 +00005404/// Determine if a class has any fields that might need to be copied by a
5405/// trivial copy or move operation.
5406static bool hasFields(const CXXRecordDecl *RD) {
5407 if (!RD || RD->isEmpty())
5408 return false;
5409 for (auto *FD : RD->fields()) {
5410 if (FD->isUnnamedBitfield())
5411 continue;
5412 return true;
5413 }
5414 for (auto &Base : RD->bases())
5415 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5416 return true;
5417 return false;
5418}
5419
Richard Smithd62306a2011-11-10 06:34:14 +00005420namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005421typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005422}
5423
5424/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005425static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5426 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005427 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005428 llvm::SmallBitVector ForbiddenNullArgs;
5429 if (Callee->hasAttr<NonNullAttr>()) {
5430 ForbiddenNullArgs.resize(Args.size());
5431 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5432 if (!Attr->args_size()) {
5433 ForbiddenNullArgs.set();
5434 break;
5435 } else
5436 for (auto Idx : Attr->args()) {
5437 unsigned ASTIdx = Idx.getASTIndex();
5438 if (ASTIdx >= Args.size())
5439 continue;
5440 ForbiddenNullArgs[ASTIdx] = 1;
5441 }
5442 }
5443 }
Richard Smithd62306a2011-11-10 06:34:14 +00005444 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005445 I != E; ++I) {
5446 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5447 // If we're checking for a potential constant expression, evaluate all
5448 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005449 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005450 return false;
5451 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005452 } else if (!ForbiddenNullArgs.empty() &&
5453 ForbiddenNullArgs[I - Args.begin()] &&
5454 ArgValues[I - Args.begin()].isNullPointer()) {
5455 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5456 if (!Info.noteFailure())
5457 return false;
5458 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005459 }
5460 }
5461 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005462}
5463
Richard Smith254a73d2011-10-28 22:34:42 +00005464/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005465static bool HandleFunctionCall(SourceLocation CallLoc,
5466 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005467 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005468 EvalInfo &Info, APValue &Result,
5469 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005470 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005471 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005472 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005473
Richard Smith253c2a32012-01-27 01:14:48 +00005474 if (!Info.CheckCallLimit(CallLoc))
5475 return false;
5476
5477 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005478
5479 // For a trivial copy or move assignment, perform an APValue copy. This is
5480 // essential for unions, where the operations performed by the assignment
5481 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005482 //
5483 // Skip this for non-union classes with no fields; in that case, the defaulted
5484 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005485 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005486 if (MD && MD->isDefaulted() &&
5487 (MD->getParent()->isUnion() ||
5488 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005489 assert(This &&
5490 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5491 LValue RHS;
5492 RHS.setFrom(Info.Ctx, ArgValues[0]);
5493 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005494 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5495 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005496 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005497 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5498 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5499 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005500 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005501 RHSValue))
5502 return false;
5503 This->moveInto(Result);
5504 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005505 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005506 // We're in a lambda; determine the lambda capture field maps unless we're
5507 // just constexpr checking a lambda's call operator. constexpr checking is
5508 // done before the captures have been added to the closure object (unless
5509 // we're inferring constexpr-ness), so we don't have access to them in this
5510 // case. But since we don't need the captures to constexpr check, we can
5511 // just ignore them.
5512 if (!Info.checkingPotentialConstantExpression())
5513 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5514 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005515 }
5516
Richard Smith52a980a2015-08-28 02:43:42 +00005517 StmtResult Ret = {Result, ResultSlot};
5518 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005519 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005520 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005521 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005522 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005523 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005524 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005525}
5526
Richard Smithd62306a2011-11-10 06:34:14 +00005527/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005528static bool HandleConstructorCall(const Expr *E, const LValue &This,
5529 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005530 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005531 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005532 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005533 if (!Info.CheckCallLimit(CallLoc))
5534 return false;
5535
Richard Smith3607ffe2012-02-13 03:54:03 +00005536 const CXXRecordDecl *RD = Definition->getParent();
5537 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005538 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005539 return false;
5540 }
5541
Erik Pilkington42925492017-10-04 00:18:55 +00005542 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005543 Info,
5544 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5545 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005546 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005547
Richard Smith52a980a2015-08-28 02:43:42 +00005548 // FIXME: Creating an APValue just to hold a nonexistent return value is
5549 // wasteful.
5550 APValue RetVal;
5551 StmtResult Ret = {RetVal, nullptr};
5552
Richard Smith5179eb72016-06-28 19:03:57 +00005553 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005554 if (Definition->isDelegatingConstructor()) {
5555 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005556 {
5557 FullExpressionRAII InitScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00005558 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5559 !InitScope.destroy())
Richard Smith9ff62af2013-11-07 18:45:03 +00005560 return false;
5561 }
Richard Smith52a980a2015-08-28 02:43:42 +00005562 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005563 }
5564
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005565 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005566 // essential for unions (or classes with anonymous union members), where the
5567 // operations performed by the constructor cannot be represented by
5568 // ctor-initializers.
5569 //
5570 // Skip this for empty non-union classes; we should not perform an
5571 // lvalue-to-rvalue conversion on them because their copy constructor does not
5572 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005573 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005574 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005575 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005576 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005577 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005578 return handleLValueToRValueConversion(
5579 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005580 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005581 }
5582
5583 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005584 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005585 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005586 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005587
John McCalld7bca762012-05-01 00:38:49 +00005588 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005589 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5590
Richard Smith08d6a2c2013-07-24 07:11:57 +00005591 // A scope for temporaries lifetime-extended by reference members.
5592 BlockScopeRAII LifetimeExtendedScope(Info);
5593
Richard Smith253c2a32012-01-27 01:14:48 +00005594 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005595 unsigned BasesSeen = 0;
5596#ifndef NDEBUG
5597 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5598#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005599 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5600 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5601 // We might be initializing the same field again if this is an indirect
5602 // field initialization.
5603 if (FieldIt == RD->field_end() ||
5604 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5605 assert(Indirect && "fields out of order?");
5606 return;
5607 }
5608
5609 // Default-initialize any fields with no explicit initializer.
5610 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5611 assert(FieldIt != RD->field_end() && "missing field?");
5612 if (!FieldIt->isUnnamedBitfield())
5613 Result.getStructField(FieldIt->getFieldIndex()) =
5614 getDefaultInitValue(FieldIt->getType());
5615 }
5616 ++FieldIt;
5617 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005618 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005619 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005620 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005621 APValue *Value = &Result;
5622
5623 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005624 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005625 if (I->isBaseInitializer()) {
5626 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005627#ifndef NDEBUG
5628 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005629 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005630 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5631 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5632 "base class initializers not in expected order");
5633 ++BaseIt;
5634#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005635 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005636 BaseType->getAsCXXRecordDecl(), &Layout))
5637 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005638 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005639 } else if ((FD = I->getMember())) {
5640 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005641 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005642 if (RD->isUnion()) {
5643 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005644 Value = &Result.getUnionValue();
5645 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005646 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005647 Value = &Result.getStructField(FD->getFieldIndex());
5648 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005649 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005650 // Walk the indirect field decl's chain to find the object to initialize,
5651 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005652 auto IndirectFieldChain = IFD->chain();
5653 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005654 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005655 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5656 // Switch the union field if it differs. This happens if we had
5657 // preceding zero-initialization, and we're now initializing a union
5658 // subobject other than the first.
5659 // FIXME: In this case, the values of the other subobjects are
5660 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005661 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005662 (Value->isUnion() && Value->getUnionField() != FD)) {
5663 if (CD->isUnion())
5664 *Value = APValue(FD);
5665 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005666 // FIXME: This immediately starts the lifetime of all members of an
5667 // anonymous struct. It would be preferable to strictly start member
5668 // lifetime in initialization order.
5669 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005670 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005671 // Store Subobject as its parent before updating it for the last element
5672 // in the chain.
5673 if (C == IndirectFieldChain.back())
5674 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005675 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005676 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005677 if (CD->isUnion())
5678 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005679 else {
5680 if (C == IndirectFieldChain.front() && !RD->isUnion())
5681 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005682 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005683 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005684 }
Richard Smithd62306a2011-11-10 06:34:14 +00005685 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005686 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005687 }
Richard Smith253c2a32012-01-27 01:14:48 +00005688
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005689 // Need to override This for implicit field initializers as in this case
5690 // This refers to innermost anonymous struct/union containing initializer,
5691 // not to currently constructed class.
5692 const Expr *Init = I->getInit();
5693 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5694 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005695 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005696 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5697 (FD && FD->isBitField() &&
5698 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005699 // If we're checking for a potential constant expression, evaluate all
5700 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005701 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005702 return false;
5703 Success = false;
5704 }
Richard Smith921f1322019-05-13 23:35:21 +00005705
5706 // This is the point at which the dynamic type of the object becomes this
5707 // class type.
5708 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5709 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005710 }
5711
Richard Smithc667cdc2019-09-18 17:37:44 +00005712 // Default-initialize any remaining fields.
5713 if (!RD->isUnion()) {
5714 for (; FieldIt != RD->field_end(); ++FieldIt) {
5715 if (!FieldIt->isUnnamedBitfield())
5716 Result.getStructField(FieldIt->getFieldIndex()) =
5717 getDefaultInitValue(FieldIt->getType());
5718 }
5719 }
5720
Richard Smithd9f663b2013-04-22 15:31:51 +00005721 return Success &&
Richard Smith457226e2019-09-23 03:48:44 +00005722 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5723 LifetimeExtendedScope.destroy();
Richard Smithd62306a2011-11-10 06:34:14 +00005724}
5725
Richard Smith5179eb72016-06-28 19:03:57 +00005726static bool HandleConstructorCall(const Expr *E, const LValue &This,
5727 ArrayRef<const Expr*> Args,
5728 const CXXConstructorDecl *Definition,
5729 EvalInfo &Info, APValue &Result) {
5730 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005731 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005732 return false;
5733
5734 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5735 Info, Result);
5736}
5737
Richard Smith61422f92019-09-27 20:24:36 +00005738static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5739 const LValue &This, APValue &Value,
5740 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005741 // Objects can only be destroyed while they're within their lifetimes.
5742 // FIXME: We have no representation for whether an object of type nullptr_t
5743 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5744 // as indeterminate instead?
5745 if (Value.isAbsent() && !T->isNullPtrType()) {
5746 APValue Printable;
5747 This.moveInto(Printable);
5748 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5749 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5750 return false;
5751 }
5752
Richard Smith457226e2019-09-23 03:48:44 +00005753 // Invent an expression for location purposes.
5754 // FIXME: We shouldn't need to do this.
5755 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5756
5757 // For arrays, destroy elements right-to-left.
5758 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5759 uint64_t Size = CAT->getSize().getZExtValue();
5760 QualType ElemT = CAT->getElementType();
5761
5762 LValue ElemLV = This;
5763 ElemLV.addArray(Info, &LocE, CAT);
5764 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5765 return false;
5766
Richard Smithda1b4342019-09-27 01:26:47 +00005767 // Ensure that we have actual array elements available to destroy; the
5768 // destructors might mutate the value, so we can't run them on the array
5769 // filler.
5770 if (Size && Size > Value.getArrayInitializedElts())
5771 expandArray(Value, Value.getArraySize() - 1);
5772
Richard Smith457226e2019-09-23 03:48:44 +00005773 for (; Size != 0; --Size) {
5774 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
Richard Smithda1b4342019-09-27 01:26:47 +00005775 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
Richard Smith61422f92019-09-27 20:24:36 +00005776 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
Richard Smith457226e2019-09-23 03:48:44 +00005777 return false;
5778 }
5779
5780 // End the lifetime of this array now.
5781 Value = APValue();
5782 return true;
5783 }
5784
5785 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5786 if (!RD) {
5787 if (T.isDestructedType()) {
5788 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5789 return false;
5790 }
5791
5792 Value = APValue();
5793 return true;
5794 }
5795
5796 if (RD->getNumVBases()) {
5797 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5798 return false;
5799 }
5800
5801 const CXXDestructorDecl *DD = RD->getDestructor();
Richard Smithda1b4342019-09-27 01:26:47 +00005802 if (!DD && !RD->hasTrivialDestructor()) {
Richard Smith457226e2019-09-23 03:48:44 +00005803 Info.FFDiag(CallLoc);
5804 return false;
5805 }
5806
Richard Smithda1b4342019-09-27 01:26:47 +00005807 if (!DD || DD->isTrivial() ||
Richard Smith457226e2019-09-23 03:48:44 +00005808 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5809 // A trivial destructor just ends the lifetime of the object. Check for
5810 // this case before checking for a body, because we might not bother
5811 // building a body for a trivial destructor. Note that it doesn't matter
5812 // whether the destructor is constexpr in this case; all trivial
5813 // destructors are constexpr.
5814 //
5815 // If an anonymous union would be destroyed, some enclosing destructor must
5816 // have been explicitly defined, and the anonymous union destruction should
5817 // have no effect.
5818 Value = APValue();
5819 return true;
5820 }
5821
5822 if (!Info.CheckCallLimit(CallLoc))
5823 return false;
5824
Richard Smithda1b4342019-09-27 01:26:47 +00005825 const FunctionDecl *Definition = nullptr;
5826 const Stmt *Body = DD->getBody(Definition);
5827
Richard Smith457226e2019-09-23 03:48:44 +00005828 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5829 return false;
5830
5831 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5832
5833 // We're now in the period of destruction of this object.
5834 unsigned BasesLeft = RD->getNumBases();
5835 EvalInfo::EvaluatingDestructorRAII EvalObj(
5836 Info,
5837 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
Richard Smithda1b4342019-09-27 01:26:47 +00005838 if (!EvalObj.DidInsert) {
5839 // C++2a [class.dtor]p19:
5840 // the behavior is undefined if the destructor is invoked for an object
5841 // whose lifetime has ended
5842 // (Note that formally the lifetime ends when the period of destruction
5843 // begins, even though certain uses of the object remain valid until the
5844 // period of destruction ends.)
5845 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5846 return false;
5847 }
Richard Smith457226e2019-09-23 03:48:44 +00005848
5849 // FIXME: Creating an APValue just to hold a nonexistent return value is
5850 // wasteful.
5851 APValue RetVal;
5852 StmtResult Ret = {RetVal, nullptr};
5853 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5854 return false;
5855
5856 // A union destructor does not implicitly destroy its members.
5857 if (RD->isUnion())
5858 return true;
5859
5860 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5861
5862 // We don't have a good way to iterate fields in reverse, so collect all the
5863 // fields first and then walk them backwards.
5864 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5865 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5866 if (FD->isUnnamedBitfield())
5867 continue;
5868
5869 LValue Subobject = This;
5870 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5871 return false;
5872
5873 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
Richard Smith61422f92019-09-27 20:24:36 +00005874 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5875 FD->getType()))
Richard Smith457226e2019-09-23 03:48:44 +00005876 return false;
5877 }
5878
5879 if (BasesLeft != 0)
5880 EvalObj.startedDestroyingBases();
5881
5882 // Destroy base classes in reverse order.
5883 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5884 --BasesLeft;
5885
5886 QualType BaseType = Base.getType();
5887 LValue Subobject = This;
5888 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5889 BaseType->getAsCXXRecordDecl(), &Layout))
5890 return false;
5891
5892 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
Richard Smith61422f92019-09-27 20:24:36 +00005893 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5894 BaseType))
Richard Smith457226e2019-09-23 03:48:44 +00005895 return false;
5896 }
5897 assert(BasesLeft == 0 && "NumBases was wrong?");
5898
5899 // The period of destruction ends now. The object is gone.
5900 Value = APValue();
5901 return true;
5902}
5903
Richard Smith61422f92019-09-27 20:24:36 +00005904namespace {
5905struct DestroyObjectHandler {
5906 EvalInfo &Info;
5907 const Expr *E;
5908 const LValue &This;
5909 const AccessKinds AccessKind;
5910
5911 typedef bool result_type;
5912 bool failed() { return false; }
5913 bool found(APValue &Subobj, QualType SubobjType) {
5914 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5915 SubobjType);
5916 }
5917 bool found(APSInt &Value, QualType SubobjType) {
5918 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5919 return false;
5920 }
5921 bool found(APFloat &Value, QualType SubobjType) {
5922 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5923 return false;
5924 }
5925};
5926}
5927
5928/// Perform a destructor or pseudo-destructor call on the given object, which
5929/// might in general not be a complete object.
5930static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5931 const LValue &This, QualType ThisType) {
5932 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5933 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5934 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5935}
5936
5937/// Destroy and end the lifetime of the given complete object.
5938static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5939 APValue::LValueBase LVBase, APValue &Value,
5940 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005941 // If we've had an unmodeled side-effect, we can't rely on mutable state
5942 // (such as the object we're about to destroy) being correct.
5943 if (Info.EvalStatus.HasSideEffects)
5944 return false;
Richard Smith457226e2019-09-23 03:48:44 +00005945
5946 LValue LV;
5947 LV.set({LVBase});
Richard Smith61422f92019-09-27 20:24:36 +00005948 return HandleDestructionImpl(Info, Loc, LV, Value, T);
Richard Smith457226e2019-09-23 03:48:44 +00005949}
5950
Richard Smith19ad5232019-10-03 00:39:33 +00005951/// Perform a call to 'perator new' or to `__builtin_operator_new'.
5952static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
5953 LValue &Result) {
5954 if (Info.checkingPotentialConstantExpression() ||
5955 Info.SpeculativeEvaluationDepth)
5956 return false;
5957
5958 // This is permitted only within a call to std::allocator<T>::allocate.
5959 auto Caller = Info.getStdAllocatorCaller("allocate");
5960 if (!Caller) {
5961 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
5962 ? diag::note_constexpr_new_untyped
5963 : diag::note_constexpr_new);
5964 return false;
5965 }
5966
5967 QualType ElemType = Caller.ElemType;
5968 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
5969 Info.FFDiag(E->getExprLoc(),
5970 diag::note_constexpr_new_not_complete_object_type)
5971 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
5972 return false;
5973 }
5974
5975 APSInt ByteSize;
5976 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
5977 return false;
5978 bool IsNothrow = false;
5979 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
5980 EvaluateIgnoredValue(Info, E->getArg(I));
5981 IsNothrow |= E->getType()->isNothrowT();
5982 }
5983
5984 CharUnits ElemSize;
5985 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
5986 return false;
5987 APInt Size, Remainder;
5988 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
5989 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
5990 if (Remainder != 0) {
5991 // This likely indicates a bug in the implementation of 'std::allocator'.
5992 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
5993 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
5994 return false;
5995 }
5996
5997 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
5998 if (IsNothrow) {
5999 Result.setNull(Info.Ctx, E->getType());
6000 return true;
6001 }
6002
6003 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6004 return false;
6005 }
6006
Richard Smith772e2662019-10-04 01:25:59 +00006007 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6008 ArrayType::Normal, 0);
Richard Smith19ad5232019-10-03 00:39:33 +00006009 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6010 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6011 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6012 return true;
6013}
6014
6015static bool hasVirtualDestructor(QualType T) {
6016 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6017 if (CXXDestructorDecl *DD = RD->getDestructor())
6018 return DD->isVirtual();
6019 return false;
6020}
6021
6022/// Check that the given object is a suitable pointer to a heap allocation that
6023/// still exists and is of the right kind for the purpose of a deletion.
6024///
6025/// On success, returns the heap allocation to deallocate. On failure, produces
6026/// a diagnostic and returns None.
6027static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6028 const LValue &Pointer,
6029 DynAlloc::Kind DeallocKind) {
6030 auto PointerAsString = [&] {
6031 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6032 };
6033
6034 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6035 if (!DA) {
6036 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6037 << PointerAsString();
6038 if (Pointer.Base)
6039 NoteLValueLocation(Info, Pointer.Base);
6040 return None;
6041 }
6042
6043 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6044 if (!Alloc) {
6045 Info.FFDiag(E, diag::note_constexpr_double_delete);
6046 return None;
6047 }
6048
6049 QualType AllocType = Pointer.Base.getDynamicAllocType();
6050 if (DeallocKind != (*Alloc)->getKind()) {
6051 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6052 << DeallocKind << (*Alloc)->getKind() << AllocType;
6053 NoteLValueLocation(Info, Pointer.Base);
6054 return None;
6055 }
6056
6057 bool Subobject = false;
6058 if (DeallocKind == DynAlloc::New) {
6059 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6060 Pointer.Designator.isOnePastTheEnd();
6061 } else {
6062 Subobject = Pointer.Designator.Entries.size() != 1 ||
6063 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6064 }
6065 if (Subobject) {
6066 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6067 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6068 return None;
6069 }
6070
6071 return Alloc;
6072}
6073
6074// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6075bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6076 if (Info.checkingPotentialConstantExpression() ||
6077 Info.SpeculativeEvaluationDepth)
6078 return false;
6079
6080 // This is permitted only within a call to std::allocator<T>::deallocate.
6081 if (!Info.getStdAllocatorCaller("deallocate")) {
6082 Info.FFDiag(E->getExprLoc());
6083 return true;
6084 }
6085
6086 LValue Pointer;
6087 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6088 return false;
6089 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6090 EvaluateIgnoredValue(Info, E->getArg(I));
6091
6092 if (Pointer.Designator.Invalid)
6093 return false;
6094
6095 // Deleting a null pointer has no effect.
6096 if (Pointer.isNullPointer())
6097 return true;
6098
6099 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6100 return false;
6101
6102 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6103 return true;
6104}
6105
Eli Friedman9a156e52008-11-12 09:44:48 +00006106//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00006107// Generic Evaluation
6108//===----------------------------------------------------------------------===//
6109namespace {
6110
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006111class BitCastBuffer {
6112 // FIXME: We're going to need bit-level granularity when we support
6113 // bit-fields.
6114 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6115 // we don't support a host or target where that is the case. Still, we should
6116 // use a more generic type in case we ever do.
6117 SmallVector<Optional<unsigned char>, 32> Bytes;
6118
6119 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6120 "Need at least 8 bit unsigned char");
6121
6122 bool TargetIsLittleEndian;
6123
6124public:
6125 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6126 : Bytes(Width.getQuantity()),
6127 TargetIsLittleEndian(TargetIsLittleEndian) {}
6128
6129 LLVM_NODISCARD
6130 bool readObject(CharUnits Offset, CharUnits Width,
6131 SmallVectorImpl<unsigned char> &Output) const {
6132 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6133 // If a byte of an integer is uninitialized, then the whole integer is
6134 // uninitalized.
6135 if (!Bytes[I.getQuantity()])
6136 return false;
6137 Output.push_back(*Bytes[I.getQuantity()]);
6138 }
6139 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6140 std::reverse(Output.begin(), Output.end());
6141 return true;
6142 }
6143
6144 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6145 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6146 std::reverse(Input.begin(), Input.end());
6147
6148 size_t Index = 0;
6149 for (unsigned char Byte : Input) {
6150 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6151 Bytes[Offset.getQuantity() + Index] = Byte;
6152 ++Index;
6153 }
6154 }
6155
6156 size_t size() { return Bytes.size(); }
6157};
6158
6159/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6160/// target would represent the value at runtime.
6161class APValueToBufferConverter {
6162 EvalInfo &Info;
6163 BitCastBuffer Buffer;
6164 const CastExpr *BCE;
6165
6166 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6167 const CastExpr *BCE)
6168 : Info(Info),
6169 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6170 BCE(BCE) {}
6171
6172 bool visit(const APValue &Val, QualType Ty) {
6173 return visit(Val, Ty, CharUnits::fromQuantity(0));
6174 }
6175
6176 // Write out Val with type Ty into Buffer starting at Offset.
6177 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6178 assert((size_t)Offset.getQuantity() <= Buffer.size());
6179
6180 // As a special case, nullptr_t has an indeterminate value.
6181 if (Ty->isNullPtrType())
6182 return true;
6183
6184 // Dig through Src to find the byte at SrcOffset.
6185 switch (Val.getKind()) {
6186 case APValue::Indeterminate:
6187 case APValue::None:
6188 return true;
6189
6190 case APValue::Int:
6191 return visitInt(Val.getInt(), Ty, Offset);
6192 case APValue::Float:
6193 return visitFloat(Val.getFloat(), Ty, Offset);
6194 case APValue::Array:
6195 return visitArray(Val, Ty, Offset);
6196 case APValue::Struct:
6197 return visitRecord(Val, Ty, Offset);
6198
6199 case APValue::ComplexInt:
6200 case APValue::ComplexFloat:
6201 case APValue::Vector:
6202 case APValue::FixedPoint:
6203 // FIXME: We should support these.
6204
6205 case APValue::Union:
6206 case APValue::MemberPointer:
6207 case APValue::AddrLabelDiff: {
6208 Info.FFDiag(BCE->getBeginLoc(),
6209 diag::note_constexpr_bit_cast_unsupported_type)
6210 << Ty;
6211 return false;
6212 }
6213
6214 case APValue::LValue:
6215 llvm_unreachable("LValue subobject in bit_cast?");
6216 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006217 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006218 }
6219
6220 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6221 const RecordDecl *RD = Ty->getAsRecordDecl();
6222 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6223
6224 // Visit the base classes.
6225 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6226 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6227 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6228 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6229
6230 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6231 Layout.getBaseClassOffset(BaseDecl) + Offset))
6232 return false;
6233 }
6234 }
6235
6236 // Visit the fields.
6237 unsigned FieldIdx = 0;
6238 for (FieldDecl *FD : RD->fields()) {
6239 if (FD->isBitField()) {
6240 Info.FFDiag(BCE->getBeginLoc(),
6241 diag::note_constexpr_bit_cast_unsupported_bitfield);
6242 return false;
6243 }
6244
6245 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6246
6247 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6248 "only bit-fields can have sub-char alignment");
6249 CharUnits FieldOffset =
6250 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6251 QualType FieldTy = FD->getType();
6252 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6253 return false;
6254 ++FieldIdx;
6255 }
6256
6257 return true;
6258 }
6259
6260 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6261 const auto *CAT =
6262 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6263 if (!CAT)
6264 return false;
6265
6266 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6267 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6268 unsigned ArraySize = Val.getArraySize();
6269 // First, initialize the initialized elements.
6270 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6271 const APValue &SubObj = Val.getArrayInitializedElt(I);
6272 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6273 return false;
6274 }
6275
6276 // Next, initialize the rest of the array using the filler.
6277 if (Val.hasArrayFiller()) {
6278 const APValue &Filler = Val.getArrayFiller();
6279 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6280 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6281 return false;
6282 }
6283 }
6284
6285 return true;
6286 }
6287
6288 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6289 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6290 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6291 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6292 Buffer.writeObject(Offset, Bytes);
6293 return true;
6294 }
6295
6296 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6297 APSInt AsInt(Val.bitcastToAPInt());
6298 return visitInt(AsInt, Ty, Offset);
6299 }
6300
6301public:
6302 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6303 const CastExpr *BCE) {
6304 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6305 APValueToBufferConverter Converter(Info, DstSize, BCE);
6306 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6307 return None;
6308 return Converter.Buffer;
6309 }
6310};
6311
6312/// Write an BitCastBuffer into an APValue.
6313class BufferToAPValueConverter {
6314 EvalInfo &Info;
6315 const BitCastBuffer &Buffer;
6316 const CastExpr *BCE;
6317
6318 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6319 const CastExpr *BCE)
6320 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6321
6322 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6323 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6324 // Ideally this will be unreachable.
6325 llvm::NoneType unsupportedType(QualType Ty) {
6326 Info.FFDiag(BCE->getBeginLoc(),
6327 diag::note_constexpr_bit_cast_unsupported_type)
6328 << Ty;
6329 return None;
6330 }
6331
6332 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6333 const EnumType *EnumSugar = nullptr) {
6334 if (T->isNullPtrType()) {
6335 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6336 return APValue((Expr *)nullptr,
6337 /*Offset=*/CharUnits::fromQuantity(NullValue),
6338 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6339 }
6340
6341 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6342 SmallVector<uint8_t, 8> Bytes;
6343 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6344 // If this is std::byte or unsigned char, then its okay to store an
6345 // indeterminate value.
6346 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6347 bool IsUChar =
6348 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6349 T->isSpecificBuiltinType(BuiltinType::Char_U));
6350 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00006351 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006352 Info.FFDiag(BCE->getExprLoc(),
6353 diag::note_constexpr_bit_cast_indet_dest)
6354 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6355 return None;
6356 }
6357
6358 return APValue::IndeterminateValue();
6359 }
6360
6361 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6362 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6363
6364 if (T->isIntegralOrEnumerationType()) {
6365 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6366 return APValue(Val);
6367 }
6368
6369 if (T->isRealFloatingType()) {
6370 const llvm::fltSemantics &Semantics =
6371 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6372 return APValue(APFloat(Semantics, Val));
6373 }
6374
6375 return unsupportedType(QualType(T, 0));
6376 }
6377
6378 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6379 const RecordDecl *RD = RTy->getAsRecordDecl();
6380 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6381
6382 unsigned NumBases = 0;
6383 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6384 NumBases = CXXRD->getNumBases();
6385
6386 APValue ResultVal(APValue::UninitStruct(), NumBases,
6387 std::distance(RD->field_begin(), RD->field_end()));
6388
6389 // Visit the base classes.
6390 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6391 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6392 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6393 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6394 if (BaseDecl->isEmpty() ||
6395 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6396 continue;
6397
6398 Optional<APValue> SubObj = visitType(
6399 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6400 if (!SubObj)
6401 return None;
6402 ResultVal.getStructBase(I) = *SubObj;
6403 }
6404 }
6405
6406 // Visit the fields.
6407 unsigned FieldIdx = 0;
6408 for (FieldDecl *FD : RD->fields()) {
6409 // FIXME: We don't currently support bit-fields. A lot of the logic for
6410 // this is in CodeGen, so we need to factor it around.
6411 if (FD->isBitField()) {
6412 Info.FFDiag(BCE->getBeginLoc(),
6413 diag::note_constexpr_bit_cast_unsupported_bitfield);
6414 return None;
6415 }
6416
6417 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6418 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6419
6420 CharUnits FieldOffset =
6421 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6422 Offset;
6423 QualType FieldTy = FD->getType();
6424 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6425 if (!SubObj)
6426 return None;
6427 ResultVal.getStructField(FieldIdx) = *SubObj;
6428 ++FieldIdx;
6429 }
6430
6431 return ResultVal;
6432 }
6433
6434 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6435 QualType RepresentationType = Ty->getDecl()->getIntegerType();
6436 assert(!RepresentationType.isNull() &&
6437 "enum forward decl should be caught by Sema");
Simon Pilgrimc15b38e2019-10-03 15:08:30 +00006438 const auto *AsBuiltin =
6439 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006440 // Recurse into the underlying type. Treat std::byte transparently as
6441 // unsigned char.
6442 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6443 }
6444
6445 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6446 size_t Size = Ty->getSize().getLimitedValue();
6447 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6448
6449 APValue ArrayValue(APValue::UninitArray(), Size, Size);
6450 for (size_t I = 0; I != Size; ++I) {
6451 Optional<APValue> ElementValue =
6452 visitType(Ty->getElementType(), Offset + I * ElementWidth);
6453 if (!ElementValue)
6454 return None;
6455 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6456 }
6457
6458 return ArrayValue;
6459 }
6460
6461 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6462 return unsupportedType(QualType(Ty, 0));
6463 }
6464
6465 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6466 QualType Can = Ty.getCanonicalType();
6467
6468 switch (Can->getTypeClass()) {
6469#define TYPE(Class, Base) \
6470 case Type::Class: \
6471 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6472#define ABSTRACT_TYPE(Class, Base)
6473#define NON_CANONICAL_TYPE(Class, Base) \
6474 case Type::Class: \
6475 llvm_unreachable("non-canonical type should be impossible!");
6476#define DEPENDENT_TYPE(Class, Base) \
6477 case Type::Class: \
6478 llvm_unreachable( \
6479 "dependent types aren't supported in the constant evaluator!");
6480#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
6481 case Type::Class: \
6482 llvm_unreachable("either dependent or not canonical!");
John McCall36b12a82019-10-02 06:35:23 +00006483#include "clang/AST/TypeNodes.inc"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006484 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006485 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006486 }
6487
6488public:
6489 // Pull out a full value of type DstType.
6490 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6491 const CastExpr *BCE) {
6492 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6493 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6494 }
6495};
6496
6497static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6498 QualType Ty, EvalInfo *Info,
6499 const ASTContext &Ctx,
6500 bool CheckingDest) {
6501 Ty = Ty.getCanonicalType();
6502
6503 auto diag = [&](int Reason) {
6504 if (Info)
6505 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6506 << CheckingDest << (Reason == 4) << Reason;
6507 return false;
6508 };
6509 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6510 if (Info)
6511 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6512 << NoteTy << Construct << Ty;
6513 return false;
6514 };
6515
6516 if (Ty->isUnionType())
6517 return diag(0);
6518 if (Ty->isPointerType())
6519 return diag(1);
6520 if (Ty->isMemberPointerType())
6521 return diag(2);
6522 if (Ty.isVolatileQualified())
6523 return diag(3);
6524
6525 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6526 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6527 for (CXXBaseSpecifier &BS : CXXRD->bases())
6528 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6529 CheckingDest))
6530 return note(1, BS.getType(), BS.getBeginLoc());
6531 }
6532 for (FieldDecl *FD : Record->fields()) {
6533 if (FD->getType()->isReferenceType())
6534 return diag(4);
6535 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6536 CheckingDest))
6537 return note(0, FD->getType(), FD->getBeginLoc());
6538 }
6539 }
6540
6541 if (Ty->isArrayType() &&
6542 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6543 Info, Ctx, CheckingDest))
6544 return false;
6545
6546 return true;
6547}
6548
6549static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6550 const ASTContext &Ctx,
6551 const CastExpr *BCE) {
6552 bool DestOK = checkBitCastConstexprEligibilityType(
6553 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6554 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6555 BCE->getBeginLoc(),
6556 BCE->getSubExpr()->getType(), Info, Ctx, false);
6557 return SourceOK;
6558}
6559
6560static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6561 APValue &SourceValue,
6562 const CastExpr *BCE) {
6563 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6564 "no host or target supports non 8-bit chars");
6565 assert(SourceValue.isLValue() &&
6566 "LValueToRValueBitcast requires an lvalue operand!");
6567
6568 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6569 return false;
6570
6571 LValue SourceLValue;
6572 APValue SourceRValue;
6573 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00006574 if (!handleLValueToRValueConversion(
6575 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6576 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006577 return false;
6578
6579 // Read out SourceValue into a char buffer.
6580 Optional<BitCastBuffer> Buffer =
6581 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6582 if (!Buffer)
6583 return false;
6584
6585 // Write out the buffer into a new APValue.
6586 Optional<APValue> MaybeDestValue =
6587 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6588 if (!MaybeDestValue)
6589 return false;
6590
6591 DestValue = std::move(*MaybeDestValue);
6592 return true;
6593}
6594
Aaron Ballman68af21c2014-01-03 19:26:43 +00006595template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00006596class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006597 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00006598private:
Richard Smith52a980a2015-08-28 02:43:42 +00006599 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006600 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006601 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006602 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006603 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006604 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006605 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006606
Richard Smith17100ba2012-02-16 02:46:34 +00006607 // Check whether a conditional operator with a non-constant condition is a
6608 // potential constant expression. If neither arm is a potential constant
6609 // expression, then the conditional operator is not either.
6610 template<typename ConditionalOperator>
6611 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00006612 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00006613
6614 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00006615 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00006616 {
Richard Smith17100ba2012-02-16 02:46:34 +00006617 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006618 StmtVisitorTy::Visit(E->getFalseExpr());
6619 if (Diag.empty())
6620 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00006621 }
Richard Smith17100ba2012-02-16 02:46:34 +00006622
George Burgess IV8c892b52016-05-25 22:31:54 +00006623 {
6624 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006625 Diag.clear();
6626 StmtVisitorTy::Visit(E->getTrueExpr());
6627 if (Diag.empty())
6628 return;
6629 }
6630
6631 Error(E, diag::note_constexpr_conditional_never_const);
6632 }
6633
6634
6635 template<typename ConditionalOperator>
6636 bool HandleConditionalOperator(const ConditionalOperator *E) {
6637 bool BoolResult;
6638 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00006639 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00006640 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00006641 return false;
6642 }
6643 if (Info.noteFailure()) {
6644 StmtVisitorTy::Visit(E->getTrueExpr());
6645 StmtVisitorTy::Visit(E->getFalseExpr());
6646 }
Richard Smith17100ba2012-02-16 02:46:34 +00006647 return false;
6648 }
6649
6650 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6651 return StmtVisitorTy::Visit(EvalExpr);
6652 }
6653
Peter Collingbournee9200682011-05-13 03:29:01 +00006654protected:
6655 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006656 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00006657 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6658
Richard Smith92b1ce02011-12-12 09:28:41 +00006659 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006660 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006661 }
6662
Aaron Ballman68af21c2014-01-03 19:26:43 +00006663 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006664
6665public:
6666 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6667
6668 EvalInfo &getEvalInfo() { return Info; }
6669
Richard Smithf57d8cb2011-12-09 22:58:01 +00006670 /// Report an evaluation error. This should only be called when an error is
6671 /// first discovered. When propagating an error, just return false.
6672 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006673 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006674 return false;
6675 }
6676 bool Error(const Expr *E) {
6677 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6678 }
6679
Aaron Ballman68af21c2014-01-03 19:26:43 +00006680 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00006681 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00006682 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006683 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006684 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006685 }
6686
Bill Wendling8003edc2018-11-09 00:41:36 +00006687 bool VisitConstantExpr(const ConstantExpr *E)
6688 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006689 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006690 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006691 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006692 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006693 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006694 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006695 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00006696 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006697 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006698 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006699 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00006700 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006701 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6702 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00006703 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006704 return StmtVisitorTy::Visit(E->getExpr());
6705 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006706 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006707 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00006708 // The initializer may not have been parsed yet, or might be erroneous.
6709 if (!E->getExpr())
6710 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00006711 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00006712 return StmtVisitorTy::Visit(E->getExpr());
6713 }
Eric Fiselier708afb52019-05-16 21:04:15 +00006714
Richard Smith457226e2019-09-23 03:48:44 +00006715 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6716 FullExpressionRAII Scope(Info);
6717 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6718 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006719
Richard Smith3b69bcc2019-10-01 00:41:16 +00006720 // Temporaries are registered when created, so we don't care about
6721 // CXXBindTemporaryExpr.
6722 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6723 return StmtVisitorTy::Visit(E->getSubExpr());
6724 }
6725
Aaron Ballman68af21c2014-01-03 19:26:43 +00006726 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006727 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6728 return static_cast<Derived*>(this)->VisitCastExpr(E);
6729 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006730 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00006731 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6732 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006733 return static_cast<Derived*>(this)->VisitCastExpr(E);
6734 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006735 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6736 return static_cast<Derived*>(this)->VisitCastExpr(E);
6737 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006738
Aaron Ballman68af21c2014-01-03 19:26:43 +00006739 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006740 switch (E->getOpcode()) {
6741 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006742 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006743
6744 case BO_Comma:
6745 VisitIgnoredValue(E->getLHS());
6746 return StmtVisitorTy::Visit(E->getRHS());
6747
6748 case BO_PtrMemD:
6749 case BO_PtrMemI: {
6750 LValue Obj;
6751 if (!HandleMemberPointerAccess(Info, E, Obj))
6752 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006753 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006754 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006755 return false;
6756 return DerivedSuccess(Result, E);
6757 }
6758 }
6759 }
6760
Aaron Ballman68af21c2014-01-03 19:26:43 +00006761 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006762 // Evaluate and cache the common expression. We treat it as a temporary,
6763 // even though it's not quite the same thing.
Richard Smith457226e2019-09-23 03:48:44 +00006764 LValue CommonLV;
6765 if (!Evaluate(Info.CurrentCall->createTemporary(
Richard Smith61422f92019-09-27 20:24:36 +00006766 E->getOpaqueValue(),
6767 getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6768 CommonLV),
Richard Smith26d4cc12012-06-26 08:12:11 +00006769 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006770 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006771
Richard Smith17100ba2012-02-16 02:46:34 +00006772 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006773 }
6774
Aaron Ballman68af21c2014-01-03 19:26:43 +00006775 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006776 bool IsBcpCall = false;
6777 // If the condition (ignoring parens) is a __builtin_constant_p call,
6778 // the result is a constant expression if it can be folded without
6779 // side-effects. This is an important GNU extension. See GCC PR38377
6780 // for discussion.
6781 if (const CallExpr *CallCE =
6782 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006783 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006784 IsBcpCall = true;
6785
6786 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6787 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00006788 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6789 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00006790 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006791 return false;
6792
Richard Smith6d4c6582013-11-05 22:18:15 +00006793 FoldConstant Fold(Info, IsBcpCall);
6794 if (!HandleConditionalOperator(E)) {
6795 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006796 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006797 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006798
6799 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006800 }
6801
Aaron Ballman68af21c2014-01-03 19:26:43 +00006802 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006803 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006804 return DerivedSuccess(*Value, E);
6805
6806 const Expr *Source = E->getSourceExpr();
6807 if (!Source)
6808 return Error(E);
6809 if (Source == E) { // sanity checking.
6810 assert(0 && "OpaqueValueExpr recursively refers to itself");
6811 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006812 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006813 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006814 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006815
Aaron Ballman68af21c2014-01-03 19:26:43 +00006816 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006817 APValue Result;
6818 if (!handleCallExpr(E, Result, nullptr))
6819 return false;
6820 return DerivedSuccess(Result, E);
6821 }
6822
6823 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006824 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006825 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006826 QualType CalleeType = Callee->getType();
6827
Craig Topper36250ad2014-05-12 05:36:57 +00006828 const FunctionDecl *FD = nullptr;
6829 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006830 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006831 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006832
Richard Smithe97cbd72011-11-11 04:05:33 +00006833 // Extract function decl and 'this' pointer from the callee.
6834 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006835 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006836 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6837 // Explicit bound member calls, such as x.f() or p->g();
6838 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006839 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006840 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6841 if (!Member)
6842 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006843 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006844 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006845 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6846 // Indirect bound member calls ('.*' or '->*').
Richard Smith52582022019-10-03 01:20:27 +00006847 const ValueDecl *D =
6848 HandleMemberPointerAccess(Info, BE, ThisVal, false);
6849 if (!D)
6850 return false;
6851 Member = dyn_cast<CXXMethodDecl>(D);
Richard Smith921f1322019-05-13 23:35:21 +00006852 if (!Member)
6853 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006854 This = &ThisVal;
Richard Smith61422f92019-09-27 20:24:36 +00006855 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6856 if (!Info.getLangOpts().CPlusPlus2a)
6857 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6858 // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6859 // their callee, we should start calling HandleDestruction here.
6860 // For now, we just evaluate the object argument and discard it.
6861 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
Richard Smith027bf112011-11-17 22:56:20 +00006862 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006863 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006864 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006865 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006866 LValue Call;
6867 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006868 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006869
Richard Smitha8105bc2012-01-06 16:39:00 +00006870 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006871 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006872 FD = dyn_cast_or_null<FunctionDecl>(
6873 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006874 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006875 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006876 // Don't call function pointers which have been cast to some other type.
6877 // Per DR (no number yet), the caller and callee can differ in noexcept.
6878 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6879 CalleeType->getPointeeType(), FD->getType())) {
6880 return Error(E);
6881 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006882
6883 // Overloaded operator calls to member functions are represented as normal
6884 // calls with '*this' as the first argument.
6885 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6886 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006887 // FIXME: When selecting an implicit conversion for an overloaded
6888 // operator delete, we sometimes try to evaluate calls to conversion
6889 // operators without a 'this' parameter!
6890 if (Args.empty())
6891 return Error(E);
6892
Nick Lewycky13073a62017-06-12 21:15:44 +00006893 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006894 return false;
6895 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006896 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006897 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006898 // Map the static invoker for the lambda back to the call operator.
6899 // Conveniently, we don't have to slice out the 'this' argument (as is
6900 // being done for the non-static case), since a static member function
6901 // doesn't have an implicit argument passed in.
6902 const CXXRecordDecl *ClosureClass = MD->getParent();
6903 assert(
6904 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6905 "Number of captures must be zero for conversion to function-ptr");
6906
6907 const CXXMethodDecl *LambdaCallOp =
6908 ClosureClass->getLambdaCallOperator();
6909
6910 // Set 'FD', the function that will be called below, to the call
6911 // operator. If the closure object represents a generic lambda, find
6912 // the corresponding specialization of the call operator.
6913
6914 if (ClosureClass->isGenericLambda()) {
6915 assert(MD->isFunctionTemplateSpecialization() &&
6916 "A generic lambda's static-invoker function must be a "
6917 "template specialization");
6918 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6919 FunctionTemplateDecl *CallOpTemplate =
6920 LambdaCallOp->getDescribedFunctionTemplate();
6921 void *InsertPos = nullptr;
6922 FunctionDecl *CorrespondingCallOpSpecialization =
6923 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6924 assert(CorrespondingCallOpSpecialization &&
6925 "We must always have a function call operator specialization "
6926 "that corresponds to our static invoker specialization");
6927 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6928 } else
6929 FD = LambdaCallOp;
Richard Smith19ad5232019-10-03 00:39:33 +00006930 } else if (FD->isReplaceableGlobalAllocationFunction()) {
6931 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
6932 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
6933 LValue Ptr;
6934 if (!HandleOperatorNewCall(Info, E, Ptr))
6935 return false;
6936 Ptr.moveInto(Result);
6937 return true;
6938 } else {
6939 return HandleOperatorDeleteCall(Info, E);
6940 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006941 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006942 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006943 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006944
Richard Smith921f1322019-05-13 23:35:21 +00006945 SmallVector<QualType, 4> CovariantAdjustmentPath;
6946 if (This) {
6947 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006948 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6949 // Perform virtual dispatch, if necessary.
6950 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6951 CovariantAdjustmentPath);
6952 if (!FD)
6953 return false;
6954 } else {
6955 // Check that the 'this' pointer points to an object of the right type.
Richard Smith61422f92019-09-27 20:24:36 +00006956 // FIXME: If this is an assignment operator call, we may need to change
6957 // the active union member before we check this.
6958 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
Richard Smith7bd54ab2019-05-15 20:22:21 +00006959 return false;
6960 }
Richard Smith921f1322019-05-13 23:35:21 +00006961 }
Richard Smith47b34932012-02-01 02:39:43 +00006962
Richard Smith61422f92019-09-27 20:24:36 +00006963 // Destructor calls are different enough that they have their own codepath.
6964 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
6965 assert(This && "no 'this' pointer for destructor call");
6966 return HandleDestruction(Info, E, *This,
6967 Info.Ctx.getRecordType(DD->getParent()));
6968 }
6969
Craig Topper36250ad2014-05-12 05:36:57 +00006970 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006971 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006972
Nick Lewycky13073a62017-06-12 21:15:44 +00006973 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6974 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006975 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006976 return false;
6977
Richard Smith921f1322019-05-13 23:35:21 +00006978 if (!CovariantAdjustmentPath.empty() &&
6979 !HandleCovariantReturnAdjustment(Info, E, Result,
6980 CovariantAdjustmentPath))
6981 return false;
6982
Richard Smith52a980a2015-08-28 02:43:42 +00006983 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006984 }
6985
Aaron Ballman68af21c2014-01-03 19:26:43 +00006986 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006987 return StmtVisitorTy::Visit(E->getInitializer());
6988 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006989 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006990 if (E->getNumInits() == 0)
6991 return DerivedZeroInitialization(E);
6992 if (E->getNumInits() == 1)
6993 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006994 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006995 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006996 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006997 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006998 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006999 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007000 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00007001 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007002 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007003 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007004 }
Richard Smith4ce706a2011-10-11 21:43:33 +00007005
Richard Smithd62306a2011-11-10 06:34:14 +00007006 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00007007 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007008 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7009 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00007010 assert(!E->isArrow() && "missing call to bound member function?");
7011
Richard Smith2e312c82012-03-03 22:46:17 +00007012 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00007013 if (!Evaluate(Val, Info, E->getBase()))
7014 return false;
7015
7016 QualType BaseTy = E->getBase()->getType();
7017
7018 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00007019 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007020 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00007021 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00007022 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7023
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007024 // Note: there is no lvalue base here. But this case should only ever
7025 // happen in C or in C++98, where we cannot be evaluating a constexpr
7026 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00007027 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00007028 SubobjectDesignator Designator(BaseTy);
7029 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00007030
Richard Smith3229b742013-05-05 21:17:10 +00007031 APValue Result;
7032 return extractSubobject(Info, E, Obj, Designator, Result) &&
7033 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00007034 }
7035
Aaron Ballman68af21c2014-01-03 19:26:43 +00007036 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007037 switch (E->getCastKind()) {
7038 default:
7039 break;
7040
Richard Smitha23ab512013-05-23 00:30:41 +00007041 case CK_AtomicToNonAtomic: {
7042 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00007043 // This does not need to be done in place even for class/array types:
7044 // atomic-to-non-atomic conversion implies copying the object
7045 // representation.
7046 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00007047 return false;
7048 return DerivedSuccess(AtomicVal, E);
7049 }
7050
Richard Smith11562c52011-10-28 17:51:58 +00007051 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00007052 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00007053 return StmtVisitorTy::Visit(E->getSubExpr());
7054
7055 case CK_LValueToRValue: {
7056 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007057 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7058 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007059 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00007060 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00007061 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00007062 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007063 return false;
7064 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00007065 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00007066 case CK_LValueToRValueBitCast: {
7067 APValue DestValue, SourceValue;
7068 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7069 return false;
7070 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7071 return false;
7072 return DerivedSuccess(DestValue, E);
7073 }
Richard Smith11562c52011-10-28 17:51:58 +00007074 }
7075
Richard Smithf57d8cb2011-12-09 22:58:01 +00007076 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007077 }
7078
Aaron Ballman68af21c2014-01-03 19:26:43 +00007079 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00007080 return VisitUnaryPostIncDec(UO);
7081 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007082 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00007083 return VisitUnaryPostIncDec(UO);
7084 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007085 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007086 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007087 return Error(UO);
7088
7089 LValue LVal;
7090 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7091 return false;
7092 APValue RVal;
7093 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7094 UO->isIncrementOp(), &RVal))
7095 return false;
7096 return DerivedSuccess(RVal, UO);
7097 }
7098
Aaron Ballman68af21c2014-01-03 19:26:43 +00007099 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00007100 // We will have checked the full-expressions inside the statement expression
7101 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00007102 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00007103 return Error(E);
7104
7105 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00007106 if (CS->body_empty())
7107 return true;
7108
Richard Smith457226e2019-09-23 03:48:44 +00007109 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00007110 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7111 BE = CS->body_end();
7112 /**/; ++BI) {
7113 if (BI + 1 == BE) {
7114 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7115 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007116 Info.FFDiag((*BI)->getBeginLoc(),
7117 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00007118 return false;
7119 }
Richard Smith457226e2019-09-23 03:48:44 +00007120 return this->Visit(FinalExpr) && Scope.destroy();
Richard Smith51f03172013-06-20 03:00:05 +00007121 }
7122
7123 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00007124 StmtResult Result = { ReturnValue, nullptr };
7125 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00007126 if (ESR != ESR_Succeeded) {
7127 // FIXME: If the statement-expression terminated due to 'return',
7128 // 'break', or 'continue', it would be nice to propagate that to
7129 // the outer statement evaluation rather than bailing out.
7130 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007131 Info.FFDiag((*BI)->getBeginLoc(),
7132 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00007133 return false;
7134 }
7135 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00007136
7137 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00007138 }
7139
Richard Smith4a678122011-10-24 18:44:57 +00007140 /// Visit a value which is evaluated, but whose value is ignored.
7141 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00007142 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00007143 }
David Majnemere9807b22016-02-26 04:23:19 +00007144
7145 /// Potentially visit a MemberExpr's base expression.
7146 void VisitIgnoredBaseExpression(const Expr *E) {
7147 // While MSVC doesn't evaluate the base expression, it does diagnose the
7148 // presence of side-effecting behavior.
7149 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7150 return;
7151 VisitIgnoredValue(E);
7152 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007153};
7154
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007155} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00007156
7157//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007158// Common base class for lvalue and temporary evaluation.
7159//===----------------------------------------------------------------------===//
7160namespace {
7161template<class Derived>
7162class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00007163 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00007164protected:
7165 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007166 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00007167 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00007168 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00007169
7170 bool Success(APValue::LValueBase B) {
7171 Result.set(B);
7172 return true;
7173 }
7174
George Burgess IVf9013bf2017-02-10 22:52:29 +00007175 bool evaluatePointer(const Expr *E, LValue &Result) {
7176 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7177 }
7178
Richard Smith027bf112011-11-17 22:56:20 +00007179public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007180 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7181 : ExprEvaluatorBaseTy(Info), Result(Result),
7182 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00007183
Richard Smith2e312c82012-03-03 22:46:17 +00007184 bool Success(const APValue &V, const Expr *E) {
7185 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00007186 return true;
7187 }
Richard Smith027bf112011-11-17 22:56:20 +00007188
Richard Smith027bf112011-11-17 22:56:20 +00007189 bool VisitMemberExpr(const MemberExpr *E) {
7190 // Handle non-static data members.
7191 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007192 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00007193 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007194 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00007195 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00007196 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007197 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00007198 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00007199 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00007200 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00007201 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00007202 BaseTy = E->getBase()->getType();
7203 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00007204 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007205 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007206 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00007207 Result.setInvalid(E);
7208 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007209 }
Richard Smith027bf112011-11-17 22:56:20 +00007210
Richard Smith1b78b3d2012-01-25 22:15:11 +00007211 const ValueDecl *MD = E->getMemberDecl();
7212 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00007213 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith1b78b3d2012-01-25 22:15:11 +00007214 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7215 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00007216 if (!HandleLValueMember(this->Info, E, Result, FD))
7217 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00007218 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00007219 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7220 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00007221 } else
7222 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007223
Richard Smith1b78b3d2012-01-25 22:15:11 +00007224 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00007225 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00007226 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00007227 RefValue))
7228 return false;
7229 return Success(RefValue, E);
7230 }
7231 return true;
7232 }
7233
7234 bool VisitBinaryOperator(const BinaryOperator *E) {
7235 switch (E->getOpcode()) {
7236 default:
7237 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7238
7239 case BO_PtrMemD:
7240 case BO_PtrMemI:
7241 return HandleMemberPointerAccess(this->Info, E, Result);
7242 }
7243 }
7244
7245 bool VisitCastExpr(const CastExpr *E) {
7246 switch (E->getCastKind()) {
7247 default:
7248 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7249
7250 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007251 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00007252 if (!this->Visit(E->getSubExpr()))
7253 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007254
7255 // Now figure out the necessary offset to add to the base LV to get from
7256 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007257 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7258 Result);
Richard Smith027bf112011-11-17 22:56:20 +00007259 }
7260 }
7261};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007262}
Richard Smith027bf112011-11-17 22:56:20 +00007263
7264//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00007265// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007266//
7267// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7268// function designators (in C), decl references to void objects (in C), and
7269// temporaries (if building with -Wno-address-of-temporary).
7270//
7271// LValue evaluation produces values comprising a base expression of one of the
7272// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00007273// - Declarations
7274// * VarDecl
7275// * FunctionDecl
7276// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00007277// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00007278// * StringLiteral
7279// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00007280// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00007281// * ObjCEncodeExpr
7282// * AddrLabelExpr
7283// * BlockExpr
7284// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00007285// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00007286// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00007287// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00007288// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00007289// was evaluated, for cases where the MaterializeTemporaryExpr is missing
7290// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00007291// * A MaterializeTemporaryExpr that has static storage duration, with no
7292// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00007293// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00007294//===----------------------------------------------------------------------===//
7295namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007296class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00007297 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00007298public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007299 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7300 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00007301
Richard Smith11562c52011-10-28 17:51:58 +00007302 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00007303 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00007304
Peter Collingbournee9200682011-05-13 03:29:01 +00007305 bool VisitDeclRefExpr(const DeclRefExpr *E);
7306 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007307 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007308 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7309 bool VisitMemberExpr(const MemberExpr *E);
7310 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7311 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00007312 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00007313 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007314 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7315 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00007316 bool VisitUnaryReal(const UnaryOperator *E);
7317 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00007318 bool VisitUnaryPreInc(const UnaryOperator *UO) {
7319 return VisitUnaryPreIncDec(UO);
7320 }
7321 bool VisitUnaryPreDec(const UnaryOperator *UO) {
7322 return VisitUnaryPreIncDec(UO);
7323 }
Richard Smith3229b742013-05-05 21:17:10 +00007324 bool VisitBinAssign(const BinaryOperator *BO);
7325 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00007326
Peter Collingbournee9200682011-05-13 03:29:01 +00007327 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00007328 switch (E->getCastKind()) {
7329 default:
Richard Smith027bf112011-11-17 22:56:20 +00007330 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00007331
Eli Friedmance3e02a2011-10-11 00:13:24 +00007332 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00007333 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00007334 if (!Visit(E->getSubExpr()))
7335 return false;
7336 Result.Designator.setInvalid();
7337 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00007338
Richard Smith027bf112011-11-17 22:56:20 +00007339 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00007340 if (!Visit(E->getSubExpr()))
7341 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007342 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00007343
7344 case CK_Dynamic:
7345 if (!Visit(E->getSubExpr()))
7346 return false;
7347 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00007348 }
7349 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007350};
7351} // end anonymous namespace
7352
Richard Smith11562c52011-10-28 17:51:58 +00007353/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00007354/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00007355/// * function designators in C, and
7356/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00007357/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00007358static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7359 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00007360 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00007361 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00007362 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007363}
7364
Peter Collingbournee9200682011-05-13 03:29:01 +00007365bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00007366 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00007367 return Success(FD);
7368 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00007369 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00007370 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00007371 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00007372 return Error(E);
7373}
Richard Smith733237d2011-10-24 23:14:33 +00007374
Faisal Vali0528a312016-11-13 06:09:16 +00007375
Richard Smith11562c52011-10-28 17:51:58 +00007376bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007377
7378 // If we are within a lambda's call operator, check whether the 'VD' referred
7379 // to within 'E' actually represents a lambda-capture that maps to a
7380 // data-member/field within the closure object, and if so, evaluate to the
7381 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00007382 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7383 isa<DeclRefExpr>(E) &&
7384 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7385 // We don't always have a complete capture-map when checking or inferring if
7386 // the function call operator meets the requirements of a constexpr function
7387 // - but we don't need to evaluate the captures to determine constexprness
7388 // (dcl.constexpr C++17).
7389 if (Info.checkingPotentialConstantExpression())
7390 return false;
7391
Faisal Vali051e3a22017-02-16 04:12:21 +00007392 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007393 // Start with 'Result' referring to the complete closure object...
7394 Result = *Info.CurrentCall->This;
7395 // ... then update it to refer to the field of the closure object
7396 // that represents the capture.
7397 if (!HandleLValueMember(Info, E, Result, FD))
7398 return false;
7399 // And if the field is of reference type, update 'Result' to refer to what
7400 // the field refers to.
7401 if (FD->getType()->isReferenceType()) {
7402 APValue RVal;
7403 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7404 RVal))
7405 return false;
7406 Result.setFrom(Info.Ctx, RVal);
7407 }
7408 return true;
7409 }
7410 }
Craig Topper36250ad2014-05-12 05:36:57 +00007411 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00007412 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7413 // Only if a local variable was declared in the function currently being
7414 // evaluated, do we expect to be able to find its value in the current
7415 // frame. (Otherwise it was likely declared in an enclosing context and
7416 // could either have a valid evaluatable value (for e.g. a constexpr
7417 // variable) or be ill-formed (and trigger an appropriate evaluation
7418 // diagnostic)).
7419 if (Info.CurrentCall->Callee &&
7420 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7421 Frame = Info.CurrentCall;
7422 }
7423 }
Richard Smith3229b742013-05-05 21:17:10 +00007424
Richard Smithfec09922011-11-01 16:57:24 +00007425 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00007426 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007427 Result.set({VD, Frame->Index,
7428 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00007429 return true;
7430 }
Richard Smithce40ad62011-11-12 22:28:03 +00007431 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00007432 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00007433
Richard Smith3229b742013-05-05 21:17:10 +00007434 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007435 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007436 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00007437 if (!V->hasValue()) {
7438 // FIXME: Is it possible for V to be indeterminate here? If so, we should
7439 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00007440 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00007441 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007442 return false;
7443 }
Richard Smith3229b742013-05-05 21:17:10 +00007444 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00007445}
7446
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007447bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7448 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007449 // Walk through the expression to find the materialized temporary itself.
7450 SmallVector<const Expr *, 2> CommaLHSs;
7451 SmallVector<SubobjectAdjustment, 2> Adjustments;
7452 const Expr *Inner = E->GetTemporaryExpr()->
7453 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00007454
Richard Smith84401042013-06-03 05:03:02 +00007455 // If we passed any comma operators, evaluate their LHSs.
7456 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7457 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7458 return false;
7459
Richard Smithe6c01442013-06-05 00:46:14 +00007460 // A materialized temporary with static storage duration can appear within the
7461 // result of a constant expression evaluation, so we need to preserve its
7462 // value for use outside this evaluation.
7463 APValue *Value;
7464 if (E->getStorageDuration() == SD_Static) {
7465 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00007466 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00007467 Result.set(E);
7468 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007469 Value = &Info.CurrentCall->createTemporary(
7470 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
Richard Smithe6c01442013-06-05 00:46:14 +00007471 }
7472
Richard Smithea4ad5d2013-06-06 08:19:16 +00007473 QualType Type = Inner->getType();
7474
Richard Smith84401042013-06-03 05:03:02 +00007475 // Materialize the temporary itself.
Richard Smith4566f872019-09-29 05:58:31 +00007476 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
Richard Smithea4ad5d2013-06-06 08:19:16 +00007477 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00007478 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00007479 }
Richard Smith84401042013-06-03 05:03:02 +00007480
7481 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00007482 for (unsigned I = Adjustments.size(); I != 0; /**/) {
7483 --I;
7484 switch (Adjustments[I].Kind) {
7485 case SubobjectAdjustment::DerivedToBaseAdjustment:
7486 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7487 Type, Result))
7488 return false;
7489 Type = Adjustments[I].DerivedToBase.BasePath->getType();
7490 break;
7491
7492 case SubobjectAdjustment::FieldAdjustment:
7493 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7494 return false;
7495 Type = Adjustments[I].Field->getType();
7496 break;
7497
7498 case SubobjectAdjustment::MemberPointerAdjustment:
7499 if (!HandleMemberPointerAccess(this->Info, Type, Result,
7500 Adjustments[I].Ptr.RHS))
7501 return false;
7502 Type = Adjustments[I].Ptr.MPT->getPointeeType();
7503 break;
7504 }
7505 }
7506
7507 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007508}
7509
Peter Collingbournee9200682011-05-13 03:29:01 +00007510bool
7511LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00007512 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7513 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00007514 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7515 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00007516 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007517}
7518
Richard Smith6e525142011-12-27 12:18:28 +00007519bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00007520 TypeInfoLValue TypeInfo;
7521
Richard Smithee0ce3022019-05-17 07:06:46 +00007522 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00007523 if (E->isTypeOperand())
7524 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7525 else
7526 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00007527 } else {
7528 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7529 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7530 << E->getExprOperand()->getType()
7531 << E->getExprOperand()->getSourceRange();
7532 }
7533
7534 if (!Visit(E->getExprOperand()))
7535 return false;
7536
7537 Optional<DynamicType> DynType =
7538 ComputeDynamicType(Info, E, Result, AK_TypeId);
7539 if (!DynType)
7540 return false;
7541
7542 TypeInfo =
7543 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00007544 }
Richard Smith6f3d4352012-10-17 23:52:07 +00007545
Richard Smitha9330302019-05-17 19:19:28 +00007546 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00007547}
7548
Francois Pichet0066db92012-04-16 04:08:35 +00007549bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7550 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00007551}
Francois Pichet0066db92012-04-16 04:08:35 +00007552
Peter Collingbournee9200682011-05-13 03:29:01 +00007553bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007554 // Handle static data members.
7555 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007556 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00007557 return VisitVarDecl(E, VD);
7558 }
7559
Richard Smith254a73d2011-10-28 22:34:42 +00007560 // Handle static member functions.
7561 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7562 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00007563 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00007564 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00007565 }
7566 }
7567
Richard Smithd62306a2011-11-10 06:34:14 +00007568 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00007569 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007570}
7571
Peter Collingbournee9200682011-05-13 03:29:01 +00007572bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007573 // FIXME: Deal with vectors as array subscript bases.
7574 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007575 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007576
Nick Lewyckyad888682017-04-27 07:27:36 +00007577 bool Success = true;
7578 if (!evaluatePointer(E->getBase(), Result)) {
7579 if (!Info.noteFailure())
7580 return false;
7581 Success = false;
7582 }
Mike Stump11289f42009-09-09 15:08:12 +00007583
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007584 APSInt Index;
7585 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00007586 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007587
Nick Lewyckyad888682017-04-27 07:27:36 +00007588 return Success &&
7589 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007590}
Eli Friedman9a156e52008-11-12 09:44:48 +00007591
Peter Collingbournee9200682011-05-13 03:29:01 +00007592bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007593 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00007594}
7595
Richard Smith66c96992012-02-18 22:04:06 +00007596bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7597 if (!Visit(E->getSubExpr()))
7598 return false;
7599 // __real is a no-op on scalar lvalues.
7600 if (E->getSubExpr()->getType()->isAnyComplexType())
7601 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7602 return true;
7603}
7604
7605bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7606 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7607 "lvalue __imag__ on scalar?");
7608 if (!Visit(E->getSubExpr()))
7609 return false;
7610 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7611 return true;
7612}
7613
Richard Smith243ef902013-05-05 23:31:59 +00007614bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007615 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007616 return Error(UO);
7617
7618 if (!this->Visit(UO->getSubExpr()))
7619 return false;
7620
Richard Smith243ef902013-05-05 23:31:59 +00007621 return handleIncDec(
7622 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00007623 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00007624}
7625
7626bool LValueExprEvaluator::VisitCompoundAssignOperator(
7627 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007628 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007629 return Error(CAO);
7630
Richard Smith3229b742013-05-05 21:17:10 +00007631 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00007632
7633 // The overall lvalue result is the result of evaluating the LHS.
7634 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007635 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007636 Evaluate(RHS, this->Info, CAO->getRHS());
7637 return false;
7638 }
7639
Richard Smith3229b742013-05-05 21:17:10 +00007640 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7641 return false;
7642
Richard Smith43e77732013-05-07 04:50:00 +00007643 return handleCompoundAssignment(
7644 this->Info, CAO,
7645 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7646 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00007647}
7648
7649bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007650 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007651 return Error(E);
7652
Richard Smith3229b742013-05-05 21:17:10 +00007653 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00007654
7655 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007656 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007657 Evaluate(NewVal, this->Info, E->getRHS());
7658 return false;
7659 }
7660
Richard Smith3229b742013-05-05 21:17:10 +00007661 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7662 return false;
Richard Smith243ef902013-05-05 23:31:59 +00007663
Richard Smith31c69a32019-05-21 23:15:20 +00007664 if (Info.getLangOpts().CPlusPlus2a &&
7665 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7666 return false;
7667
Richard Smith243ef902013-05-05 23:31:59 +00007668 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00007669 NewVal);
7670}
7671
Eli Friedman9a156e52008-11-12 09:44:48 +00007672//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007673// Pointer Evaluation
7674//===----------------------------------------------------------------------===//
7675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007676/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00007677/// returned by a function with the alloc_size attribute. Returns true if we
7678/// were successful. Places an unsigned number into `Result`.
7679///
7680/// This expects the given CallExpr to be a call to a function with an
7681/// alloc_size attribute.
7682static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7683 const CallExpr *Call,
7684 llvm::APInt &Result) {
7685 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7686
Joel E. Denny81508102018-03-13 14:51:22 +00007687 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7688 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007689 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7690 if (Call->getNumArgs() <= SizeArgNo)
7691 return false;
7692
7693 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00007694 Expr::EvalResult ExprResult;
7695 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00007696 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007697 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00007698 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7699 return false;
7700 Into = Into.zextOrSelf(BitsInSizeT);
7701 return true;
7702 };
7703
7704 APSInt SizeOfElem;
7705 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7706 return false;
7707
Joel E. Denny81508102018-03-13 14:51:22 +00007708 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007709 Result = std::move(SizeOfElem);
7710 return true;
7711 }
7712
7713 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00007714 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007715 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7716 return false;
7717
7718 bool Overflow;
7719 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7720 if (Overflow)
7721 return false;
7722
7723 Result = std::move(BytesAvailable);
7724 return true;
7725}
7726
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007727/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00007728/// function.
7729static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7730 const LValue &LVal,
7731 llvm::APInt &Result) {
7732 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7733 "Can't get the size of a non alloc_size function");
7734 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7735 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7736 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7737}
7738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007739/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00007740/// a function with the alloc_size attribute. If it was possible to do so, this
7741/// function will return true, make Result's Base point to said function call,
7742/// and mark Result's Base as invalid.
7743static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7744 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007745 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00007746 return false;
7747
7748 // Because we do no form of static analysis, we only support const variables.
7749 //
7750 // Additionally, we can't support parameters, nor can we support static
7751 // variables (in the latter case, use-before-assign isn't UB; in the former,
7752 // we have no clue what they'll be assigned to).
7753 const auto *VD =
7754 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7755 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7756 return false;
7757
7758 const Expr *Init = VD->getAnyInitializer();
7759 if (!Init)
7760 return false;
7761
7762 const Expr *E = Init->IgnoreParens();
7763 if (!tryUnwrapAllocSizeCall(E))
7764 return false;
7765
7766 // Store E instead of E unwrapped so that the type of the LValue's base is
7767 // what the user wanted.
7768 Result.setInvalid(E);
7769
7770 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007771 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007772 return true;
7773}
7774
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007775namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007776class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007777 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007778 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007779 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007780
Peter Collingbournee9200682011-05-13 03:29:01 +00007781 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007782 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007783 return true;
7784 }
George Burgess IVe3763372016-12-22 02:50:20 +00007785
George Burgess IVf9013bf2017-02-10 22:52:29 +00007786 bool evaluateLValue(const Expr *E, LValue &Result) {
7787 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7788 }
7789
7790 bool evaluatePointer(const Expr *E, LValue &Result) {
7791 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7792 }
7793
George Burgess IVe3763372016-12-22 02:50:20 +00007794 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007795public:
Mike Stump11289f42009-09-09 15:08:12 +00007796
George Burgess IVf9013bf2017-02-10 22:52:29 +00007797 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7798 : ExprEvaluatorBaseTy(info), Result(Result),
7799 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007800
Richard Smith2e312c82012-03-03 22:46:17 +00007801 bool Success(const APValue &V, const Expr *E) {
7802 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007803 return true;
7804 }
Richard Smithfddd3842011-12-30 21:15:51 +00007805 bool ZeroInitialization(const Expr *E) {
Richard Smith19ad5232019-10-03 00:39:33 +00007806 Result.setNull(Info.Ctx, E->getType());
Yaxun Liu402804b2016-12-15 08:09:08 +00007807 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007808 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007809
John McCall45d55e42010-05-07 21:00:08 +00007810 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007811 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007812 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007813 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007814 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007815 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007816 if (E->isExpressibleAsConstantInitializer())
7817 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007818 if (Info.noteFailure())
7819 EvaluateIgnoredValue(Info, E->getSubExpr());
7820 return Error(E);
7821 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007822 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007823 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007824 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007825 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007826 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007827 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007828 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007829 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007830 }
Richard Smithd62306a2011-11-10 06:34:14 +00007831 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007832 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007833 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007834 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007835 if (!Info.CurrentCall->This) {
7836 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007837 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007838 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007839 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007840 return false;
7841 }
Richard Smithd62306a2011-11-10 06:34:14 +00007842 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007843 // If we are inside a lambda's call operator, the 'this' expression refers
7844 // to the enclosing '*this' object (either by value or reference) which is
7845 // either copied into the closure object's field that represents the '*this'
7846 // or refers to '*this'.
7847 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7848 // Update 'Result' to refer to the data member/field of the closure object
7849 // that represents the '*this' capture.
7850 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007851 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007852 return false;
7853 // If we captured '*this' by reference, replace the field with its referent.
7854 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7855 ->isPointerType()) {
7856 APValue RVal;
7857 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7858 RVal))
7859 return false;
7860
7861 Result.setFrom(Info.Ctx, RVal);
7862 }
7863 }
Richard Smithd62306a2011-11-10 06:34:14 +00007864 return true;
7865 }
John McCallc07a0c72011-02-17 10:25:35 +00007866
Richard Smithda1b4342019-09-27 01:26:47 +00007867 bool VisitCXXNewExpr(const CXXNewExpr *E);
7868
Eric Fiselier708afb52019-05-16 21:04:15 +00007869 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7870 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7871 APValue LValResult = E->EvaluateInContext(
7872 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7873 Result.setFrom(Info.Ctx, LValResult);
7874 return true;
7875 }
7876
Eli Friedman449fe542009-03-23 04:56:01 +00007877 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007878};
Chris Lattner05706e882008-07-11 18:11:29 +00007879} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007880
George Burgess IVf9013bf2017-02-10 22:52:29 +00007881static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7882 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007883 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007884 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007885}
7886
John McCall45d55e42010-05-07 21:00:08 +00007887bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007888 if (E->getOpcode() != BO_Add &&
7889 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007890 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007891
Chris Lattner05706e882008-07-11 18:11:29 +00007892 const Expr *PExp = E->getLHS();
7893 const Expr *IExp = E->getRHS();
7894 if (IExp->getType()->isPointerType())
7895 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007896
George Burgess IVf9013bf2017-02-10 22:52:29 +00007897 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007898 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007899 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007900
John McCall45d55e42010-05-07 21:00:08 +00007901 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007902 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007903 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007904
Richard Smith96e0c102011-11-04 02:25:55 +00007905 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007906 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007907
Ted Kremenek28831752012-08-23 20:46:57 +00007908 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007909 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007910}
Eli Friedman9a156e52008-11-12 09:44:48 +00007911
John McCall45d55e42010-05-07 21:00:08 +00007912bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007913 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007914}
Mike Stump11289f42009-09-09 15:08:12 +00007915
Richard Smith81dfef92018-07-11 00:29:05 +00007916bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7917 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007918
Eli Friedman847a2bc2009-12-27 05:43:15 +00007919 switch (E->getCastKind()) {
7920 default:
7921 break;
John McCalle3027922010-08-25 11:45:40 +00007922 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007923 case CK_CPointerToObjCPointerCast:
7924 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007925 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007926 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007927 if (!Visit(SubExpr))
7928 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007929 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7930 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7931 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007932 if (!E->getType()->isVoidPointerType()) {
Richard Smith19ad5232019-10-03 00:39:33 +00007933 if (!Result.InvalidBase && !Result.Designator.Invalid &&
7934 !Result.IsNullPtr &&
7935 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
7936 E->getType()->getPointeeType()) &&
7937 Info.getStdAllocatorCaller("allocate")) {
7938 // Inside a call to std::allocator::allocate and friends, we permit
7939 // casting from void* back to cv1 T* for a pointer that points to a
7940 // cv2 T.
7941 } else {
7942 Result.Designator.setInvalid();
7943 if (SubExpr->getType()->isVoidPointerType())
7944 CCEDiag(E, diag::note_constexpr_invalid_cast)
7945 << 3 << SubExpr->getType();
7946 else
7947 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7948 }
Richard Smithff07af12011-12-12 19:10:03 +00007949 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007950 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7951 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007952 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007953
Anders Carlsson18275092010-10-31 20:41:46 +00007954 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007955 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007956 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007957 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007958 if (!Result.Base && Result.Offset.isZero())
7959 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007960
Richard Smithd62306a2011-11-10 06:34:14 +00007961 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007962 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007963 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7964 castAs<PointerType>()->getPointeeType(),
7965 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007966
Richard Smith027bf112011-11-17 22:56:20 +00007967 case CK_BaseToDerived:
7968 if (!Visit(E->getSubExpr()))
7969 return false;
7970 if (!Result.Base && Result.Offset.isZero())
7971 return true;
7972 return HandleBaseToDerivedCast(Info, E, Result);
7973
Richard Smith7bd54ab2019-05-15 20:22:21 +00007974 case CK_Dynamic:
7975 if (!Visit(E->getSubExpr()))
7976 return false;
7977 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7978
Richard Smith0b0a0b62011-10-29 20:57:55 +00007979 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007980 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007981 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007982
John McCalle3027922010-08-25 11:45:40 +00007983 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007984 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7985
Richard Smith2e312c82012-03-03 22:46:17 +00007986 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007987 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007988 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007989
John McCall45d55e42010-05-07 21:00:08 +00007990 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007991 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7992 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007993 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007994 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007995 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007996 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007997 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007998 return true;
7999 } else {
8000 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00008001 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00008002 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00008003 }
8004 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00008005
8006 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00008007 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00008008 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00008009 return false;
8010 } else {
Richard Smith457226e2019-09-23 03:48:44 +00008011 APValue &Value = Info.CurrentCall->createTemporary(
8012 SubExpr, SubExpr->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008013 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00008014 return false;
8015 }
Richard Smith96e0c102011-11-04 02:25:55 +00008016 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00008017 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8018 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00008019 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00008020 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00008021 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00008022 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00008023 }
Richard Smithdd785442011-10-31 20:57:44 +00008024
John McCalle3027922010-08-25 11:45:40 +00008025 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00008026 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00008027
8028 case CK_LValueToRValue: {
8029 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00008030 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00008031 return false;
8032
8033 APValue RVal;
8034 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8035 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8036 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00008037 return InvalidBaseOK &&
8038 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00008039 return Success(RVal, E);
8040 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008041 }
8042
Richard Smith11562c52011-10-28 17:51:58 +00008043 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00008044}
Chris Lattner05706e882008-07-11 18:11:29 +00008045
Richard Smith6822bd72018-10-26 19:26:45 +00008046static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8047 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008048 // C++ [expr.alignof]p3:
8049 // When alignof is applied to a reference type, the result is the
8050 // alignment of the referenced type.
8051 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8052 T = Ref->getPointeeType();
8053
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00008054 if (T.getQualifiers().hasUnaligned())
8055 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00008056
8057 const bool AlignOfReturnsPreferred =
8058 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8059
8060 // __alignof is defined to return the preferred alignment.
8061 // Before 8, clang returned the preferred alignment for alignof and _Alignof
8062 // as well.
8063 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8064 return Info.Ctx.toCharUnitsFromBits(
8065 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8066 // alignof and _Alignof are defined to return the ABI alignment.
8067 else if (ExprKind == UETT_AlignOf)
8068 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8069 else
8070 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00008071}
8072
Richard Smith6822bd72018-10-26 19:26:45 +00008073static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8074 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008075 E = E->IgnoreParens();
8076
8077 // The kinds of expressions that we have special-case logic here for
8078 // should be kept up to date with the special checks for those
8079 // expressions in Sema.
8080
8081 // alignof decl is always accepted, even if it doesn't make sense: we default
8082 // to 1 in those cases.
8083 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8084 return Info.Ctx.getDeclAlign(DRE->getDecl(),
8085 /*RefAsPointee*/true);
8086
8087 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8088 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8089 /*RefAsPointee*/true);
8090
Richard Smith6822bd72018-10-26 19:26:45 +00008091 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008092}
8093
George Burgess IVe3763372016-12-22 02:50:20 +00008094// To be clear: this happily visits unsupported builtins. Better name welcomed.
8095bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8096 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8097 return true;
8098
George Burgess IVf9013bf2017-02-10 22:52:29 +00008099 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00008100 return false;
8101
8102 Result.setInvalid(E);
8103 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00008104 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00008105 return true;
8106}
8107
Peter Collingbournee9200682011-05-13 03:29:01 +00008108bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008109 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00008110 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00008111
Richard Smith6328cbd2016-11-16 00:57:23 +00008112 if (unsigned BuiltinOp = E->getBuiltinCallee())
8113 return VisitBuiltinCallExpr(E, BuiltinOp);
8114
George Burgess IVe3763372016-12-22 02:50:20 +00008115 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008116}
8117
8118bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8119 unsigned BuiltinOp) {
8120 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00008121 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00008122 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008123 case Builtin::BI__builtin_assume_aligned: {
8124 // We need to be very careful here because: if the pointer does not have the
8125 // asserted alignment, then the behavior is undefined, and undefined
8126 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00008127 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00008128 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00008129
Hal Finkel0dd05d42014-10-03 17:18:37 +00008130 LValue OffsetResult(Result);
8131 APSInt Alignment;
8132 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
8133 return false;
Richard Smith642a2362017-01-30 23:30:26 +00008134 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00008135
8136 if (E->getNumArgs() > 2) {
8137 APSInt Offset;
8138 if (!EvaluateInteger(E->getArg(2), Offset, Info))
8139 return false;
8140
Richard Smith642a2362017-01-30 23:30:26 +00008141 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008142 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8143 }
8144
8145 // If there is a base object, then it must have the correct alignment.
8146 if (OffsetResult.Base) {
8147 CharUnits BaseAlignment;
8148 if (const ValueDecl *VD =
8149 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
8150 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00008151 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
8152 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008153 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00008154 BaseAlignment = GetAlignOfType(
8155 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008156 }
8157
8158 if (BaseAlignment < Align) {
8159 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00008160 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00008161 CCEDiag(E->getArg(0),
8162 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00008163 << (unsigned)BaseAlignment.getQuantity()
8164 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008165 return false;
8166 }
8167 }
8168
8169 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008170 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008171 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008172
Richard Smith642a2362017-01-30 23:30:26 +00008173 (OffsetResult.Base
8174 ? CCEDiag(E->getArg(0),
8175 diag::note_constexpr_baa_insufficient_alignment) << 1
8176 : CCEDiag(E->getArg(0),
8177 diag::note_constexpr_baa_value_insufficient_alignment))
8178 << (int)OffsetResult.Offset.getQuantity()
8179 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008180 return false;
8181 }
8182
8183 return true;
8184 }
Richard Smith19ad5232019-10-03 00:39:33 +00008185 case Builtin::BI__builtin_operator_new:
8186 return HandleOperatorNewCall(Info, E, Result);
Eric Fiselier26187502018-12-14 21:11:28 +00008187 case Builtin::BI__builtin_launder:
8188 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00008189 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008190 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00008191 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008192 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00008193 if (Info.getLangOpts().CPlusPlus11)
8194 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8195 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008196 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00008197 else
8198 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008199 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00008200 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008201 case Builtin::BI__builtin_wcschr:
8202 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00008203 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008204 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00008205 if (!Visit(E->getArg(0)))
8206 return false;
8207 APSInt Desired;
8208 if (!EvaluateInteger(E->getArg(1), Desired, Info))
8209 return false;
8210 uint64_t MaxLength = uint64_t(-1);
8211 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008212 BuiltinOp != Builtin::BIwcschr &&
8213 BuiltinOp != Builtin::BI__builtin_strchr &&
8214 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00008215 APSInt N;
8216 if (!EvaluateInteger(E->getArg(2), N, Info))
8217 return false;
8218 MaxLength = N.getExtValue();
8219 }
Hubert Tong147b7432018-12-12 16:53:43 +00008220 // We cannot find the value if there are no candidates to match against.
8221 if (MaxLength == 0u)
8222 return ZeroInitialization(E);
8223 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8224 Result.Designator.Invalid)
8225 return false;
8226 QualType CharTy = Result.Designator.getType(Info.Ctx);
8227 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8228 BuiltinOp == Builtin::BI__builtin_memchr;
8229 assert(IsRawByte ||
8230 Info.Ctx.hasSameUnqualifiedType(
8231 CharTy, E->getArg(0)->getType()->getPointeeType()));
8232 // Pointers to const void may point to objects of incomplete type.
8233 if (IsRawByte && CharTy->isIncompleteType()) {
8234 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8235 return false;
8236 }
8237 // Give up on byte-oriented matching against multibyte elements.
8238 // FIXME: We can compare the bytes in the correct order.
8239 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8240 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008241 // Figure out what value we're actually looking for (after converting to
8242 // the corresponding unsigned type if necessary).
8243 uint64_t DesiredVal;
8244 bool StopAtNull = false;
8245 switch (BuiltinOp) {
8246 case Builtin::BIstrchr:
8247 case Builtin::BI__builtin_strchr:
8248 // strchr compares directly to the passed integer, and therefore
8249 // always fails if given an int that is not a char.
8250 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8251 E->getArg(1)->getType(),
8252 Desired),
8253 Desired))
8254 return ZeroInitialization(E);
8255 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008256 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008257 case Builtin::BImemchr:
8258 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00008259 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008260 // memchr compares by converting both sides to unsigned char. That's also
8261 // correct for strchr if we get this far (to cope with plain char being
8262 // unsigned in the strchr case).
8263 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8264 break;
Richard Smithe9507952016-11-12 01:39:56 +00008265
Richard Smith8110c9d2016-11-29 19:45:17 +00008266 case Builtin::BIwcschr:
8267 case Builtin::BI__builtin_wcschr:
8268 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008269 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008270 case Builtin::BIwmemchr:
8271 case Builtin::BI__builtin_wmemchr:
8272 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8273 DesiredVal = Desired.getZExtValue();
8274 break;
8275 }
Richard Smithe9507952016-11-12 01:39:56 +00008276
8277 for (; MaxLength; --MaxLength) {
8278 APValue Char;
8279 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8280 !Char.isInt())
8281 return false;
8282 if (Char.getInt().getZExtValue() == DesiredVal)
8283 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00008284 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00008285 break;
8286 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8287 return false;
8288 }
8289 // Not found: return nullptr.
8290 return ZeroInitialization(E);
8291 }
8292
Richard Smith06f71b52018-08-04 00:57:17 +00008293 case Builtin::BImemcpy:
8294 case Builtin::BImemmove:
8295 case Builtin::BIwmemcpy:
8296 case Builtin::BIwmemmove:
8297 if (Info.getLangOpts().CPlusPlus11)
8298 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8299 << /*isConstexpr*/0 << /*isConstructor*/0
8300 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8301 else
8302 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8303 LLVM_FALLTHROUGH;
8304 case Builtin::BI__builtin_memcpy:
8305 case Builtin::BI__builtin_memmove:
8306 case Builtin::BI__builtin_wmemcpy:
8307 case Builtin::BI__builtin_wmemmove: {
8308 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8309 BuiltinOp == Builtin::BIwmemmove ||
8310 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8311 BuiltinOp == Builtin::BI__builtin_wmemmove;
8312 bool Move = BuiltinOp == Builtin::BImemmove ||
8313 BuiltinOp == Builtin::BIwmemmove ||
8314 BuiltinOp == Builtin::BI__builtin_memmove ||
8315 BuiltinOp == Builtin::BI__builtin_wmemmove;
8316
8317 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00008318 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00008319 return false;
8320 LValue Dest = Result;
8321
8322 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00008323 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00008324 return false;
8325
8326 APSInt N;
8327 if (!EvaluateInteger(E->getArg(2), N, Info))
8328 return false;
8329 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8330
8331 // If the size is zero, we treat this as always being a valid no-op.
8332 // (Even if one of the src and dest pointers is null.)
8333 if (!N)
8334 return true;
8335
Richard Smith128719c2018-09-13 22:47:33 +00008336 // Otherwise, if either of the operands is null, we can't proceed. Don't
8337 // try to determine the type of the copied objects, because there aren't
8338 // any.
8339 if (!Src.Base || !Dest.Base) {
8340 APValue Val;
8341 (!Src.Base ? Src : Dest).moveInto(Val);
8342 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8343 << Move << WChar << !!Src.Base
8344 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8345 return false;
8346 }
8347 if (Src.Designator.Invalid || Dest.Designator.Invalid)
8348 return false;
8349
Richard Smith06f71b52018-08-04 00:57:17 +00008350 // We require that Src and Dest are both pointers to arrays of
8351 // trivially-copyable type. (For the wide version, the designator will be
8352 // invalid if the designated object is not a wchar_t.)
8353 QualType T = Dest.Designator.getType(Info.Ctx);
8354 QualType SrcT = Src.Designator.getType(Info.Ctx);
8355 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8356 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8357 return false;
8358 }
Petr Pavlued083f22018-10-04 09:25:44 +00008359 if (T->isIncompleteType()) {
8360 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8361 return false;
8362 }
Richard Smith06f71b52018-08-04 00:57:17 +00008363 if (!T.isTriviallyCopyableType(Info.Ctx)) {
8364 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8365 return false;
8366 }
8367
8368 // Figure out how many T's we're copying.
8369 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8370 if (!WChar) {
8371 uint64_t Remainder;
8372 llvm::APInt OrigN = N;
8373 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8374 if (Remainder) {
8375 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8376 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8377 << (unsigned)TSize;
8378 return false;
8379 }
8380 }
8381
8382 // Check that the copying will remain within the arrays, just so that we
8383 // can give a more meaningful diagnostic. This implicitly also checks that
8384 // N fits into 64 bits.
8385 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8386 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8387 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8388 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8389 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8390 << N.toString(10, /*Signed*/false);
8391 return false;
8392 }
8393 uint64_t NElems = N.getZExtValue();
8394 uint64_t NBytes = NElems * TSize;
8395
8396 // Check for overlap.
8397 int Direction = 1;
8398 if (HasSameBase(Src, Dest)) {
8399 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8400 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8401 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8402 // Dest is inside the source region.
8403 if (!Move) {
8404 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8405 return false;
8406 }
8407 // For memmove and friends, copy backwards.
8408 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8409 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8410 return false;
8411 Direction = -1;
8412 } else if (!Move && SrcOffset >= DestOffset &&
8413 SrcOffset - DestOffset < NBytes) {
8414 // Src is inside the destination region for memcpy: invalid.
8415 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8416 return false;
8417 }
8418 }
8419
8420 while (true) {
8421 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00008422 // FIXME: Set WantObjectRepresentation to true if we're copying a
8423 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00008424 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8425 !handleAssignment(Info, E, Dest, T, Val))
8426 return false;
8427 // Do not iterate past the last element; if we're copying backwards, that
8428 // might take us off the start of the array.
8429 if (--NElems == 0)
8430 return true;
8431 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8432 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8433 return false;
8434 }
8435 }
8436
Richard Smith6cbd65d2013-07-11 02:27:57 +00008437 default:
Richard Smith19ad5232019-10-03 00:39:33 +00008438 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00008439 }
Richard Smith19ad5232019-10-03 00:39:33 +00008440
8441 return visitNonBuiltinCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008442}
Chris Lattner05706e882008-07-11 18:11:29 +00008443
Richard Smithda1b4342019-09-27 01:26:47 +00008444static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8445 APValue &Result, const InitListExpr *ILE,
8446 QualType AllocType);
8447
8448bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
Richard Smith62a95562019-09-27 01:26:49 +00008449 if (!Info.getLangOpts().CPlusPlus2a)
8450 Info.CCEDiag(E, diag::note_constexpr_new);
8451
Richard Smithda1b4342019-09-27 01:26:47 +00008452 // We cannot speculatively evaluate a delete expression.
8453 if (Info.SpeculativeEvaluationDepth)
8454 return false;
8455
8456 FunctionDecl *OperatorNew = E->getOperatorNew();
Richard Smithb5426022019-10-03 00:39:35 +00008457
8458 bool IsNothrow = false;
8459 bool IsPlacement = false;
8460 if (OperatorNew->isReservedGlobalPlacementOperator() &&
8461 Info.CurrentCall->isStdFunction() && !E->isArray()) {
8462 // FIXME Support array placement new.
8463 assert(E->getNumPlacementArgs() == 1);
8464 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8465 return false;
8466 if (Result.Designator.Invalid)
8467 return false;
8468 IsPlacement = true;
8469 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
Richard Smithda1b4342019-09-27 01:26:47 +00008470 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8471 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8472 return false;
Richard Smithb5426022019-10-03 00:39:35 +00008473 } else if (E->getNumPlacementArgs()) {
Richard Smith62a95562019-09-27 01:26:49 +00008474 // The only new-placement list we support is of the form (std::nothrow).
8475 //
8476 // FIXME: There is no restriction on this, but it's not clear that any
8477 // other form makes any sense. We get here for cases such as:
8478 //
8479 // new (std::align_val_t{N}) X(int)
8480 //
8481 // (which should presumably be valid only if N is a multiple of
8482 // alignof(int), and in any case can't be deallocated unless N is
8483 // alignof(X) and X has new-extended alignment).
8484 if (E->getNumPlacementArgs() != 1 ||
8485 !E->getPlacementArg(0)->getType()->isNothrowT())
8486 return Error(E, diag::note_constexpr_new_placement);
8487
8488 LValue Nothrow;
8489 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8490 return false;
8491 IsNothrow = true;
8492 }
Richard Smithda1b4342019-09-27 01:26:47 +00008493
8494 const Expr *Init = E->getInitializer();
8495 const InitListExpr *ResizedArrayILE = nullptr;
8496
8497 QualType AllocType = E->getAllocatedType();
8498 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8499 const Expr *Stripped = *ArraySize;
8500 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8501 Stripped = ICE->getSubExpr())
8502 if (ICE->getCastKind() != CK_NoOp &&
8503 ICE->getCastKind() != CK_IntegralCast)
8504 break;
8505
8506 llvm::APSInt ArrayBound;
8507 if (!EvaluateInteger(Stripped, ArrayBound, Info))
8508 return false;
8509
8510 // C++ [expr.new]p9:
8511 // The expression is erroneous if:
8512 // -- [...] its value before converting to size_t [or] applying the
8513 // second standard conversion sequence is less than zero
8514 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
Richard Smith62a95562019-09-27 01:26:49 +00008515 if (IsNothrow)
8516 return ZeroInitialization(E);
8517
Richard Smithda1b4342019-09-27 01:26:47 +00008518 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8519 << ArrayBound << (*ArraySize)->getSourceRange();
8520 return false;
8521 }
8522
8523 // -- its value is such that the size of the allocated object would
8524 // exceed the implementation-defined limit
8525 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8526 ArrayBound) >
8527 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
Richard Smith62a95562019-09-27 01:26:49 +00008528 if (IsNothrow)
8529 return ZeroInitialization(E);
8530
Richard Smithda1b4342019-09-27 01:26:47 +00008531 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8532 << ArrayBound << (*ArraySize)->getSourceRange();
8533 return false;
8534 }
8535
8536 // -- the new-initializer is a braced-init-list and the number of
8537 // array elements for which initializers are provided [...]
8538 // exceeds the number of elements to initialize
8539 if (Init) {
8540 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8541 assert(CAT && "unexpected type for array initializer");
8542
8543 unsigned Bits =
8544 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8545 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8546 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8547 if (InitBound.ugt(AllocBound)) {
Richard Smith62a95562019-09-27 01:26:49 +00008548 if (IsNothrow)
8549 return ZeroInitialization(E);
8550
Richard Smithda1b4342019-09-27 01:26:47 +00008551 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8552 << AllocBound.toString(10, /*Signed=*/false)
8553 << InitBound.toString(10, /*Signed=*/false)
8554 << (*ArraySize)->getSourceRange();
8555 return false;
8556 }
8557
8558 // If the sizes differ, we must have an initializer list, and we need
8559 // special handling for this case when we initialize.
8560 if (InitBound != AllocBound)
8561 ResizedArrayILE = cast<InitListExpr>(Init);
8562 }
8563
Richard Smith772e2662019-10-04 01:25:59 +00008564 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
Richard Smithda1b4342019-09-27 01:26:47 +00008565 ArrayType::Normal, 0);
8566 } else {
8567 assert(!AllocType->isArrayType() &&
8568 "array allocation with non-array new");
8569 }
8570
Richard Smithb5426022019-10-03 00:39:35 +00008571 APValue *Val;
8572 if (IsPlacement) {
8573 AccessKinds AK = AK_Construct;
8574 struct FindObjectHandler {
8575 EvalInfo &Info;
8576 const Expr *E;
8577 QualType AllocType;
8578 const AccessKinds AccessKind;
8579 APValue *Value;
8580
8581 typedef bool result_type;
8582 bool failed() { return false; }
8583 bool found(APValue &Subobj, QualType SubobjType) {
8584 // FIXME: Reject the cases where [basic.life]p8 would not permit the
8585 // old name of the object to be used to name the new object.
8586 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8587 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8588 SubobjType << AllocType;
8589 return false;
8590 }
8591 Value = &Subobj;
8592 return true;
8593 }
8594 bool found(APSInt &Value, QualType SubobjType) {
8595 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8596 return false;
8597 }
8598 bool found(APFloat &Value, QualType SubobjType) {
8599 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8600 return false;
8601 }
8602 } Handler = {Info, E, AllocType, AK, nullptr};
8603
8604 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8605 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8606 return false;
8607
8608 Val = Handler.Value;
8609
8610 // [basic.life]p1:
8611 // The lifetime of an object o of type T ends when [...] the storage
8612 // which the object occupies is [...] reused by an object that is not
8613 // nested within o (6.6.2).
8614 *Val = APValue();
8615 } else {
8616 // Perform the allocation and obtain a pointer to the resulting object.
8617 Val = Info.createHeapAlloc(E, AllocType, Result);
8618 if (!Val)
8619 return false;
8620 }
Richard Smithda1b4342019-09-27 01:26:47 +00008621
8622 if (ResizedArrayILE) {
8623 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8624 AllocType))
8625 return false;
8626 } else if (Init) {
8627 if (!EvaluateInPlace(*Val, Info, Result, Init))
8628 return false;
8629 } else {
8630 *Val = getDefaultInitValue(AllocType);
8631 }
8632
8633 // Array new returns a pointer to the first element, not a pointer to the
8634 // array.
8635 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8636 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8637
8638 return true;
8639}
Chris Lattner05706e882008-07-11 18:11:29 +00008640//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008641// Member Pointer Evaluation
8642//===----------------------------------------------------------------------===//
8643
8644namespace {
8645class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008646 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00008647 MemberPtr &Result;
8648
8649 bool Success(const ValueDecl *D) {
8650 Result = MemberPtr(D);
8651 return true;
8652 }
8653public:
8654
8655 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8656 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8657
Richard Smith2e312c82012-03-03 22:46:17 +00008658 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008659 Result.setFrom(V);
8660 return true;
8661 }
Richard Smithfddd3842011-12-30 21:15:51 +00008662 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00008663 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00008664 }
8665
8666 bool VisitCastExpr(const CastExpr *E);
8667 bool VisitUnaryAddrOf(const UnaryOperator *E);
8668};
8669} // end anonymous namespace
8670
8671static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8672 EvalInfo &Info) {
8673 assert(E->isRValue() && E->getType()->isMemberPointerType());
8674 return MemberPointerExprEvaluator(Info, Result).Visit(E);
8675}
8676
8677bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8678 switch (E->getCastKind()) {
8679 default:
8680 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8681
8682 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00008683 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008684 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00008685
8686 case CK_BaseToDerivedMemberPointer: {
8687 if (!Visit(E->getSubExpr()))
8688 return false;
8689 if (E->path_empty())
8690 return true;
8691 // Base-to-derived member pointer casts store the path in derived-to-base
8692 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8693 // the wrong end of the derived->base arc, so stagger the path by one class.
8694 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8695 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8696 PathI != PathE; ++PathI) {
8697 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8698 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8699 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008700 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008701 }
8702 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8703 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008704 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008705 return true;
8706 }
8707
8708 case CK_DerivedToBaseMemberPointer:
8709 if (!Visit(E->getSubExpr()))
8710 return false;
8711 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8712 PathE = E->path_end(); PathI != PathE; ++PathI) {
8713 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8714 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8715 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008716 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008717 }
8718 return true;
8719 }
8720}
8721
8722bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8723 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8724 // member can be formed.
8725 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8726}
8727
8728//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00008729// Record Evaluation
8730//===----------------------------------------------------------------------===//
8731
8732namespace {
8733 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008734 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008735 const LValue &This;
8736 APValue &Result;
8737 public:
8738
8739 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8740 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8741
Richard Smith2e312c82012-03-03 22:46:17 +00008742 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00008743 Result = V;
8744 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00008745 }
Richard Smithb8348f52016-05-12 22:16:28 +00008746 bool ZeroInitialization(const Expr *E) {
8747 return ZeroInitialization(E, E->getType());
8748 }
8749 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00008750
Richard Smith52a980a2015-08-28 02:43:42 +00008751 bool VisitCallExpr(const CallExpr *E) {
8752 return handleCallExpr(E, Result, &This);
8753 }
Richard Smithe97cbd72011-11-11 04:05:33 +00008754 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008755 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008756 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8757 return VisitCXXConstructExpr(E, E->getType());
8758 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008759 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00008760 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008761 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00008762 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008763 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008764 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008765}
Richard Smithd62306a2011-11-10 06:34:14 +00008766
Richard Smithfddd3842011-12-30 21:15:51 +00008767/// Perform zero-initialization on an object of non-union class type.
8768/// C++11 [dcl.init]p5:
8769/// To zero-initialize an object or reference of type T means:
8770/// [...]
8771/// -- if T is a (possibly cv-qualified) non-union class type,
8772/// each non-static data member and each base-class subobject is
8773/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00008774static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8775 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00008776 const LValue &This, APValue &Result) {
8777 assert(!RD->isUnion() && "Expected non-union class type");
8778 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8779 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00008780 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00008781
John McCalld7bca762012-05-01 00:38:49 +00008782 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008783 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8784
8785 if (CD) {
8786 unsigned Index = 0;
8787 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00008788 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00008789 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8790 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008791 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8792 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00008793 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00008794 Result.getStructBase(Index)))
8795 return false;
8796 }
8797 }
8798
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008799 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00008800 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00008801 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00008802 continue;
8803
8804 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008805 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008806 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008807
David Blaikie2d7c57e2012-04-30 02:36:29 +00008808 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008809 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00008810 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00008811 return false;
8812 }
8813
8814 return true;
8815}
8816
Richard Smithb8348f52016-05-12 22:16:28 +00008817bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8818 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008819 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008820 if (RD->isUnion()) {
8821 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8822 // object's first non-static named data member is zero-initialized
8823 RecordDecl::field_iterator I = RD->field_begin();
8824 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00008825 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00008826 return true;
8827 }
8828
8829 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00008830 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00008831 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00008832 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00008833 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008834 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00008835 }
8836
Richard Smith5d108602012-02-17 00:44:16 +00008837 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008838 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00008839 return false;
8840 }
8841
Richard Smitha8105bc2012-01-06 16:39:00 +00008842 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00008843}
8844
Richard Smithe97cbd72011-11-11 04:05:33 +00008845bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8846 switch (E->getCastKind()) {
8847 default:
8848 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8849
8850 case CK_ConstructorConversion:
8851 return Visit(E->getSubExpr());
8852
8853 case CK_DerivedToBase:
8854 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00008855 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008856 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00008857 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008858 if (!DerivedObject.isStruct())
8859 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00008860
8861 // Derived-to-base rvalue conversion: just slice off the derived part.
8862 APValue *Value = &DerivedObject;
8863 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8864 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8865 PathE = E->path_end(); PathI != PathE; ++PathI) {
8866 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
8867 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8868 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8869 RD = Base;
8870 }
8871 Result = *Value;
8872 return true;
8873 }
8874 }
8875}
8876
Richard Smithd62306a2011-11-10 06:34:14 +00008877bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00008878 if (E->isTransparent())
8879 return Visit(E->getInit(0));
8880
Richard Smithd62306a2011-11-10 06:34:14 +00008881 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008882 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008883 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008884 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8885
8886 EvalInfo::EvaluatingConstructorRAII EvalObj(
8887 Info,
8888 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8889 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00008890
8891 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00008892 const FieldDecl *Field = E->getInitializedFieldInUnion();
8893 Result = APValue(Field);
8894 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00008895 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00008896
8897 // If the initializer list for a union does not contain any elements, the
8898 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00008899 // FIXME: The element should be initialized from an initializer list.
8900 // Is this difference ever observable for initializer lists which
8901 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00008902 ImplicitValueInitExpr VIE(Field->getType());
8903 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8904
Richard Smithd62306a2011-11-10 06:34:14 +00008905 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008906 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8907 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00008908
8909 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8910 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8911 isa<CXXDefaultInitExpr>(InitExpr));
8912
Richard Smithb228a862012-02-15 02:18:13 +00008913 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00008914 }
8915
Richard Smithe637cbe2019-05-21 23:15:18 +00008916 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00008917 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8918 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00008919 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00008920 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00008921
8922 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008923 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00008924 for (const auto &Base : CXXRD->bases()) {
8925 assert(ElementNo < E->getNumInits() && "missing init for base class");
8926 const Expr *Init = E->getInit(ElementNo);
8927
8928 LValue Subobject = This;
8929 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8930 return false;
8931
8932 APValue &FieldVal = Result.getStructBase(ElementNo);
8933 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008934 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00008935 return false;
8936 Success = false;
8937 }
8938 ++ElementNo;
8939 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008940
8941 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00008942 }
8943
8944 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008945 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008946 // Anonymous bit-fields are not considered members of the class for
8947 // purposes of aggregate initialization.
8948 if (Field->isUnnamedBitfield())
8949 continue;
8950
8951 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00008952
Richard Smith253c2a32012-01-27 01:14:48 +00008953 bool HaveInit = ElementNo < E->getNumInits();
8954
8955 // FIXME: Diagnostics here should point to the end of the initializer
8956 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00008957 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008958 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008959 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008960
8961 // Perform an implicit value-initialization for members beyond the end of
8962 // the initializer list.
8963 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00008964 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00008965
Richard Smith852c9db2013-04-20 22:23:05 +00008966 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8967 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8968 isa<CXXDefaultInitExpr>(Init));
8969
Richard Smith49ca8aa2013-08-06 07:09:20 +00008970 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8971 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8972 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008973 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00008974 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00008975 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008976 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00008977 }
8978 }
8979
Richard Smith253c2a32012-01-27 01:14:48 +00008980 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00008981}
8982
Richard Smithb8348f52016-05-12 22:16:28 +00008983bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8984 QualType T) {
8985 // Note that E's type is not necessarily the type of our class here; we might
8986 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00008987 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00008988 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8989
Richard Smithfddd3842011-12-30 21:15:51 +00008990 bool ZeroInit = E->requiresZeroInitialization();
8991 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00008992 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00008993 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00008994 return true;
8995
Richard Smithc667cdc2019-09-18 17:37:44 +00008996 if (ZeroInit)
8997 return ZeroInitialization(E, T);
8998
8999 Result = getDefaultInitValue(T);
9000 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00009001 }
9002
Craig Topper36250ad2014-05-12 05:36:57 +00009003 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00009004 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00009005
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00009006 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00009007 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009008
Richard Smith1bc5c2c2012-01-10 04:32:03 +00009009 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00009010 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00009011 if (const MaterializeTemporaryExpr *ME
9012 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9013 return Visit(ME->GetTemporaryExpr());
9014
Richard Smithb8348f52016-05-12 22:16:28 +00009015 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00009016 return false;
9017
Craig Topper5fc8fc22014-08-27 06:28:36 +00009018 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00009019 return HandleConstructorCall(E, This, Args,
9020 cast<CXXConstructorDecl>(Definition), Info,
9021 Result);
9022}
9023
9024bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9025 const CXXInheritedCtorInitExpr *E) {
9026 if (!Info.CurrentCall) {
9027 assert(Info.checkingPotentialConstantExpression());
9028 return false;
9029 }
9030
9031 const CXXConstructorDecl *FD = E->getConstructor();
9032 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9033 return false;
9034
9035 const FunctionDecl *Definition = nullptr;
9036 auto Body = FD->getBody(Definition);
9037
9038 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9039 return false;
9040
9041 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009042 cast<CXXConstructorDecl>(Definition), Info,
9043 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00009044}
9045
Richard Smithcc1b96d2013-06-12 22:31:48 +00009046bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9047 const CXXStdInitializerListExpr *E) {
9048 const ConstantArrayType *ArrayType =
9049 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9050
9051 LValue Array;
9052 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9053 return false;
9054
9055 // Get a pointer to the first element of the array.
9056 Array.addArray(Info, E, ArrayType);
9057
9058 // FIXME: Perform the checks on the field types in SemaInit.
9059 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9060 RecordDecl::field_iterator Field = Record->field_begin();
9061 if (Field == Record->field_end())
9062 return Error(E);
9063
9064 // Start pointer.
9065 if (!Field->getType()->isPointerType() ||
9066 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9067 ArrayType->getElementType()))
9068 return Error(E);
9069
9070 // FIXME: What if the initializer_list type has base classes, etc?
9071 Result = APValue(APValue::UninitStruct(), 0, 2);
9072 Array.moveInto(Result.getStructField(0));
9073
9074 if (++Field == Record->field_end())
9075 return Error(E);
9076
9077 if (Field->getType()->isPointerType() &&
9078 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9079 ArrayType->getElementType())) {
9080 // End pointer.
9081 if (!HandleLValueArrayAdjustment(Info, E, Array,
9082 ArrayType->getElementType(),
9083 ArrayType->getSize().getZExtValue()))
9084 return false;
9085 Array.moveInto(Result.getStructField(1));
9086 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9087 // Length.
9088 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9089 else
9090 return Error(E);
9091
9092 if (++Field != Record->field_end())
9093 return Error(E);
9094
9095 return true;
9096}
9097
Faisal Valic72a08c2017-01-09 03:02:53 +00009098bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9099 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
Richard Smithda1b4342019-09-27 01:26:47 +00009100 if (ClosureClass->isInvalidDecl())
9101 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009102
Faisal Vali051e3a22017-02-16 04:12:21 +00009103 const size_t NumFields =
9104 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00009105
9106 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9107 E->capture_init_end()) &&
9108 "The number of lambda capture initializers should equal the number of "
9109 "fields within the closure type");
9110
Faisal Vali051e3a22017-02-16 04:12:21 +00009111 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9112 // Iterate through all the lambda's closure object's fields and initialize
9113 // them.
9114 auto *CaptureInitIt = E->capture_init_begin();
9115 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9116 bool Success = true;
9117 for (const auto *Field : ClosureClass->fields()) {
9118 assert(CaptureInitIt != E->capture_init_end());
9119 // Get the initializer for this field
9120 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00009121
Faisal Vali051e3a22017-02-16 04:12:21 +00009122 // If there is no initializer, either this is a VLA or an error has
9123 // occurred.
9124 if (!CurFieldInit)
9125 return Error(E);
9126
9127 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9128 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9129 if (!Info.keepEvaluatingAfterFailure())
9130 return false;
9131 Success = false;
9132 }
9133 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00009134 }
Faisal Vali051e3a22017-02-16 04:12:21 +00009135 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00009136}
9137
Richard Smithd62306a2011-11-10 06:34:14 +00009138static bool EvaluateRecord(const Expr *E, const LValue &This,
9139 APValue &Result, EvalInfo &Info) {
9140 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00009141 "can't evaluate expression as a record rvalue");
9142 return RecordExprEvaluator(Info, This, Result).Visit(E);
9143}
9144
9145//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00009146// Temporary Evaluation
9147//
9148// Temporaries are represented in the AST as rvalues, but generally behave like
9149// lvalues. The full-object of which the temporary is a subobject is implicitly
9150// materialized so that a reference can bind to it.
9151//===----------------------------------------------------------------------===//
9152namespace {
9153class TemporaryExprEvaluator
9154 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9155public:
9156 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00009157 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00009158
9159 /// Visit an expression which constructs the value of this temporary.
9160 bool VisitConstructExpr(const Expr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009161 APValue &Value =
9162 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00009163 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00009164 }
9165
9166 bool VisitCastExpr(const CastExpr *E) {
9167 switch (E->getCastKind()) {
9168 default:
9169 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9170
9171 case CK_ConstructorConversion:
9172 return VisitConstructExpr(E->getSubExpr());
9173 }
9174 }
9175 bool VisitInitListExpr(const InitListExpr *E) {
9176 return VisitConstructExpr(E);
9177 }
9178 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9179 return VisitConstructExpr(E);
9180 }
9181 bool VisitCallExpr(const CallExpr *E) {
9182 return VisitConstructExpr(E);
9183 }
Richard Smith513955c2014-12-17 19:24:30 +00009184 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9185 return VisitConstructExpr(E);
9186 }
Faisal Valic72a08c2017-01-09 03:02:53 +00009187 bool VisitLambdaExpr(const LambdaExpr *E) {
9188 return VisitConstructExpr(E);
9189 }
Richard Smith027bf112011-11-17 22:56:20 +00009190};
9191} // end anonymous namespace
9192
9193/// Evaluate an expression of record type as a temporary.
9194static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00009195 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00009196 return TemporaryExprEvaluator(Info, Result).Visit(E);
9197}
9198
9199//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009200// Vector Evaluation
9201//===----------------------------------------------------------------------===//
9202
9203namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009204 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009205 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00009206 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009207 public:
Mike Stump11289f42009-09-09 15:08:12 +00009208
Richard Smith2d406342011-10-22 21:10:00 +00009209 VectorExprEvaluator(EvalInfo &info, APValue &Result)
9210 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00009211
Craig Topper9798b932015-09-29 04:30:05 +00009212 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009213 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9214 // FIXME: remove this APValue copy.
9215 Result = APValue(V.data(), V.size());
9216 return true;
9217 }
Richard Smith2e312c82012-03-03 22:46:17 +00009218 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00009219 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00009220 Result = V;
9221 return true;
9222 }
Richard Smithfddd3842011-12-30 21:15:51 +00009223 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00009224
Richard Smith2d406342011-10-22 21:10:00 +00009225 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00009226 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00009227 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00009228 bool VisitInitListExpr(const InitListExpr *E);
9229 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009230 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00009231 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00009232 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009233 };
9234} // end anonymous namespace
9235
9236static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009237 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00009238 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009239}
9240
George Burgess IV533ff002015-12-11 00:23:35 +00009241bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009242 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00009243 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00009244
Richard Smith161f09a2011-12-06 22:44:34 +00009245 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00009246 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009247
Eli Friedmanc757de22011-03-25 00:43:55 +00009248 switch (E->getCastKind()) {
9249 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00009250 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00009251 if (SETy->isIntegerType()) {
9252 APSInt IntResult;
9253 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00009254 return false;
9255 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00009256 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00009257 APFloat FloatResult(0.0);
9258 if (!EvaluateFloat(SE, FloatResult, Info))
9259 return false;
9260 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00009261 } else {
Richard Smith2d406342011-10-22 21:10:00 +00009262 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009263 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00009264
9265 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00009266 SmallVector<APValue, 4> Elts(NElts, Val);
9267 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00009268 }
Eli Friedman803acb32011-12-22 03:51:45 +00009269 case CK_BitCast: {
9270 // Evaluate the operand into an APInt we can extract from.
9271 llvm::APInt SValInt;
9272 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9273 return false;
9274 // Extract the elements
9275 QualType EltTy = VTy->getElementType();
9276 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9277 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9278 SmallVector<APValue, 4> Elts;
9279 if (EltTy->isRealFloatingType()) {
9280 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00009281 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00009282 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00009283 FloatEltSize = 80;
9284 for (unsigned i = 0; i < NElts; i++) {
9285 llvm::APInt Elt;
9286 if (BigEndian)
9287 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9288 else
9289 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00009290 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00009291 }
9292 } else if (EltTy->isIntegerType()) {
9293 for (unsigned i = 0; i < NElts; i++) {
9294 llvm::APInt Elt;
9295 if (BigEndian)
9296 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9297 else
9298 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9299 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9300 }
9301 } else {
9302 return Error(E);
9303 }
9304 return Success(Elts, E);
9305 }
Eli Friedmanc757de22011-03-25 00:43:55 +00009306 default:
Richard Smith11562c52011-10-28 17:51:58 +00009307 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009308 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009309}
9310
Richard Smith2d406342011-10-22 21:10:00 +00009311bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009312VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009313 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009314 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00009315 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00009316
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009317 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009318 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009319
Eli Friedmanb9c71292012-01-03 23:24:20 +00009320 // The number of initializers can be less than the number of
9321 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00009322 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00009323 // should be initialized with zeroes.
9324 unsigned CountInits = 0, CountElts = 0;
9325 while (CountElts < NumElements) {
9326 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00009327 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00009328 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00009329 APValue v;
9330 if (!EvaluateVector(E->getInit(CountInits), v, Info))
9331 return Error(E);
9332 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00009333 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00009334 Elements.push_back(v.getVectorElt(j));
9335 CountElts += vlen;
9336 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009337 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009338 if (CountInits < NumInits) {
9339 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009340 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009341 } else // trailing integer zero.
9342 sInt = Info.Ctx.MakeIntValue(0, EltTy);
9343 Elements.push_back(APValue(sInt));
9344 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009345 } else {
9346 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009347 if (CountInits < NumInits) {
9348 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009349 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009350 } else // trailing float zero.
9351 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9352 Elements.push_back(APValue(f));
9353 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00009354 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00009355 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009356 }
Richard Smith2d406342011-10-22 21:10:00 +00009357 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009358}
9359
Richard Smith2d406342011-10-22 21:10:00 +00009360bool
Richard Smithfddd3842011-12-30 21:15:51 +00009361VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Simon Pilgrimc15b38e2019-10-03 15:08:30 +00009362 const auto *VT = E->getType()->castAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00009363 QualType EltTy = VT->getElementType();
9364 APValue ZeroElement;
9365 if (EltTy->isIntegerType())
9366 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9367 else
9368 ZeroElement =
9369 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9370
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009371 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00009372 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009373}
9374
Richard Smith2d406342011-10-22 21:10:00 +00009375bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00009376 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00009377 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009378}
9379
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009380//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00009381// Array Evaluation
9382//===----------------------------------------------------------------------===//
9383
9384namespace {
9385 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009386 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00009387 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00009388 APValue &Result;
9389 public:
9390
Richard Smithd62306a2011-11-10 06:34:14 +00009391 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9392 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00009393
9394 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00009395 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00009396 Result = V;
9397 return true;
9398 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009399
Richard Smithfddd3842011-12-30 21:15:51 +00009400 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00009401 const ConstantArrayType *CAT =
9402 Info.Ctx.getAsConstantArrayType(E->getType());
9403 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009404 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00009405
9406 Result = APValue(APValue::UninitArray(), 0,
9407 CAT->getSize().getZExtValue());
9408 if (!Result.hasArrayFiller()) return true;
9409
Richard Smithfddd3842011-12-30 21:15:51 +00009410 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00009411 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009412 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00009413 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00009414 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00009415 }
9416
Richard Smith52a980a2015-08-28 02:43:42 +00009417 bool VisitCallExpr(const CallExpr *E) {
9418 return handleCallExpr(E, Result, &This);
9419 }
Richard Smithda1b4342019-09-27 01:26:47 +00009420 bool VisitInitListExpr(const InitListExpr *E,
9421 QualType AllocType = QualType());
Richard Smith410306b2016-12-12 02:53:20 +00009422 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00009423 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00009424 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9425 const LValue &Subobject,
9426 APValue *Value, QualType Type);
Richard Smithda1b4342019-09-27 01:26:47 +00009427 bool VisitStringLiteral(const StringLiteral *E,
9428 QualType AllocType = QualType()) {
9429 expandStringLiteral(Info, E, Result, AllocType);
Eli Friedman3bf72d72019-02-08 21:18:46 +00009430 return true;
9431 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009432 };
9433} // end anonymous namespace
9434
Richard Smithd62306a2011-11-10 06:34:14 +00009435static bool EvaluateArray(const Expr *E, const LValue &This,
9436 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00009437 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00009438 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009439}
9440
Richard Smithda1b4342019-09-27 01:26:47 +00009441static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9442 APValue &Result, const InitListExpr *ILE,
9443 QualType AllocType) {
9444 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9445 "not an array rvalue");
9446 return ArrayExprEvaluator(Info, This, Result)
9447 .VisitInitListExpr(ILE, AllocType);
9448}
9449
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009450// Return true iff the given array filler may depend on the element index.
9451static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9452 // For now, just whitelist non-class value-initialization and initialization
9453 // lists comprised of them.
9454 if (isa<ImplicitValueInitExpr>(FillerExpr))
9455 return false;
9456 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9457 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9458 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9459 return true;
9460 }
9461 return false;
9462 }
9463 return true;
9464}
9465
Richard Smithda1b4342019-09-27 01:26:47 +00009466bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9467 QualType AllocType) {
9468 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9469 AllocType.isNull() ? E->getType() : AllocType);
Richard Smithf3e9e432011-11-07 09:22:26 +00009470 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009471 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009472
Richard Smithca2cfbf2011-12-22 01:07:19 +00009473 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9474 // an appropriately-typed string literal enclosed in braces.
Richard Smithda1b4342019-09-27 01:26:47 +00009475 if (E->isStringLiteralInit()) {
9476 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9477 // FIXME: Support ObjCEncodeExpr here once we support it in
9478 // ArrayExprEvaluator generally.
9479 if (!SL)
9480 return Error(E);
9481 return VisitStringLiteral(SL, AllocType);
9482 }
Richard Smithca2cfbf2011-12-22 01:07:19 +00009483
Richard Smith253c2a32012-01-27 01:14:48 +00009484 bool Success = true;
9485
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009486 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9487 "zero-initialized array shouldn't have any initialized elts");
9488 APValue Filler;
9489 if (Result.isArray() && Result.hasArrayFiller())
9490 Filler = Result.getArrayFiller();
9491
Richard Smith9543c5e2013-04-22 14:44:29 +00009492 unsigned NumEltsToInit = E->getNumInits();
9493 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00009494 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00009495
9496 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009497 // array element.
9498 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00009499 NumEltsToInit = NumElts;
9500
Nicola Zaghen3538b392018-05-15 13:30:56 +00009501 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9502 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009503
Richard Smith9543c5e2013-04-22 14:44:29 +00009504 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009505
9506 // If the array was previously zero-initialized, preserve the
9507 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00009508 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009509 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9510 Result.getArrayInitializedElt(I) = Filler;
9511 if (Result.hasArrayFiller())
9512 Result.getArrayFiller() = Filler;
9513 }
9514
Richard Smithd62306a2011-11-10 06:34:14 +00009515 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009516 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00009517 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9518 const Expr *Init =
9519 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00009520 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00009521 Info, Subobject, Init) ||
9522 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00009523 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00009524 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00009525 return false;
9526 Success = false;
9527 }
Richard Smithd62306a2011-11-10 06:34:14 +00009528 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009529
Richard Smith9543c5e2013-04-22 14:44:29 +00009530 if (!Result.hasArrayFiller())
9531 return Success;
9532
9533 // If we get here, we have a trivial filler, which we can just evaluate
9534 // once and splat over the rest of the array elements.
9535 assert(FillerExpr && "no array filler for incomplete init list");
9536 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9537 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00009538}
9539
Richard Smith410306b2016-12-12 02:53:20 +00009540bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009541 LValue CommonLV;
Richard Smith410306b2016-12-12 02:53:20 +00009542 if (E->getCommonExpr() &&
Richard Smith457226e2019-09-23 03:48:44 +00009543 !Evaluate(Info.CurrentCall->createTemporary(
9544 E->getCommonExpr(),
9545 getStorageType(Info.Ctx, E->getCommonExpr()), false,
9546 CommonLV),
Richard Smith410306b2016-12-12 02:53:20 +00009547 Info, E->getCommonExpr()->getSourceExpr()))
9548 return false;
9549
9550 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9551
9552 uint64_t Elements = CAT->getSize().getZExtValue();
9553 Result = APValue(APValue::UninitArray(), Elements, Elements);
9554
9555 LValue Subobject = This;
9556 Subobject.addArray(Info, E, CAT);
9557
9558 bool Success = true;
9559 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9560 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9561 Info, Subobject, E->getSubExpr()) ||
9562 !HandleLValueArrayAdjustment(Info, E, Subobject,
9563 CAT->getElementType(), 1)) {
9564 if (!Info.noteFailure())
9565 return false;
9566 Success = false;
9567 }
9568 }
9569
9570 return Success;
9571}
9572
Richard Smith027bf112011-11-17 22:56:20 +00009573bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00009574 return VisitCXXConstructExpr(E, This, &Result, E->getType());
9575}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009576
Richard Smith9543c5e2013-04-22 14:44:29 +00009577bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9578 const LValue &Subobject,
9579 APValue *Value,
9580 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00009581 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00009582
9583 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9584 unsigned N = CAT->getSize().getZExtValue();
9585
9586 // Preserve the array filler if we had prior zero-initialization.
9587 APValue Filler =
9588 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9589 : APValue();
9590
9591 *Value = APValue(APValue::UninitArray(), N, N);
9592
9593 if (HadZeroInit)
9594 for (unsigned I = 0; I != N; ++I)
9595 Value->getArrayInitializedElt(I) = Filler;
9596
9597 // Initialize the elements.
9598 LValue ArrayElt = Subobject;
9599 ArrayElt.addArray(Info, E, CAT);
9600 for (unsigned I = 0; I != N; ++I)
9601 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9602 CAT->getElementType()) ||
9603 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9604 CAT->getElementType(), 1))
9605 return false;
9606
9607 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009608 }
Richard Smith027bf112011-11-17 22:56:20 +00009609
Richard Smith9543c5e2013-04-22 14:44:29 +00009610 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00009611 return Error(E);
9612
Richard Smithb8348f52016-05-12 22:16:28 +00009613 return RecordExprEvaluator(Info, Subobject, *Value)
9614 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00009615}
9616
Richard Smithf3e9e432011-11-07 09:22:26 +00009617//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009618// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00009619//
9620// As a GNU extension, we support casting pointers to sufficiently-wide integer
9621// types and back in constant folding. Integer values are thus represented
9622// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00009623//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009624
9625namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009626class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009627 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00009628 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009629public:
Richard Smith2e312c82012-03-03 22:46:17 +00009630 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009631 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00009632
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009633 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009634 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009635 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009636 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009637 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009638 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009639 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009640 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009641 return true;
9642 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009643 bool Success(const llvm::APSInt &SI, const Expr *E) {
9644 return Success(SI, E, Result);
9645 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009646
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009647 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00009648 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009649 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009650 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009651 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009652 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009653 Result.getInt().setIsUnsigned(
9654 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009655 return true;
9656 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009657 bool Success(const llvm::APInt &I, const Expr *E) {
9658 return Success(I, E, Result);
9659 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009660
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009661 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009662 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009663 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009664 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009665 return true;
9666 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009667 bool Success(uint64_t Value, const Expr *E) {
9668 return Success(Value, E, Result);
9669 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009670
Ken Dyckdbc01912011-03-11 02:13:43 +00009671 bool Success(CharUnits Size, const Expr *E) {
9672 return Success(Size.getQuantity(), E);
9673 }
9674
Richard Smith2e312c82012-03-03 22:46:17 +00009675 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00009676 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00009677 Result = V;
9678 return true;
9679 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009680 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00009681 }
Mike Stump11289f42009-09-09 15:08:12 +00009682
Richard Smithfddd3842011-12-30 21:15:51 +00009683 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00009684
Peter Collingbournee9200682011-05-13 03:29:01 +00009685 //===--------------------------------------------------------------------===//
9686 // Visitor Methods
9687 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009688
Fangrui Song407659a2018-11-30 23:41:18 +00009689 bool VisitConstantExpr(const ConstantExpr *E);
9690
Chris Lattner7174bf32008-07-12 00:38:25 +00009691 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009692 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009693 }
9694 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009695 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009696 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009697
9698 bool CheckReferencedDecl(const Expr *E, const Decl *D);
9699 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009700 if (CheckReferencedDecl(E, E->getDecl()))
9701 return true;
9702
9703 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009704 }
9705 bool VisitMemberExpr(const MemberExpr *E) {
9706 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00009707 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009708 return true;
9709 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009710
9711 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009712 }
9713
Peter Collingbournee9200682011-05-13 03:29:01 +00009714 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00009715 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00009716 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00009717 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00009718 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00009719
Peter Collingbournee9200682011-05-13 03:29:01 +00009720 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009721 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00009722
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009723 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009724 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009725 }
Mike Stump11289f42009-09-09 15:08:12 +00009726
Ted Kremeneke65b0862012-03-06 20:05:56 +00009727 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9728 return Success(E->getValue(), E);
9729 }
Richard Smith410306b2016-12-12 02:53:20 +00009730
9731 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9732 if (Info.ArrayInitIndex == uint64_t(-1)) {
9733 // We were asked to evaluate this subexpression independent of the
9734 // enclosing ArrayInitLoopExpr. We can't do that.
9735 Info.FFDiag(E);
9736 return false;
9737 }
9738 return Success(Info.ArrayInitIndex, E);
9739 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009740
Richard Smith4ce706a2011-10-11 21:43:33 +00009741 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00009742 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00009743 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009744 }
9745
Douglas Gregor29c42f22012-02-24 07:38:34 +00009746 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9747 return Success(E->getValue(), E);
9748 }
9749
John Wiegley6242b6a2011-04-28 00:16:57 +00009750 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9751 return Success(E->getValue(), E);
9752 }
9753
John Wiegleyf9f65842011-04-25 06:54:41 +00009754 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9755 return Success(E->getValue(), E);
9756 }
9757
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009758 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009759 bool VisitUnaryImag(const UnaryOperator *E);
9760
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009761 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009762 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00009763 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009764 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00009765};
Leonard Chandb01c3a2018-06-20 17:19:40 +00009766
9767class FixedPointExprEvaluator
9768 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9769 APValue &Result;
9770
9771 public:
9772 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9773 : ExprEvaluatorBaseTy(info), Result(result) {}
9774
Leonard Chandb01c3a2018-06-20 17:19:40 +00009775 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009776 return Success(
9777 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009778 }
9779
Leonard Chandb01c3a2018-06-20 17:19:40 +00009780 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009781 return Success(
9782 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009783 }
9784
9785 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009786 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009787 }
9788
Leonard Chand3f3e162019-01-18 21:04:25 +00009789 bool Success(const APFixedPoint &V, const Expr *E) {
9790 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9791 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9792 "Invalid evaluation result.");
9793 Result = APValue(V);
9794 return true;
9795 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00009796
9797 //===--------------------------------------------------------------------===//
9798 // Visitor Methods
9799 //===--------------------------------------------------------------------===//
9800
9801 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9802 return Success(E->getValue(), E);
9803 }
9804
Leonard Chand3f3e162019-01-18 21:04:25 +00009805 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009806 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00009807 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009808};
Chris Lattner05706e882008-07-11 18:11:29 +00009809} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009810
Richard Smith11562c52011-10-28 17:51:58 +00009811/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9812/// produce either the integer value or a pointer.
9813///
9814/// GCC has a heinous extension which folds casts between pointer types and
9815/// pointer-sized integral types. We support this by allowing the evaluation of
9816/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9817/// Some simple arithmetic on such values is supported (they are treated much
9818/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00009819static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00009820 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009821 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009822 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00009823}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009824
Richard Smithf57d8cb2011-12-09 22:58:01 +00009825static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00009826 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009827 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00009828 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009829 if (!Val.isInt()) {
9830 // FIXME: It would be better to produce the diagnostic for casting
9831 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00009832 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009833 return false;
9834 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009835 Result = Val.getInt();
9836 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009837}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009838
Eric Fiselier708afb52019-05-16 21:04:15 +00009839bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9840 APValue Evaluated = E->EvaluateInContext(
9841 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9842 return Success(Evaluated, E);
9843}
9844
Leonard Chand3f3e162019-01-18 21:04:25 +00009845static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9846 EvalInfo &Info) {
9847 if (E->getType()->isFixedPointType()) {
9848 APValue Val;
9849 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9850 return false;
9851 if (!Val.isFixedPoint())
9852 return false;
9853
9854 Result = Val.getFixedPoint();
9855 return true;
9856 }
9857 return false;
9858}
9859
9860static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9861 EvalInfo &Info) {
9862 if (E->getType()->isIntegerType()) {
9863 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9864 APSInt Val;
9865 if (!EvaluateInteger(E, Val, Info))
9866 return false;
9867 Result = APFixedPoint(Val, FXSema);
9868 return true;
9869 } else if (E->getType()->isFixedPointType()) {
9870 return EvaluateFixedPoint(E, Result, Info);
9871 }
9872 return false;
9873}
9874
Richard Smithf57d8cb2011-12-09 22:58:01 +00009875/// Check whether the given declaration can be directly converted to an integral
9876/// rvalue. If not, no diagnostic is produced; there are other things we can
9877/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009878bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00009879 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009880 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009881 // Check for signedness/width mismatches between E type and ECD value.
9882 bool SameSign = (ECD->getInitVal().isSigned()
9883 == E->getType()->isSignedIntegerOrEnumerationType());
9884 bool SameWidth = (ECD->getInitVal().getBitWidth()
9885 == Info.Ctx.getIntWidth(E->getType()));
9886 if (SameSign && SameWidth)
9887 return Success(ECD->getInitVal(), E);
9888 else {
9889 // Get rid of mismatch (otherwise Success assertions will fail)
9890 // by computing a new value matching the type of E.
9891 llvm::APSInt Val = ECD->getInitVal();
9892 if (!SameSign)
9893 Val.setIsSigned(!ECD->getInitVal().isSigned());
9894 if (!SameWidth)
9895 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9896 return Success(Val, E);
9897 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009898 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009899 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00009900}
9901
Richard Smith08b682b2018-05-23 21:18:00 +00009902/// Values returned by __builtin_classify_type, chosen to match the values
9903/// produced by GCC's builtin.
9904enum class GCCTypeClass {
9905 None = -1,
9906 Void = 0,
9907 Integer = 1,
9908 // GCC reserves 2 for character types, but instead classifies them as
9909 // integers.
9910 Enum = 3,
9911 Bool = 4,
9912 Pointer = 5,
9913 // GCC reserves 6 for references, but appears to never use it (because
9914 // expressions never have reference type, presumably).
9915 PointerToDataMember = 7,
9916 RealFloat = 8,
9917 Complex = 9,
9918 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9919 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9920 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9921 // uses 12 for that purpose, same as for a class or struct. Maybe it
9922 // internally implements a pointer to member as a struct? Who knows.
9923 PointerToMemberFunction = 12, // Not a bug, see above.
9924 ClassOrStruct = 12,
9925 Union = 13,
9926 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9927 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9928 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9929 // literals.
9930};
9931
Chris Lattner86ee2862008-10-06 06:40:35 +00009932/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9933/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00009934static GCCTypeClass
9935EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9936 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00009937
Richard Smith08b682b2018-05-23 21:18:00 +00009938 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009939 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9940
9941 switch (CanTy->getTypeClass()) {
9942#define TYPE(ID, BASE)
9943#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9944#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9945#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
John McCall36b12a82019-10-02 06:35:23 +00009946#include "clang/AST/TypeNodes.inc"
Richard Smith08b682b2018-05-23 21:18:00 +00009947 case Type::Auto:
9948 case Type::DeducedTemplateSpecialization:
9949 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009950
9951 case Type::Builtin:
9952 switch (BT->getKind()) {
9953#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00009954#define SIGNED_TYPE(ID, SINGLETON_ID) \
9955 case BuiltinType::ID: return GCCTypeClass::Integer;
9956#define FLOATING_TYPE(ID, SINGLETON_ID) \
9957 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9958#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9959 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009960#include "clang/AST/BuiltinTypes.def"
9961 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00009962 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009963
9964 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00009965 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009966
Richard Smith08b682b2018-05-23 21:18:00 +00009967 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009968 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00009969 case BuiltinType::WChar_U:
9970 case BuiltinType::Char8:
9971 case BuiltinType::Char16:
9972 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009973 case BuiltinType::UShort:
9974 case BuiltinType::UInt:
9975 case BuiltinType::ULong:
9976 case BuiltinType::ULongLong:
9977 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00009978 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009979
Leonard Chanf921d852018-06-04 16:07:52 +00009980 case BuiltinType::UShortAccum:
9981 case BuiltinType::UAccum:
9982 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009983 case BuiltinType::UShortFract:
9984 case BuiltinType::UFract:
9985 case BuiltinType::ULongFract:
9986 case BuiltinType::SatUShortAccum:
9987 case BuiltinType::SatUAccum:
9988 case BuiltinType::SatULongAccum:
9989 case BuiltinType::SatUShortFract:
9990 case BuiltinType::SatUFract:
9991 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00009992 return GCCTypeClass::None;
9993
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009994 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009995
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009996 case BuiltinType::ObjCId:
9997 case BuiltinType::ObjCClass:
9998 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00009999#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10000 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +000010001#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +000010002#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10003 case BuiltinType::Id:
10004#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010005 case BuiltinType::OCLSampler:
10006 case BuiltinType::OCLEvent:
10007 case BuiltinType::OCLClkEvent:
10008 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010009 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +000010010#define SVE_TYPE(Name, Id, SingletonId) \
10011 case BuiltinType::Id:
10012#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +000010013 return GCCTypeClass::None;
10014
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010015 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +000010016 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010017 };
Richard Smith08b682b2018-05-23 21:18:00 +000010018 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010019
10020 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +000010021 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010022
10023 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010024 case Type::ConstantArray:
10025 case Type::VariableArray:
10026 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +000010027 case Type::FunctionNoProto:
10028 case Type::FunctionProto:
10029 return GCCTypeClass::Pointer;
10030
10031 case Type::MemberPointer:
10032 return CanTy->isMemberDataPointerType()
10033 ? GCCTypeClass::PointerToDataMember
10034 : GCCTypeClass::PointerToMemberFunction;
10035
10036 case Type::Complex:
10037 return GCCTypeClass::Complex;
10038
10039 case Type::Record:
10040 return CanTy->isUnionType() ? GCCTypeClass::Union
10041 : GCCTypeClass::ClassOrStruct;
10042
10043 case Type::Atomic:
10044 // GCC classifies _Atomic T the same as T.
10045 return EvaluateBuiltinClassifyType(
10046 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010047
10048 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010049 case Type::Vector:
10050 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010051 case Type::ObjCObject:
10052 case Type::ObjCInterface:
10053 case Type::ObjCObjectPointer:
10054 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +000010055 // GCC classifies vectors as None. We follow its lead and classify all
10056 // other types that don't fit into the regular classification the same way.
10057 return GCCTypeClass::None;
10058
10059 case Type::LValueReference:
10060 case Type::RValueReference:
10061 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010062 }
10063
Richard Smith08b682b2018-05-23 21:18:00 +000010064 llvm_unreachable("unexpected type class");
10065}
10066
10067/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10068/// as GCC.
10069static GCCTypeClass
10070EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10071 // If no argument was supplied, default to None. This isn't
10072 // ideal, however it is what gcc does.
10073 if (E->getNumArgs() == 0)
10074 return GCCTypeClass::None;
10075
10076 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10077 // being an ICE, but still folds it to a constant using the type of the first
10078 // argument.
10079 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +000010080}
10081
Richard Smith5fab0c92011-12-28 19:48:30 +000010082/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +000010083/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +000010084///
Richard Smith31cfb312019-04-27 02:58:17 +000010085/// A pointer is only "constant" if it is null (or a pointer cast to integer)
10086/// or it points to the first character of a string literal.
10087static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10088 APValue::LValueBase Base = LV.getLValueBase();
10089 if (Base.isNull()) {
10090 // A null base is acceptable.
10091 return true;
10092 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10093 if (!isa<StringLiteral>(E))
10094 return false;
10095 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +000010096 } else if (Base.is<TypeInfoLValue>()) {
10097 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10098 // evaluate to true.
10099 return true;
Richard Smith31cfb312019-04-27 02:58:17 +000010100 } else {
10101 // Any other base is not constant enough for GCC.
10102 return false;
10103 }
Richard Smith5fab0c92011-12-28 19:48:30 +000010104}
10105
10106/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10107/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +000010108static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +000010109 // This evaluation is not permitted to have side-effects, so evaluate it in
10110 // a speculative evaluation context.
10111 SpeculativeEvaluationRAII SpeculativeEval(Info);
10112
Richard Smith31cfb312019-04-27 02:58:17 +000010113 // Constant-folding is always enabled for the operand of __builtin_constant_p
10114 // (even when the enclosing evaluation context otherwise requires a strict
10115 // language-specific constant expression).
10116 FoldConstant Fold(Info, true);
10117
Richard Smith5fab0c92011-12-28 19:48:30 +000010118 QualType ArgType = Arg->getType();
10119
10120 // __builtin_constant_p always has one operand. The rules which gcc follows
10121 // are not precisely documented, but are as follows:
10122 //
10123 // - If the operand is of integral, floating, complex or enumeration type,
10124 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +000010125 // - If the operand can be folded to a pointer to the first character
10126 // of a string literal (or such a pointer cast to an integral type)
10127 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +000010128 //
10129 // Otherwise, it returns 0.
10130 //
10131 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +000010132 // its support for this did not work prior to GCC 9 and is not yet well
10133 // understood.
10134 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10135 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10136 ArgType->isNullPtrType()) {
10137 APValue V;
10138 if (!::EvaluateAsRValue(Info, Arg, V)) {
10139 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +000010140 return false;
Richard Smith31cfb312019-04-27 02:58:17 +000010141 }
Richard Smith5fab0c92011-12-28 19:48:30 +000010142
Richard Smith31cfb312019-04-27 02:58:17 +000010143 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +000010144 if (V.getKind() == APValue::LValue)
10145 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +000010146
10147 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +000010148 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +000010149 }
10150
10151 // Anything else isn't considered to be sufficiently constant.
10152 return false;
10153}
10154
John McCall95007602010-05-10 23:27:23 +000010155/// Retrieves the "underlying object type" of the given expression,
10156/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +000010157static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000010158 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10159 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +000010160 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000010161 } else if (const Expr *E = B.get<const Expr*>()) {
10162 if (isa<CompoundLiteralExpr>(E))
10163 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +000010164 } else if (B.is<TypeInfoLValue>()) {
10165 return B.getTypeInfoType();
Richard Smithda1b4342019-09-27 01:26:47 +000010166 } else if (B.is<DynamicAllocLValue>()) {
10167 return B.getDynamicAllocType();
John McCall95007602010-05-10 23:27:23 +000010168 }
10169
10170 return QualType();
10171}
10172
George Burgess IV3a03fab2015-09-04 21:28:13 +000010173/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +000010174/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +000010175/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +000010176/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10177///
10178/// Always returns an RValue with a pointer representation.
10179static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10180 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10181
10182 auto *NoParens = E->IgnoreParens();
10183 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +000010184 if (Cast == nullptr)
10185 return NoParens;
10186
10187 // We only conservatively allow a few kinds of casts, because this code is
10188 // inherently a simple solution that seeks to support the common case.
10189 auto CastKind = Cast->getCastKind();
10190 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10191 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +000010192 return NoParens;
10193
10194 auto *SubExpr = Cast->getSubExpr();
10195 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10196 return NoParens;
10197 return ignorePointerCastsAndParens(SubExpr);
10198}
10199
George Burgess IVa51c4072015-10-16 01:49:01 +000010200/// Checks to see if the given LValue's Designator is at the end of the LValue's
10201/// record layout. e.g.
10202/// struct { struct { int a, b; } fst, snd; } obj;
10203/// obj.fst // no
10204/// obj.snd // yes
10205/// obj.fst.a // no
10206/// obj.fst.b // no
10207/// obj.snd.a // no
10208/// obj.snd.b // yes
10209///
10210/// Please note: this function is specialized for how __builtin_object_size
10211/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +000010212///
Richard Smith6f4f0f12017-10-20 22:56:25 +000010213/// If this encounters an invalid RecordDecl or otherwise cannot determine the
10214/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +000010215static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10216 assert(!LVal.Designator.Invalid);
10217
George Burgess IV4168d752016-06-27 19:40:41 +000010218 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10219 const RecordDecl *Parent = FD->getParent();
10220 Invalid = Parent->isInvalidDecl();
10221 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +000010222 return true;
George Burgess IV4168d752016-06-27 19:40:41 +000010223 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +000010224 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10225 };
10226
10227 auto &Base = LVal.getLValueBase();
10228 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10229 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +000010230 bool Invalid;
10231 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10232 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +000010233 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +000010234 for (auto *FD : IFD->chain()) {
10235 bool Invalid;
10236 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10237 return Invalid;
10238 }
George Burgess IVa51c4072015-10-16 01:49:01 +000010239 }
10240 }
10241
George Burgess IVe3763372016-12-22 02:50:20 +000010242 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +000010243 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +000010244 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000010245 // If we don't know the array bound, conservatively assume we're looking at
10246 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +000010247 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +000010248 if (BaseType->isIncompleteArrayType())
10249 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10250 else
10251 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +000010252 }
10253
10254 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10255 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +000010256 if (BaseType->isArrayType()) {
10257 // Because __builtin_object_size treats arrays as objects, we can ignore
10258 // the index iff this is the last array in the Designator.
10259 if (I + 1 == E)
10260 return true;
George Burgess IVe3763372016-12-22 02:50:20 +000010261 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +000010262 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +000010263 if (Index + 1 != CAT->getSize())
10264 return false;
10265 BaseType = CAT->getElementType();
10266 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +000010267 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010268 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +000010269 if (Index != 1)
10270 return false;
10271 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +000010272 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +000010273 bool Invalid;
10274 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10275 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +000010276 BaseType = FD->getType();
10277 } else {
George Burgess IVe3763372016-12-22 02:50:20 +000010278 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +000010279 return false;
10280 }
10281 }
10282 return true;
10283}
10284
George Burgess IVe3763372016-12-22 02:50:20 +000010285/// Tests to see if the LValue has a user-specified designator (that isn't
10286/// necessarily valid). Note that this always returns 'true' if the LValue has
10287/// an unsized array as its first designator entry, because there's currently no
10288/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +000010289static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +000010290 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +000010291 return false;
10292
George Burgess IVe3763372016-12-22 02:50:20 +000010293 if (!LVal.Designator.Entries.empty())
10294 return LVal.Designator.isMostDerivedAnUnsizedArray();
10295
George Burgess IVa51c4072015-10-16 01:49:01 +000010296 if (!LVal.InvalidBase)
10297 return true;
10298
George Burgess IVe3763372016-12-22 02:50:20 +000010299 // If `E` is a MemberExpr, then the first part of the designator is hiding in
10300 // the LValueBase.
10301 const auto *E = LVal.Base.dyn_cast<const Expr *>();
10302 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +000010303}
10304
George Burgess IVe3763372016-12-22 02:50:20 +000010305/// Attempts to detect a user writing into a piece of memory that's impossible
10306/// to figure out the size of by just using types.
10307static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10308 const SubobjectDesignator &Designator = LVal.Designator;
10309 // Notes:
10310 // - Users can only write off of the end when we have an invalid base. Invalid
10311 // bases imply we don't know where the memory came from.
10312 // - We used to be a bit more aggressive here; we'd only be conservative if
10313 // the array at the end was flexible, or if it had 0 or 1 elements. This
10314 // broke some common standard library extensions (PR30346), but was
10315 // otherwise seemingly fine. It may be useful to reintroduce this behavior
10316 // with some sort of whitelist. OTOH, it seems that GCC is always
10317 // conservative with the last element in structs (if it's an array), so our
10318 // current behavior is more compatible than a whitelisting approach would
10319 // be.
10320 return LVal.InvalidBase &&
10321 Designator.Entries.size() == Designator.MostDerivedPathLength &&
10322 Designator.MostDerivedIsArrayElement &&
10323 isDesignatorAtObjectEnd(Ctx, LVal);
10324}
10325
10326/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10327/// Fails if the conversion would cause loss of precision.
10328static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10329 CharUnits &Result) {
10330 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10331 if (Int.ugt(CharUnitsMax))
10332 return false;
10333 Result = CharUnits::fromQuantity(Int.getZExtValue());
10334 return true;
10335}
10336
10337/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10338/// determine how many bytes exist from the beginning of the object to either
10339/// the end of the current subobject, or the end of the object itself, depending
10340/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +000010341///
George Burgess IVe3763372016-12-22 02:50:20 +000010342/// If this returns false, the value of Result is undefined.
10343static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10344 unsigned Type, const LValue &LVal,
10345 CharUnits &EndOffset) {
10346 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010347
George Burgess IV7fb7e362017-01-03 23:35:19 +000010348 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10349 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10350 return false;
10351 return HandleSizeof(Info, ExprLoc, Ty, Result);
10352 };
10353
George Burgess IVe3763372016-12-22 02:50:20 +000010354 // We want to evaluate the size of the entire object. This is a valid fallback
10355 // for when Type=1 and the designator is invalid, because we're asked for an
10356 // upper-bound.
10357 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10358 // Type=3 wants a lower bound, so we can't fall back to this.
10359 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +000010360 return false;
George Burgess IVe3763372016-12-22 02:50:20 +000010361
10362 llvm::APInt APEndOffset;
10363 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10364 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10365 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10366
10367 if (LVal.InvalidBase)
10368 return false;
10369
10370 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +000010371 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +000010372 }
10373
George Burgess IVe3763372016-12-22 02:50:20 +000010374 // We want to evaluate the size of a subobject.
10375 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010376
10377 // The following is a moderately common idiom in C:
10378 //
10379 // struct Foo { int a; char c[1]; };
10380 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10381 // strcpy(&F->c[0], Bar);
10382 //
George Burgess IVe3763372016-12-22 02:50:20 +000010383 // In order to not break too much legacy code, we need to support it.
10384 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10385 // If we can resolve this to an alloc_size call, we can hand that back,
10386 // because we know for certain how many bytes there are to write to.
10387 llvm::APInt APEndOffset;
10388 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10389 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10390 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10391
10392 // If we cannot determine the size of the initial allocation, then we can't
10393 // given an accurate upper-bound. However, we are still able to give
10394 // conservative lower-bounds for Type=3.
10395 if (Type == 1)
10396 return false;
10397 }
10398
10399 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +000010400 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010401 return false;
10402
George Burgess IVe3763372016-12-22 02:50:20 +000010403 // According to the GCC documentation, we want the size of the subobject
10404 // denoted by the pointer. But that's not quite right -- what we actually
10405 // want is the size of the immediately-enclosing array, if there is one.
10406 int64_t ElemsRemaining;
10407 if (Designator.MostDerivedIsArrayElement &&
10408 Designator.Entries.size() == Designator.MostDerivedPathLength) {
10409 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010410 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +000010411 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10412 } else {
10413 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10414 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010415
George Burgess IVe3763372016-12-22 02:50:20 +000010416 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10417 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010418}
10419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010420/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +000010421/// returns true and stores the result in @p Size.
10422///
10423/// If @p WasError is non-null, this will report whether the failure to evaluate
10424/// is to be treated as an Error in IntExprEvaluator.
10425static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10426 EvalInfo &Info, uint64_t &Size) {
10427 // Determine the denoted object.
10428 LValue LVal;
10429 {
10430 // The operand of __builtin_object_size is never evaluated for side-effects.
10431 // If there are any, but we can determine the pointed-to object anyway, then
10432 // ignore the side-effects.
10433 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +000010434 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +000010435
10436 if (E->isGLValue()) {
10437 // It's possible for us to be given GLValues if we're called via
10438 // Expr::tryEvaluateObjectSize.
10439 APValue RVal;
10440 if (!EvaluateAsRValue(Info, E, RVal))
10441 return false;
10442 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +000010443 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10444 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +000010445 return false;
10446 }
10447
10448 // If we point to before the start of the object, there are no accessible
10449 // bytes.
10450 if (LVal.getLValueOffset().isNegative()) {
10451 Size = 0;
10452 return true;
10453 }
10454
10455 CharUnits EndOffset;
10456 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10457 return false;
10458
10459 // If we've fallen outside of the end offset, just pretend there's nothing to
10460 // write to/read from.
10461 if (EndOffset <= LVal.getLValueOffset())
10462 Size = 0;
10463 else
10464 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10465 return true;
John McCall95007602010-05-10 23:27:23 +000010466}
10467
Fangrui Song407659a2018-11-30 23:41:18 +000010468bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10469 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +000010470 if (E->getResultAPValueKind() != APValue::None)
10471 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +000010472 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10473}
10474
Peter Collingbournee9200682011-05-13 03:29:01 +000010475bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +000010476 if (unsigned BuiltinOp = E->getBuiltinCallee())
10477 return VisitBuiltinCallExpr(E, BuiltinOp);
10478
10479 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10480}
10481
10482bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10483 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +000010484 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010485 default:
Peter Collingbournee9200682011-05-13 03:29:01 +000010486 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +000010487
Erik Pilkington9c3b5882019-01-30 20:34:53 +000010488 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +000010489 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +000010490 // The type was checked when we built the expression.
10491 unsigned Type =
10492 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10493 assert(Type <= 3 && "unexpected type");
10494
George Burgess IVe3763372016-12-22 02:50:20 +000010495 uint64_t Size;
10496 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10497 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +000010498
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010499 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +000010500 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +000010501
Richard Smith01ade172012-05-23 04:13:20 +000010502 // Expression had no side effects, but we couldn't statically determine the
10503 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010504 switch (Info.EvalMode) {
10505 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010506 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010507 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010508 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010509 return Error(E);
10510 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010511 // Reduce it to a constant now.
10512 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010513 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +000010514
10515 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +000010516 }
10517
Tim Northover314fbfa2018-11-02 13:14:11 +000010518 case Builtin::BI__builtin_os_log_format_buffer_size: {
10519 analyze_os_log::OSLogBufferLayout Layout;
10520 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10521 return Success(Layout.size().getQuantity(), E);
10522 }
10523
Benjamin Kramera801f4a2012-10-06 14:42:22 +000010524 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +000010525 case Builtin::BI__builtin_bswap32:
10526 case Builtin::BI__builtin_bswap64: {
10527 APSInt Val;
10528 if (!EvaluateInteger(E->getArg(0), Val, Info))
10529 return false;
10530
10531 return Success(Val.byteSwap(), E);
10532 }
10533
Richard Smith8889a3d2013-06-13 06:26:32 +000010534 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +000010535 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +000010536
Craig Topperf95a6d92018-08-08 22:31:12 +000010537 case Builtin::BI__builtin_clrsb:
10538 case Builtin::BI__builtin_clrsbl:
10539 case Builtin::BI__builtin_clrsbll: {
10540 APSInt Val;
10541 if (!EvaluateInteger(E->getArg(0), Val, Info))
10542 return false;
10543
10544 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10545 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010546
Richard Smith80b3c8e2013-06-13 05:04:16 +000010547 case Builtin::BI__builtin_clz:
10548 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010549 case Builtin::BI__builtin_clzll:
10550 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010551 APSInt Val;
10552 if (!EvaluateInteger(E->getArg(0), Val, Info))
10553 return false;
10554 if (!Val)
10555 return Error(E);
10556
10557 return Success(Val.countLeadingZeros(), E);
10558 }
10559
Fangrui Song407659a2018-11-30 23:41:18 +000010560 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +000010561 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +000010562 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +000010563 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +000010564 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +000010565 // Outside a constant context, eagerly evaluate to false in the presence
10566 // of side-effects in order to avoid -Wunsequenced false-positives in
10567 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +000010568 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +000010569 }
David Blaikie639b3d12019-05-03 18:11:31 +000010570 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10571 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000010572 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010573
Eric Fiselieradd16a82019-04-24 02:23:30 +000010574 case Builtin::BI__builtin_is_constant_evaluated:
10575 return Success(Info.InConstantContext, E);
10576
Richard Smith80b3c8e2013-06-13 05:04:16 +000010577 case Builtin::BI__builtin_ctz:
10578 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010579 case Builtin::BI__builtin_ctzll:
10580 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010581 APSInt Val;
10582 if (!EvaluateInteger(E->getArg(0), Val, Info))
10583 return false;
10584 if (!Val)
10585 return Error(E);
10586
10587 return Success(Val.countTrailingZeros(), E);
10588 }
10589
Richard Smith8889a3d2013-06-13 06:26:32 +000010590 case Builtin::BI__builtin_eh_return_data_regno: {
10591 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10592 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10593 return Success(Operand, E);
10594 }
10595
10596 case Builtin::BI__builtin_expect:
10597 return Visit(E->getArg(0));
10598
10599 case Builtin::BI__builtin_ffs:
10600 case Builtin::BI__builtin_ffsl:
10601 case Builtin::BI__builtin_ffsll: {
10602 APSInt Val;
10603 if (!EvaluateInteger(E->getArg(0), Val, Info))
10604 return false;
10605
10606 unsigned N = Val.countTrailingZeros();
10607 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10608 }
10609
10610 case Builtin::BI__builtin_fpclassify: {
10611 APFloat Val(0.0);
10612 if (!EvaluateFloat(E->getArg(5), Val, Info))
10613 return false;
10614 unsigned Arg;
10615 switch (Val.getCategory()) {
10616 case APFloat::fcNaN: Arg = 0; break;
10617 case APFloat::fcInfinity: Arg = 1; break;
10618 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10619 case APFloat::fcZero: Arg = 4; break;
10620 }
10621 return Visit(E->getArg(Arg));
10622 }
10623
10624 case Builtin::BI__builtin_isinf_sign: {
10625 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +000010626 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +000010627 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10628 }
10629
Richard Smithea3019d2013-10-15 19:07:14 +000010630 case Builtin::BI__builtin_isinf: {
10631 APFloat Val(0.0);
10632 return EvaluateFloat(E->getArg(0), Val, Info) &&
10633 Success(Val.isInfinity() ? 1 : 0, E);
10634 }
10635
10636 case Builtin::BI__builtin_isfinite: {
10637 APFloat Val(0.0);
10638 return EvaluateFloat(E->getArg(0), Val, Info) &&
10639 Success(Val.isFinite() ? 1 : 0, E);
10640 }
10641
10642 case Builtin::BI__builtin_isnan: {
10643 APFloat Val(0.0);
10644 return EvaluateFloat(E->getArg(0), Val, Info) &&
10645 Success(Val.isNaN() ? 1 : 0, E);
10646 }
10647
10648 case Builtin::BI__builtin_isnormal: {
10649 APFloat Val(0.0);
10650 return EvaluateFloat(E->getArg(0), Val, Info) &&
10651 Success(Val.isNormal() ? 1 : 0, E);
10652 }
10653
Richard Smith8889a3d2013-06-13 06:26:32 +000010654 case Builtin::BI__builtin_parity:
10655 case Builtin::BI__builtin_parityl:
10656 case Builtin::BI__builtin_parityll: {
10657 APSInt Val;
10658 if (!EvaluateInteger(E->getArg(0), Val, Info))
10659 return false;
10660
10661 return Success(Val.countPopulation() % 2, E);
10662 }
10663
Richard Smith80b3c8e2013-06-13 05:04:16 +000010664 case Builtin::BI__builtin_popcount:
10665 case Builtin::BI__builtin_popcountl:
10666 case Builtin::BI__builtin_popcountll: {
10667 APSInt Val;
10668 if (!EvaluateInteger(E->getArg(0), Val, Info))
10669 return false;
10670
10671 return Success(Val.countPopulation(), E);
10672 }
10673
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010674 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +000010675 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +000010676 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010677 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010678 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +000010679 << /*isConstexpr*/0 << /*isConstructor*/0
10680 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +000010681 else
Richard Smithce1ec5e2012-03-15 04:53:45 +000010682 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010683 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +000010684 case Builtin::BI__builtin_strlen:
10685 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +000010686 // As an extension, we support __builtin_strlen() as a constant expression,
10687 // and support folding strlen() to a constant.
10688 LValue String;
10689 if (!EvaluatePointer(E->getArg(0), String, Info))
10690 return false;
10691
Richard Smith8110c9d2016-11-29 19:45:17 +000010692 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10693
Richard Smithe6c19f22013-11-15 02:10:04 +000010694 // Fast path: if it's a string literal, search the string value.
10695 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10696 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010697 // The string literal may have embedded null characters. Find the first
10698 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +000010699 StringRef Str = S->getBytes();
10700 int64_t Off = String.Offset.getQuantity();
10701 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010702 S->getCharByteWidth() == 1 &&
10703 // FIXME: Add fast-path for wchar_t too.
10704 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +000010705 Str = Str.substr(Off);
10706
10707 StringRef::size_type Pos = Str.find(0);
10708 if (Pos != StringRef::npos)
10709 Str = Str.substr(0, Pos);
10710
10711 return Success(Str.size(), E);
10712 }
10713
10714 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010715 }
Richard Smithe6c19f22013-11-15 02:10:04 +000010716
10717 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +000010718 for (uint64_t Strlen = 0; /**/; ++Strlen) {
10719 APValue Char;
10720 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
10721 !Char.isInt())
10722 return false;
10723 if (!Char.getInt())
10724 return Success(Strlen, E);
10725 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
10726 return false;
10727 }
10728 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010729
Richard Smithe151bab2016-11-11 23:43:35 +000010730 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010731 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010732 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010733 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010734 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010735 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010736 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010737 // A call to strlen is not a constant expression.
10738 if (Info.getLangOpts().CPlusPlus11)
10739 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10740 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +000010741 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +000010742 else
10743 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010744 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +000010745 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010746 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010747 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010748 case Builtin::BI__builtin_wcsncmp:
10749 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010750 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010751 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +000010752 LValue String1, String2;
10753 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10754 !EvaluatePointer(E->getArg(1), String2, Info))
10755 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +000010756
Richard Smithe151bab2016-11-11 23:43:35 +000010757 uint64_t MaxLength = uint64_t(-1);
10758 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010759 BuiltinOp != Builtin::BIwcscmp &&
10760 BuiltinOp != Builtin::BI__builtin_strcmp &&
10761 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +000010762 APSInt N;
10763 if (!EvaluateInteger(E->getArg(2), N, Info))
10764 return false;
10765 MaxLength = N.getExtValue();
10766 }
Hubert Tong147b7432018-12-12 16:53:43 +000010767
10768 // Empty substrings compare equal by definition.
10769 if (MaxLength == 0u)
10770 return Success(0, E);
10771
10772 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10773 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10774 String1.Designator.Invalid || String2.Designator.Invalid)
10775 return false;
10776
10777 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10778 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10779
10780 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +000010781 BuiltinOp == Builtin::BIbcmp ||
10782 BuiltinOp == Builtin::BI__builtin_memcmp ||
10783 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010784
10785 assert(IsRawByte ||
10786 (Info.Ctx.hasSameUnqualifiedType(
10787 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
10788 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
10789
10790 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10791 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10792 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10793 Char1.isInt() && Char2.isInt();
10794 };
10795 const auto &AdvanceElems = [&] {
10796 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10797 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10798 };
10799
10800 if (IsRawByte) {
10801 uint64_t BytesRemaining = MaxLength;
10802 // Pointers to const void may point to objects of incomplete type.
10803 if (CharTy1->isIncompleteType()) {
10804 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10805 return false;
10806 }
10807 if (CharTy2->isIncompleteType()) {
10808 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10809 return false;
10810 }
10811 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10812 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10813 // Give up on comparing between elements with disparate widths.
10814 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10815 return false;
10816 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10817 assert(BytesRemaining && "BytesRemaining should not be zero: the "
10818 "following loop considers at least one element");
10819 while (true) {
10820 APValue Char1, Char2;
10821 if (!ReadCurElems(Char1, Char2))
10822 return false;
10823 // We have compatible in-memory widths, but a possible type and
10824 // (for `bool`) internal representation mismatch.
10825 // Assuming two's complement representation, including 0 for `false` and
10826 // 1 for `true`, we can check an appropriate number of elements for
10827 // equality even if they are not byte-sized.
10828 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10829 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10830 if (Char1InMem.ne(Char2InMem)) {
10831 // If the elements are byte-sized, then we can produce a three-way
10832 // comparison result in a straightforward manner.
10833 if (BytesPerElement == 1u) {
10834 // memcmp always compares unsigned chars.
10835 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10836 }
10837 // The result is byte-order sensitive, and we have multibyte elements.
10838 // FIXME: We can compare the remaining bytes in the correct order.
10839 return false;
10840 }
10841 if (!AdvanceElems())
10842 return false;
10843 if (BytesRemaining <= BytesPerElement)
10844 break;
10845 BytesRemaining -= BytesPerElement;
10846 }
10847 // Enough elements are equal to account for the memcmp limit.
10848 return Success(0, E);
10849 }
10850
Clement Courbet8c3343d2019-02-14 12:00:34 +000010851 bool StopAtNull =
10852 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10853 BuiltinOp != Builtin::BIwmemcmp &&
10854 BuiltinOp != Builtin::BI__builtin_memcmp &&
10855 BuiltinOp != Builtin::BI__builtin_bcmp &&
10856 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +000010857 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10858 BuiltinOp == Builtin::BIwcsncmp ||
10859 BuiltinOp == Builtin::BIwmemcmp ||
10860 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10861 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10862 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010863
Richard Smithe151bab2016-11-11 23:43:35 +000010864 for (; MaxLength; --MaxLength) {
10865 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +000010866 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +000010867 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +000010868 if (Char1.getInt() != Char2.getInt()) {
10869 if (IsWide) // wmemcmp compares with wchar_t signedness.
10870 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10871 // memcmp always compares unsigned chars.
10872 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10873 }
Richard Smithe151bab2016-11-11 23:43:35 +000010874 if (StopAtNull && !Char1.getInt())
10875 return Success(0, E);
10876 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +000010877 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +000010878 return false;
10879 }
10880 // We hit the strncmp / memcmp limit.
10881 return Success(0, E);
10882 }
10883
Richard Smith01ba47d2012-04-13 00:45:38 +000010884 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +000010885 case Builtin::BI__atomic_is_lock_free:
10886 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +000010887 APSInt SizeVal;
10888 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10889 return false;
10890
10891 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10892 // of two less than the maximum inline atomic width, we know it is
10893 // lock-free. If the size isn't a power of two, or greater than the
10894 // maximum alignment where we promote atomics, we know it is not lock-free
10895 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10896 // the answer can only be determined at runtime; for example, 16-byte
10897 // atomics have lock-free implementations on some, but not all,
10898 // x86-64 processors.
10899
10900 // Check power-of-two.
10901 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +000010902 if (Size.isPowerOfTwo()) {
10903 // Check against inlining width.
10904 unsigned InlineWidthBits =
10905 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10906 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10907 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10908 Size == CharUnits::One() ||
10909 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10910 Expr::NPC_NeverValueDependent))
10911 // OK, we will inline appropriately-aligned operations of this size,
10912 // and _Atomic(T) is appropriately-aligned.
10913 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010914
Richard Smith01ba47d2012-04-13 00:45:38 +000010915 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10916 castAs<PointerType>()->getPointeeType();
10917 if (!PointeeType->isIncompleteType() &&
10918 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10919 // OK, we will inline operations on this object.
10920 return Success(1, E);
10921 }
10922 }
10923 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010924
Richard Smith01ba47d2012-04-13 00:45:38 +000010925 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10926 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010927 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +000010928 case Builtin::BIomp_is_initial_device:
10929 // We can decide statically which value the runtime would return if called.
10930 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +000010931 case Builtin::BI__builtin_add_overflow:
10932 case Builtin::BI__builtin_sub_overflow:
10933 case Builtin::BI__builtin_mul_overflow:
10934 case Builtin::BI__builtin_sadd_overflow:
10935 case Builtin::BI__builtin_uadd_overflow:
10936 case Builtin::BI__builtin_uaddl_overflow:
10937 case Builtin::BI__builtin_uaddll_overflow:
10938 case Builtin::BI__builtin_usub_overflow:
10939 case Builtin::BI__builtin_usubl_overflow:
10940 case Builtin::BI__builtin_usubll_overflow:
10941 case Builtin::BI__builtin_umul_overflow:
10942 case Builtin::BI__builtin_umull_overflow:
10943 case Builtin::BI__builtin_umulll_overflow:
10944 case Builtin::BI__builtin_saddl_overflow:
10945 case Builtin::BI__builtin_saddll_overflow:
10946 case Builtin::BI__builtin_ssub_overflow:
10947 case Builtin::BI__builtin_ssubl_overflow:
10948 case Builtin::BI__builtin_ssubll_overflow:
10949 case Builtin::BI__builtin_smul_overflow:
10950 case Builtin::BI__builtin_smull_overflow:
10951 case Builtin::BI__builtin_smulll_overflow: {
10952 LValue ResultLValue;
10953 APSInt LHS, RHS;
10954
10955 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10956 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10957 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10958 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10959 return false;
10960
10961 APSInt Result;
10962 bool DidOverflow = false;
10963
10964 // If the types don't have to match, enlarge all 3 to the largest of them.
10965 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10966 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10967 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10968 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
10969 ResultType->isSignedIntegerOrEnumerationType();
10970 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
10971 ResultType->isSignedIntegerOrEnumerationType();
10972 uint64_t LHSSize = LHS.getBitWidth();
10973 uint64_t RHSSize = RHS.getBitWidth();
10974 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
10975 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
10976
10977 // Add an additional bit if the signedness isn't uniformly agreed to. We
10978 // could do this ONLY if there is a signed and an unsigned that both have
10979 // MaxBits, but the code to check that is pretty nasty. The issue will be
10980 // caught in the shrink-to-result later anyway.
10981 if (IsSigned && !AllSigned)
10982 ++MaxBits;
10983
Erich Keanefc3dfd32019-05-30 21:35:32 +000010984 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
10985 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +000010986 Result = APSInt(MaxBits, !IsSigned);
10987 }
10988
10989 // Find largest int.
10990 switch (BuiltinOp) {
10991 default:
10992 llvm_unreachable("Invalid value for BuiltinOp");
10993 case Builtin::BI__builtin_add_overflow:
10994 case Builtin::BI__builtin_sadd_overflow:
10995 case Builtin::BI__builtin_saddl_overflow:
10996 case Builtin::BI__builtin_saddll_overflow:
10997 case Builtin::BI__builtin_uadd_overflow:
10998 case Builtin::BI__builtin_uaddl_overflow:
10999 case Builtin::BI__builtin_uaddll_overflow:
11000 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11001 : LHS.uadd_ov(RHS, DidOverflow);
11002 break;
11003 case Builtin::BI__builtin_sub_overflow:
11004 case Builtin::BI__builtin_ssub_overflow:
11005 case Builtin::BI__builtin_ssubl_overflow:
11006 case Builtin::BI__builtin_ssubll_overflow:
11007 case Builtin::BI__builtin_usub_overflow:
11008 case Builtin::BI__builtin_usubl_overflow:
11009 case Builtin::BI__builtin_usubll_overflow:
11010 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11011 : LHS.usub_ov(RHS, DidOverflow);
11012 break;
11013 case Builtin::BI__builtin_mul_overflow:
11014 case Builtin::BI__builtin_smul_overflow:
11015 case Builtin::BI__builtin_smull_overflow:
11016 case Builtin::BI__builtin_smulll_overflow:
11017 case Builtin::BI__builtin_umul_overflow:
11018 case Builtin::BI__builtin_umull_overflow:
11019 case Builtin::BI__builtin_umulll_overflow:
11020 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11021 : LHS.umul_ov(RHS, DidOverflow);
11022 break;
11023 }
11024
11025 // In the case where multiple sizes are allowed, truncate and see if
11026 // the values are the same.
11027 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11028 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11029 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11030 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11031 // since it will give us the behavior of a TruncOrSelf in the case where
11032 // its parameter <= its size. We previously set Result to be at least the
11033 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11034 // will work exactly like TruncOrSelf.
11035 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11036 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11037
11038 if (!APSInt::isSameValue(Temp, Result))
11039 DidOverflow = true;
11040 Result = Temp;
11041 }
11042
11043 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000011044 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11045 return false;
Erich Keane00958272018-06-13 20:43:27 +000011046 return Success(DidOverflow, E);
11047 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011048 }
Chris Lattner7174bf32008-07-12 00:38:25 +000011049}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000011050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011051/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000011052/// object referred to by the lvalue.
11053static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11054 const LValue &LV) {
11055 // A null pointer can be viewed as being "past the end" but we don't
11056 // choose to look at it that way here.
11057 if (!LV.getLValueBase())
11058 return false;
11059
11060 // If the designator is valid and refers to a subobject, we're not pointing
11061 // past the end.
11062 if (!LV.getLValueDesignator().Invalid &&
11063 !LV.getLValueDesignator().isOnePastTheEnd())
11064 return false;
11065
David Majnemerc378ca52015-08-29 08:32:55 +000011066 // A pointer to an incomplete type might be past-the-end if the type's size is
11067 // zero. We cannot tell because the type is incomplete.
11068 QualType Ty = getType(LV.getLValueBase());
11069 if (Ty->isIncompleteType())
11070 return true;
11071
Richard Smithd20f1e62014-10-21 23:01:04 +000011072 // We're a past-the-end pointer if we point to the byte after the object,
11073 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000011074 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000011075 return LV.getLValueOffset() == Size;
11076}
11077
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011078namespace {
Richard Smith11562c52011-10-28 17:51:58 +000011079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011080/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011081///
11082/// We use a data recursive algorithm for binary operators so that we are able
11083/// to handle extreme cases of chained binary operators without causing stack
11084/// overflow.
11085class DataRecursiveIntBinOpEvaluator {
11086 struct EvalResult {
11087 APValue Val;
11088 bool Failed;
11089
11090 EvalResult() : Failed(false) { }
11091
11092 void swap(EvalResult &RHS) {
11093 Val.swap(RHS.Val);
11094 Failed = RHS.Failed;
11095 RHS.Failed = false;
11096 }
11097 };
11098
11099 struct Job {
11100 const Expr *E;
11101 EvalResult LHSResult; // meaningful only for binary operator expression.
11102 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000011103
David Blaikie73726062015-08-12 23:09:24 +000011104 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000011105 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000011106
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011107 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000011108 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011109 }
George Burgess IV8c892b52016-05-25 22:31:54 +000011110
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011111 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000011112 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011113 };
11114
11115 SmallVector<Job, 16> Queue;
11116
11117 IntExprEvaluator &IntEval;
11118 EvalInfo &Info;
11119 APValue &FinalResult;
11120
11121public:
11122 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11123 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11124
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011125 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011126 /// data recursively.
11127 /// We handle binary operators that are comma, logical, or that have operands
11128 /// with integral or enumeration type.
11129 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011130 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11131 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000011132 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011133 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000011134 }
11135
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011136 bool Traverse(const BinaryOperator *E) {
11137 enqueue(E);
11138 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000011139 while (!Queue.empty())
11140 process(PrevResult);
11141
11142 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011143
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011144 FinalResult.swap(PrevResult.Val);
11145 return true;
11146 }
11147
11148private:
11149 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11150 return IntEval.Success(Value, E, Result);
11151 }
11152 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11153 return IntEval.Success(Value, E, Result);
11154 }
11155 bool Error(const Expr *E) {
11156 return IntEval.Error(E);
11157 }
11158 bool Error(const Expr *E, diag::kind D) {
11159 return IntEval.Error(E, D);
11160 }
11161
11162 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11163 return Info.CCEDiag(E, D);
11164 }
11165
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011166 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011167 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011168 bool &SuppressRHSDiags);
11169
11170 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11171 const BinaryOperator *E, APValue &Result);
11172
11173 void EvaluateExpr(const Expr *E, EvalResult &Result) {
11174 Result.Failed = !Evaluate(Result.Val, Info, E);
11175 if (Result.Failed)
11176 Result.Val = APValue();
11177 }
11178
Richard Trieuba4d0872012-03-21 23:30:30 +000011179 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011180
11181 void enqueue(const Expr *E) {
11182 E = E->IgnoreParens();
11183 Queue.resize(Queue.size()+1);
11184 Queue.back().E = E;
11185 Queue.back().Kind = Job::AnyExprKind;
11186 }
11187};
11188
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011189}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011190
11191bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011192 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011193 bool &SuppressRHSDiags) {
11194 if (E->getOpcode() == BO_Comma) {
11195 // Ignore LHS but note if we could not evaluate it.
11196 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000011197 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011198 return true;
11199 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011200
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011201 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000011202 bool LHSAsBool;
11203 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011204 // We were able to evaluate the LHS, see if we can get away with not
11205 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000011206 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11207 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011208 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011209 }
11210 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000011211 LHSResult.Failed = true;
11212
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011213 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000011214 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000011215 if (!Info.noteSideEffect())
11216 return false;
11217
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011218 // We can't evaluate the LHS; however, sometimes the result
11219 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11220 // Don't ignore RHS and suppress diagnostics from this arm.
11221 SuppressRHSDiags = true;
11222 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011223
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011224 return true;
11225 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011226
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011227 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11228 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000011229
George Burgess IVa145e252016-05-25 22:38:36 +000011230 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011231 return false; // Ignore RHS;
11232
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011233 return true;
11234}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011235
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000011236static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11237 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000011238 // Compute the new offset in the appropriate width, wrapping at 64 bits.
11239 // FIXME: When compiling for a 32-bit target, we should use 32-bit
11240 // offsets.
11241 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11242 CharUnits &Offset = LVal.getLValueOffset();
11243 uint64_t Offset64 = Offset.getQuantity();
11244 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11245 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11246 : Offset64 + Index64);
11247}
11248
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011249bool DataRecursiveIntBinOpEvaluator::
11250 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11251 const BinaryOperator *E, APValue &Result) {
11252 if (E->getOpcode() == BO_Comma) {
11253 if (RHSResult.Failed)
11254 return false;
11255 Result = RHSResult.Val;
11256 return true;
11257 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011258
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011259 if (E->isLogicalOp()) {
11260 bool lhsResult, rhsResult;
11261 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11262 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000011263
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011264 if (LHSIsOK) {
11265 if (RHSIsOK) {
11266 if (E->getOpcode() == BO_LOr)
11267 return Success(lhsResult || rhsResult, E, Result);
11268 else
11269 return Success(lhsResult && rhsResult, E, Result);
11270 }
11271 } else {
11272 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011273 // We can't evaluate the LHS; however, sometimes the result
11274 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11275 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011276 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011277 }
11278 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011279
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011280 return false;
11281 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011282
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011283 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11284 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000011285
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011286 if (LHSResult.Failed || RHSResult.Failed)
11287 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000011288
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011289 const APValue &LHSVal = LHSResult.Val;
11290 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000011291
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011292 // Handle cases like (unsigned long)&a + 4.
11293 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11294 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000011295 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011296 return true;
11297 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011298
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011299 // Handle cases like 4 + (unsigned long)&a
11300 if (E->getOpcode() == BO_Add &&
11301 RHSVal.isLValue() && LHSVal.isInt()) {
11302 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000011303 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011304 return true;
11305 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011306
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011307 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11308 // Handle (intptr_t)&&A - (intptr_t)&&B.
11309 if (!LHSVal.getLValueOffset().isZero() ||
11310 !RHSVal.getLValueOffset().isZero())
11311 return false;
11312 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11313 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11314 if (!LHSExpr || !RHSExpr)
11315 return false;
11316 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11317 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11318 if (!LHSAddrExpr || !RHSAddrExpr)
11319 return false;
11320 // Make sure both labels come from the same function.
11321 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11322 RHSAddrExpr->getLabel()->getDeclContext())
11323 return false;
11324 Result = APValue(LHSAddrExpr, RHSAddrExpr);
11325 return true;
11326 }
Richard Smith43e77732013-05-07 04:50:00 +000011327
11328 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011329 if (!LHSVal.isInt() || !RHSVal.isInt())
11330 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000011331
11332 // Set up the width and signedness manually, in case it can't be deduced
11333 // from the operation we're performing.
11334 // FIXME: Don't do this in the cases where we can deduce it.
11335 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11336 E->getType()->isUnsignedIntegerOrEnumerationType());
11337 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11338 RHSVal.getInt(), Value))
11339 return false;
11340 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011341}
11342
Richard Trieuba4d0872012-03-21 23:30:30 +000011343void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011344 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000011345
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011346 switch (job.Kind) {
11347 case Job::AnyExprKind: {
11348 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11349 if (shouldEnqueue(Bop)) {
11350 job.Kind = Job::BinOpKind;
11351 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011352 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011353 }
11354 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011355
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011356 EvaluateExpr(job.E, Result);
11357 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011358 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011359 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011360
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011361 case Job::BinOpKind: {
11362 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011363 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011364 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011365 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011366 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011367 }
11368 if (SuppressRHSDiags)
11369 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011370 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011371 job.Kind = Job::BinOpVisitedLHSKind;
11372 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011373 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011374 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011375
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011376 case Job::BinOpVisitedLHSKind: {
11377 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11378 EvalResult RHS;
11379 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000011380 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011381 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011382 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011383 }
11384 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011385
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011386 llvm_unreachable("Invalid Job::Kind!");
11387}
11388
George Burgess IV8c892b52016-05-25 22:31:54 +000011389namespace {
11390/// Used when we determine that we should fail, but can keep evaluating prior to
11391/// noting that we had a failure.
11392class DelayedNoteFailureRAII {
11393 EvalInfo &Info;
11394 bool NoteFailure;
11395
11396public:
11397 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11398 : Info(Info), NoteFailure(NoteFailure) {}
11399 ~DelayedNoteFailureRAII() {
11400 if (NoteFailure) {
11401 bool ContinueAfterFailure = Info.noteFailure();
11402 (void)ContinueAfterFailure;
11403 assert(ContinueAfterFailure &&
11404 "Shouldn't have kept evaluating on failure.");
11405 }
11406 }
11407};
11408}
11409
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011410template <class SuccessCB, class AfterCB>
11411static bool
11412EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11413 SuccessCB &&Success, AfterCB &&DoAfter) {
11414 assert(E->isComparisonOp() && "expected comparison operator");
11415 assert((E->getOpcode() == BO_Cmp ||
11416 E->getType()->isIntegralOrEnumerationType()) &&
11417 "unsupported binary expression evaluation");
11418 auto Error = [&](const Expr *E) {
11419 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11420 return false;
11421 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011422
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011423 using CCR = ComparisonCategoryResult;
11424 bool IsRelational = E->isRelationalOp();
11425 bool IsEquality = E->isEqualityOp();
11426 if (E->getOpcode() == BO_Cmp) {
11427 const ComparisonCategoryInfo &CmpInfo =
11428 Info.Ctx.CompCategories.getInfoForType(E->getType());
11429 IsRelational = CmpInfo.isOrdered();
11430 IsEquality = CmpInfo.isEquality();
11431 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000011432
Anders Carlssonacc79812008-11-16 07:17:21 +000011433 QualType LHSTy = E->getLHS()->getType();
11434 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011435
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011436 if (LHSTy->isIntegralOrEnumerationType() &&
11437 RHSTy->isIntegralOrEnumerationType()) {
11438 APSInt LHS, RHS;
11439 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11440 if (!LHSOK && !Info.noteFailure())
11441 return false;
11442 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11443 return false;
11444 if (LHS < RHS)
11445 return Success(CCR::Less, E);
11446 if (LHS > RHS)
11447 return Success(CCR::Greater, E);
11448 return Success(CCR::Equal, E);
11449 }
11450
Leonard Chance1d4f12019-02-21 20:50:09 +000011451 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11452 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11453 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11454
11455 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11456 if (!LHSOK && !Info.noteFailure())
11457 return false;
11458 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11459 return false;
11460 if (LHSFX < RHSFX)
11461 return Success(CCR::Less, E);
11462 if (LHSFX > RHSFX)
11463 return Success(CCR::Greater, E);
11464 return Success(CCR::Equal, E);
11465 }
11466
Chandler Carruthb29a7432014-10-11 11:03:30 +000011467 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011468 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000011469 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000011470 if (E->isAssignmentOp()) {
11471 LValue LV;
11472 EvaluateLValue(E->getLHS(), LV, Info);
11473 LHSOK = false;
11474 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000011475 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11476 if (LHSOK) {
11477 LHS.makeComplexFloat();
11478 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11479 }
11480 } else {
11481 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11482 }
George Burgess IVa145e252016-05-25 22:38:36 +000011483 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011484 return false;
11485
Chandler Carruthb29a7432014-10-11 11:03:30 +000011486 if (E->getRHS()->getType()->isRealFloatingType()) {
11487 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11488 return false;
11489 RHS.makeComplexFloat();
11490 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11491 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011492 return false;
11493
11494 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000011495 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011496 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000011497 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011498 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011499 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11500 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011501 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011502 assert(IsEquality && "invalid complex comparison");
11503 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11504 LHS.getComplexIntImag() == RHS.getComplexIntImag();
11505 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011506 }
11507 }
Mike Stump11289f42009-09-09 15:08:12 +000011508
Anders Carlssonacc79812008-11-16 07:17:21 +000011509 if (LHSTy->isRealFloatingType() &&
11510 RHSTy->isRealFloatingType()) {
11511 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000011512
Richard Smith253c2a32012-01-27 01:14:48 +000011513 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011514 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000011515 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011516
Richard Smith253c2a32012-01-27 01:14:48 +000011517 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000011518 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011519
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011520 assert(E->isComparisonOp() && "Invalid binary operator!");
11521 auto GetCmpRes = [&]() {
11522 switch (LHS.compare(RHS)) {
11523 case APFloat::cmpEqual:
11524 return CCR::Equal;
11525 case APFloat::cmpLessThan:
11526 return CCR::Less;
11527 case APFloat::cmpGreaterThan:
11528 return CCR::Greater;
11529 case APFloat::cmpUnordered:
11530 return CCR::Unordered;
11531 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000011532 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011533 };
11534 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000011535 }
Mike Stump11289f42009-09-09 15:08:12 +000011536
Eli Friedmana38da572009-04-28 19:17:36 +000011537 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011538 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000011539
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011540 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11541 if (!LHSOK && !Info.noteFailure())
11542 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011543
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011544 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11545 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011546
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011547 // Reject differing bases from the normal codepath; we special-case
11548 // comparisons to null.
11549 if (!HasSameBase(LHSValue, RHSValue)) {
11550 // Inequalities and subtractions between unrelated pointers have
11551 // unspecified or undefined behavior.
11552 if (!IsEquality)
11553 return Error(E);
11554 // A constant address may compare equal to the address of a symbol.
11555 // The one exception is that address of an object cannot compare equal
11556 // to a null pointer constant.
11557 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11558 (!RHSValue.Base && !RHSValue.Offset.isZero()))
11559 return Error(E);
11560 // It's implementation-defined whether distinct literals will have
11561 // distinct addresses. In clang, the result of such a comparison is
11562 // unspecified, so it is not a constant expression. However, we do know
11563 // that the address of a literal will be non-null.
11564 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11565 LHSValue.Base && RHSValue.Base)
11566 return Error(E);
11567 // We can't tell whether weak symbols will end up pointing to the same
11568 // object.
11569 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11570 return Error(E);
11571 // We can't compare the address of the start of one object with the
11572 // past-the-end address of another object, per C++ DR1652.
11573 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11574 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11575 (RHSValue.Base && RHSValue.Offset.isZero() &&
11576 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11577 return Error(E);
11578 // We can't tell whether an object is at the same address as another
11579 // zero sized object.
11580 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11581 (LHSValue.Base && isZeroSized(RHSValue)))
11582 return Error(E);
11583 return Success(CCR::Nonequal, E);
11584 }
Eli Friedman64004332009-03-23 04:38:34 +000011585
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011586 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11587 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000011588
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011589 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11590 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000011591
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011592 // C++11 [expr.rel]p3:
11593 // Pointers to void (after pointer conversions) can be compared, with a
11594 // result defined as follows: If both pointers represent the same
11595 // address or are both the null pointer value, the result is true if the
11596 // operator is <= or >= and false otherwise; otherwise the result is
11597 // unspecified.
11598 // We interpret this as applying to pointers to *cv* void.
11599 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11600 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000011601
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011602 // C++11 [expr.rel]p2:
11603 // - If two pointers point to non-static data members of the same object,
11604 // or to subobjects or array elements fo such members, recursively, the
11605 // pointer to the later declared member compares greater provided the
11606 // two members have the same access control and provided their class is
11607 // not a union.
11608 // [...]
11609 // - Otherwise pointer comparisons are unspecified.
11610 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11611 bool WasArrayIndex;
11612 unsigned Mismatch = FindDesignatorMismatch(
11613 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11614 // At the point where the designators diverge, the comparison has a
11615 // specified value if:
11616 // - we are comparing array indices
11617 // - we are comparing fields of a union, or fields with the same access
11618 // Otherwise, the result is unspecified and thus the comparison is not a
11619 // constant expression.
11620 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11621 Mismatch < RHSDesignator.Entries.size()) {
11622 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11623 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11624 if (!LF && !RF)
11625 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11626 else if (!LF)
11627 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011628 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11629 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011630 else if (!RF)
11631 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011632 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11633 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011634 else if (!LF->getParent()->isUnion() &&
11635 LF->getAccess() != RF->getAccess())
11636 Info.CCEDiag(E,
11637 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011638 << LF << LF->getAccess() << RF << RF->getAccess()
11639 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000011640 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011641 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011642
11643 // The comparison here must be unsigned, and performed with the same
11644 // width as the pointer.
11645 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11646 uint64_t CompareLHS = LHSOffset.getQuantity();
11647 uint64_t CompareRHS = RHSOffset.getQuantity();
11648 assert(PtrSize <= 64 && "Unexpected pointer width");
11649 uint64_t Mask = ~0ULL >> (64 - PtrSize);
11650 CompareLHS &= Mask;
11651 CompareRHS &= Mask;
11652
11653 // If there is a base and this is a relational operator, we can only
11654 // compare pointers within the object in question; otherwise, the result
11655 // depends on where the object is located in memory.
11656 if (!LHSValue.Base.isNull() && IsRelational) {
11657 QualType BaseTy = getType(LHSValue.Base);
11658 if (BaseTy->isIncompleteType())
11659 return Error(E);
11660 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11661 uint64_t OffsetLimit = Size.getQuantity();
11662 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11663 return Error(E);
11664 }
11665
11666 if (CompareLHS < CompareRHS)
11667 return Success(CCR::Less, E);
11668 if (CompareLHS > CompareRHS)
11669 return Success(CCR::Greater, E);
11670 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011671 }
Richard Smith7bb00672012-02-01 01:42:44 +000011672
11673 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011674 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000011675 assert(RHSTy->isMemberPointerType() && "invalid comparison");
11676
11677 MemberPtr LHSValue, RHSValue;
11678
11679 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011680 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000011681 return false;
11682
11683 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11684 return false;
11685
11686 // C++11 [expr.eq]p2:
11687 // If both operands are null, they compare equal. Otherwise if only one is
11688 // null, they compare unequal.
11689 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11690 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011691 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011692 }
11693
11694 // Otherwise if either is a pointer to a virtual member function, the
11695 // result is unspecified.
11696 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11697 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011698 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011699 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11700 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011701 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011702
11703 // Otherwise they compare equal if and only if they would refer to the
11704 // same member of the same most derived object or the same subobject if
11705 // they were dereferenced with a hypothetical object of the associated
11706 // class type.
11707 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011708 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011709 }
11710
Richard Smithab44d9b2012-02-14 22:35:28 +000011711 if (LHSTy->isNullPtrType()) {
11712 assert(E->isComparisonOp() && "unexpected nullptr operation");
11713 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
11714 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
11715 // are compared, the result is true of the operator is <=, >= or ==, and
11716 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011717 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000011718 }
11719
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011720 return DoAfter();
11721}
11722
11723bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
11724 if (!CheckLiteralType(Info, E))
11725 return false;
11726
11727 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11728 const BinaryOperator *E) {
11729 // Evaluation succeeded. Lookup the information for the comparison category
11730 // type and fetch the VarDecl for the result.
11731 const ComparisonCategoryInfo &CmpInfo =
11732 Info.Ctx.CompCategories.getInfoForType(E->getType());
11733 const VarDecl *VD =
11734 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
11735 // Check and evaluate the result as a constant expression.
11736 LValue LV;
11737 LV.set(VD);
11738 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11739 return false;
11740 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11741 };
11742 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11743 return ExprEvaluatorBaseTy::VisitBinCmp(E);
11744 });
11745}
11746
11747bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11748 // We don't call noteFailure immediately because the assignment happens after
11749 // we evaluate LHS and RHS.
11750 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11751 return Error(E);
11752
11753 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11754 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11755 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11756
11757 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
11758 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011759 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011760
11761 if (E->isComparisonOp()) {
11762 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11763 // comparisons and then translating the result.
11764 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11765 const BinaryOperator *E) {
11766 using CCR = ComparisonCategoryResult;
11767 bool IsEqual = ResKind == CCR::Equal,
11768 IsLess = ResKind == CCR::Less,
11769 IsGreater = ResKind == CCR::Greater;
11770 auto Op = E->getOpcode();
11771 switch (Op) {
11772 default:
11773 llvm_unreachable("unsupported binary operator");
11774 case BO_EQ:
11775 case BO_NE:
11776 return Success(IsEqual == (Op == BO_EQ), E);
11777 case BO_LT: return Success(IsLess, E);
11778 case BO_GT: return Success(IsGreater, E);
11779 case BO_LE: return Success(IsEqual || IsLess, E);
11780 case BO_GE: return Success(IsEqual || IsGreater, E);
11781 }
11782 };
11783 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11784 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11785 });
11786 }
11787
11788 QualType LHSTy = E->getLHS()->getType();
11789 QualType RHSTy = E->getRHS()->getType();
11790
11791 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11792 E->getOpcode() == BO_Sub) {
11793 LValue LHSValue, RHSValue;
11794
11795 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11796 if (!LHSOK && !Info.noteFailure())
11797 return false;
11798
11799 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11800 return false;
11801
11802 // Reject differing bases from the normal codepath; we special-case
11803 // comparisons to null.
11804 if (!HasSameBase(LHSValue, RHSValue)) {
11805 // Handle &&A - &&B.
11806 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11807 return Error(E);
11808 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11809 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11810 if (!LHSExpr || !RHSExpr)
11811 return Error(E);
11812 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11813 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11814 if (!LHSAddrExpr || !RHSAddrExpr)
11815 return Error(E);
11816 // Make sure both labels come from the same function.
11817 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11818 RHSAddrExpr->getLabel()->getDeclContext())
11819 return Error(E);
11820 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11821 }
11822 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11823 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11824
11825 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11826 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11827
11828 // C++11 [expr.add]p6:
11829 // Unless both pointers point to elements of the same array object, or
11830 // one past the last element of the array object, the behavior is
11831 // undefined.
11832 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11833 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11834 RHSDesignator))
11835 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11836
11837 QualType Type = E->getLHS()->getType();
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000011838 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011839
11840 CharUnits ElementSize;
11841 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11842 return false;
11843
11844 // As an extension, a type may have zero size (empty struct or union in
11845 // C, array of zero length). Pointer subtraction in such cases has
11846 // undefined behavior, so is not constant.
11847 if (ElementSize.isZero()) {
11848 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11849 << ElementType;
11850 return false;
11851 }
11852
11853 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11854 // and produce incorrect results when it overflows. Such behavior
11855 // appears to be non-conforming, but is common, so perhaps we should
11856 // assume the standard intended for such cases to be undefined behavior
11857 // and check for them.
11858
11859 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11860 // overflow in the final conversion to ptrdiff_t.
11861 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11862 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11863 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11864 false);
11865 APSInt TrueResult = (LHS - RHS) / ElemSize;
11866 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11867
11868 if (Result.extend(65) != TrueResult &&
11869 !HandleOverflow(Info, E, TrueResult, E->getType()))
11870 return false;
11871 return Success(Result, E);
11872 }
11873
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011874 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000011875}
11876
Peter Collingbournee190dee2011-03-11 19:24:49 +000011877/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11878/// a result as the expression's type.
11879bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11880 const UnaryExprOrTypeTraitExpr *E) {
11881 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000011882 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000011883 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000011884 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000011885 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11886 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011887 else
Richard Smith6822bd72018-10-26 19:26:45 +000011888 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11889 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011890 }
Eli Friedman64004332009-03-23 04:38:34 +000011891
Peter Collingbournee190dee2011-03-11 19:24:49 +000011892 case UETT_VecStep: {
11893 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000011894
Peter Collingbournee190dee2011-03-11 19:24:49 +000011895 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000011896 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000011897
Peter Collingbournee190dee2011-03-11 19:24:49 +000011898 // The vec_step built-in functions that take a 3-component
11899 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11900 if (n == 3)
11901 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000011902
Peter Collingbournee190dee2011-03-11 19:24:49 +000011903 return Success(n, E);
11904 } else
11905 return Success(1, E);
11906 }
11907
11908 case UETT_SizeOf: {
11909 QualType SrcTy = E->getTypeOfArgument();
11910 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11911 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000011912 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11913 SrcTy = Ref->getPointeeType();
11914
Richard Smithd62306a2011-11-10 06:34:14 +000011915 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000011916 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000011917 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000011918 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011919 }
Alexey Bataev00396512015-07-02 03:40:19 +000011920 case UETT_OpenMPRequiredSimdAlign:
11921 assert(E->isArgumentType());
11922 return Success(
11923 Info.Ctx.toCharUnitsFromBits(
11924 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11925 .getQuantity(),
11926 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011927 }
11928
11929 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000011930}
11931
Peter Collingbournee9200682011-05-13 03:29:01 +000011932bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011933 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000011934 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000011935 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011936 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000011937 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000011938 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000011939 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000011940 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000011941 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000011942 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000011943 APSInt IdxResult;
11944 if (!EvaluateInteger(Idx, IdxResult, Info))
11945 return false;
11946 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11947 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011948 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011949 CurrentType = AT->getElementType();
11950 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11951 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000011952 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000011953 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011954
James Y Knight7281c352015-12-29 22:31:18 +000011955 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000011956 FieldDecl *MemberDecl = ON.getField();
11957 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011958 if (!RT)
11959 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011960 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011961 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000011962 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000011963 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000011964 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000011965 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000011966 CurrentType = MemberDecl->getType().getNonReferenceType();
11967 break;
11968 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011969
James Y Knight7281c352015-12-29 22:31:18 +000011970 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000011971 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000011972
James Y Knight7281c352015-12-29 22:31:18 +000011973 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000011974 CXXBaseSpecifier *BaseSpec = ON.getBase();
11975 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000011976 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011977
11978 // Find the layout of the class whose base we are looking into.
11979 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011980 if (!RT)
11981 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011982 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011983 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000011984 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11985
11986 // Find the base class itself.
11987 CurrentType = BaseSpec->getType();
11988 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
11989 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011990 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000011991
Douglas Gregord1702062010-04-29 00:18:15 +000011992 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000011993 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000011994 break;
11995 }
Douglas Gregor882211c2010-04-28 22:16:22 +000011996 }
11997 }
Peter Collingbournee9200682011-05-13 03:29:01 +000011998 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011999}
12000
Chris Lattnere13042c2008-07-11 19:10:17 +000012001bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012002 switch (E->getOpcode()) {
12003 default:
12004 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12005 // See C99 6.6p3.
12006 return Error(E);
12007 case UO_Extension:
12008 // FIXME: Should extension allow i-c-e extension expressions in its scope?
12009 // If so, we could clear the diagnostic ID.
12010 return Visit(E->getSubExpr());
12011 case UO_Plus:
12012 // The result is just the value.
12013 return Visit(E->getSubExpr());
12014 case UO_Minus: {
12015 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000012016 return false;
12017 if (!Result.isInt()) return Error(E);
12018 const APSInt &Value = Result.getInt();
12019 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12020 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12021 E->getType()))
12022 return false;
Richard Smithfe800032012-01-31 04:08:20 +000012023 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012024 }
12025 case UO_Not: {
12026 if (!Visit(E->getSubExpr()))
12027 return false;
12028 if (!Result.isInt()) return Error(E);
12029 return Success(~Result.getInt(), E);
12030 }
12031 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000012032 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000012033 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000012034 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000012035 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000012036 }
Anders Carlsson9c181652008-07-08 14:35:21 +000012037 }
Anders Carlsson9c181652008-07-08 14:35:21 +000012038}
Mike Stump11289f42009-09-09 15:08:12 +000012039
Chris Lattner477c4be2008-07-12 01:15:53 +000012040/// HandleCast - This is used to evaluate implicit or explicit casts where the
12041/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000012042bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12043 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000012044 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000012045 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000012046
Eli Friedmanc757de22011-03-25 00:43:55 +000012047 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000012048 case CK_BaseToDerived:
12049 case CK_DerivedToBase:
12050 case CK_UncheckedDerivedToBase:
12051 case CK_Dynamic:
12052 case CK_ToUnion:
12053 case CK_ArrayToPointerDecay:
12054 case CK_FunctionToPointerDecay:
12055 case CK_NullToPointer:
12056 case CK_NullToMemberPointer:
12057 case CK_BaseToDerivedMemberPointer:
12058 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000012059 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000012060 case CK_ConstructorConversion:
12061 case CK_IntegralToPointer:
12062 case CK_ToVoid:
12063 case CK_VectorSplat:
12064 case CK_IntegralToFloating:
12065 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000012066 case CK_CPointerToObjCPointerCast:
12067 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000012068 case CK_AnyPointerToBlockPointerCast:
12069 case CK_ObjCObjectLValueCast:
12070 case CK_FloatingRealToComplex:
12071 case CK_FloatingComplexToReal:
12072 case CK_FloatingComplexCast:
12073 case CK_FloatingComplexToIntegralComplex:
12074 case CK_IntegralRealToComplex:
12075 case CK_IntegralComplexCast:
12076 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000012077 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012078 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012079 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012080 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012081 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012082 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012083 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000012084 llvm_unreachable("invalid cast kind for integral value");
12085
Eli Friedman9faf2f92011-03-25 19:07:11 +000012086 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000012087 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012088 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000012089 case CK_ARCProduceObject:
12090 case CK_ARCConsumeObject:
12091 case CK_ARCReclaimReturnedObject:
12092 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012093 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012094 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012095
Richard Smith4ef685b2012-01-17 21:17:26 +000012096 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000012097 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012098 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000012099 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012100 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012101 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012102
12103 case CK_MemberPointerToBoolean:
12104 case CK_PointerToBoolean:
12105 case CK_IntegralToBoolean:
12106 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012107 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000012108 case CK_FloatingComplexToBoolean:
12109 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012110 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000012111 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000012112 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000012113 uint64_t IntResult = BoolResult;
12114 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12115 IntResult = (uint64_t)-1;
12116 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000012117 }
12118
Leonard Chan8f7caae2019-03-06 00:28:43 +000012119 case CK_FixedPointToIntegral: {
12120 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12121 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12122 return false;
12123 bool Overflowed;
12124 llvm::APSInt Result = Src.convertToInt(
12125 Info.Ctx.getIntWidth(DestType),
12126 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12127 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12128 return false;
12129 return Success(Result, E);
12130 }
12131
Leonard Chanb4ba4672018-10-23 17:55:35 +000012132 case CK_FixedPointToBoolean: {
12133 // Unsigned padding does not affect this.
12134 APValue Val;
12135 if (!Evaluate(Val, Info, SubExpr))
12136 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000012137 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000012138 }
12139
Eli Friedmanc757de22011-03-25 00:43:55 +000012140 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000012141 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000012142 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000012143
Eli Friedman742421e2009-02-20 01:15:07 +000012144 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000012145 // Allow casts of address-of-label differences if they are no-ops
12146 // or narrowing. (The narrowing case isn't actually guaranteed to
12147 // be constant-evaluatable except in some narrow cases which are hard
12148 // to detect here. We let it through on the assumption the user knows
12149 // what they are doing.)
12150 if (Result.isAddrLabelDiff())
12151 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000012152 // Only allow casts of lvalues if they are lossless.
12153 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12154 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000012155
Richard Smith911e1422012-01-30 22:27:01 +000012156 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12157 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000012158 }
Mike Stump11289f42009-09-09 15:08:12 +000012159
Eli Friedmanc757de22011-03-25 00:43:55 +000012160 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000012161 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12162
John McCall45d55e42010-05-07 21:00:08 +000012163 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000012164 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000012165 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000012166
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012167 if (LV.getLValueBase()) {
12168 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000012169 // FIXME: Allow a larger integer size than the pointer size, and allow
12170 // narrowing back down to pointer width in subsequent integral casts.
12171 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012172 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012173 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000012174
Richard Smithcf74da72011-11-16 07:18:12 +000012175 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000012176 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012177 return true;
12178 }
12179
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000012180 APSInt AsInt;
12181 APValue V;
12182 LV.moveInto(V);
12183 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12184 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000012185
Richard Smith911e1422012-01-30 22:27:01 +000012186 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000012187 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012188
Eli Friedmanc757de22011-03-25 00:43:55 +000012189 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000012190 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000012191 if (!EvaluateComplex(SubExpr, C, Info))
12192 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000012193 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000012194 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000012195
Eli Friedmanc757de22011-03-25 00:43:55 +000012196 case CK_FloatingToIntegral: {
12197 APFloat F(0.0);
12198 if (!EvaluateFloat(SubExpr, F, Info))
12199 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000012200
Richard Smith357362d2011-12-13 06:39:58 +000012201 APSInt Value;
12202 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12203 return false;
12204 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012205 }
12206 }
Mike Stump11289f42009-09-09 15:08:12 +000012207
Eli Friedmanc757de22011-03-25 00:43:55 +000012208 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000012209}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000012210
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012211bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12212 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000012213 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012214 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12215 return false;
12216 if (!LV.isComplexInt())
12217 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012218 return Success(LV.getComplexIntReal(), E);
12219 }
12220
12221 return Visit(E->getSubExpr());
12222}
12223
Eli Friedman4e7a2412009-02-27 04:45:43 +000012224bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012225 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000012226 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012227 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12228 return false;
12229 if (!LV.isComplexInt())
12230 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012231 return Success(LV.getComplexIntImag(), E);
12232 }
12233
Richard Smith4a678122011-10-24 18:44:57 +000012234 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000012235 return Success(0, E);
12236}
12237
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012238bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12239 return Success(E->getPackLength(), E);
12240}
12241
Sebastian Redl5f0180d2010-09-10 20:55:47 +000012242bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12243 return Success(E->getValue(), E);
12244}
12245
Leonard Chandb01c3a2018-06-20 17:19:40 +000012246bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12247 switch (E->getOpcode()) {
12248 default:
12249 // Invalid unary operators
12250 return Error(E);
12251 case UO_Plus:
12252 // The result is just the value.
12253 return Visit(E->getSubExpr());
12254 case UO_Minus: {
12255 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000012256 if (!Result.isFixedPoint())
12257 return Error(E);
12258 bool Overflowed;
12259 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12260 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12261 return false;
12262 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012263 }
12264 case UO_LNot: {
12265 bool bres;
12266 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12267 return false;
12268 return Success(!bres, E);
12269 }
12270 }
12271}
12272
Leonard Chand3f3e162019-01-18 21:04:25 +000012273bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12274 const Expr *SubExpr = E->getSubExpr();
12275 QualType DestType = E->getType();
12276 assert(DestType->isFixedPointType() &&
12277 "Expected destination type to be a fixed point type");
12278 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12279
12280 switch (E->getCastKind()) {
12281 case CK_FixedPointCast: {
12282 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12283 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12284 return false;
12285 bool Overflowed;
12286 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12287 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12288 return false;
12289 return Success(Result, E);
12290 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000012291 case CK_IntegralToFixedPoint: {
12292 APSInt Src;
12293 if (!EvaluateInteger(SubExpr, Src, Info))
12294 return false;
12295
12296 bool Overflowed;
12297 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12298 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12299
12300 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12301 return false;
12302
12303 return Success(IntResult, E);
12304 }
Leonard Chand3f3e162019-01-18 21:04:25 +000012305 case CK_NoOp:
12306 case CK_LValueToRValue:
12307 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12308 default:
12309 return Error(E);
12310 }
12311}
12312
12313bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12314 const Expr *LHS = E->getLHS();
12315 const Expr *RHS = E->getRHS();
12316 FixedPointSemantics ResultFXSema =
12317 Info.Ctx.getFixedPointSemantics(E->getType());
12318
12319 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12320 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12321 return false;
12322 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12323 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12324 return false;
12325
12326 switch (E->getOpcode()) {
12327 case BO_Add: {
12328 bool AddOverflow, ConversionOverflow;
12329 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12330 .convert(ResultFXSema, &ConversionOverflow);
12331 if ((AddOverflow || ConversionOverflow) &&
12332 !HandleOverflow(Info, E, Result, E->getType()))
12333 return false;
12334 return Success(Result, E);
12335 }
12336 default:
12337 return false;
12338 }
12339 llvm_unreachable("Should've exited before this");
12340}
12341
Chris Lattner05706e882008-07-11 18:11:29 +000012342//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000012343// Float Evaluation
12344//===----------------------------------------------------------------------===//
12345
12346namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012347class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012348 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000012349 APFloat &Result;
12350public:
12351 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012352 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000012353
Richard Smith2e312c82012-03-03 22:46:17 +000012354 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012355 Result = V.getFloat();
12356 return true;
12357 }
Eli Friedman24c01542008-08-22 00:06:13 +000012358
Richard Smithfddd3842011-12-30 21:15:51 +000012359 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000012360 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12361 return true;
12362 }
12363
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012364 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012365
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012366 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012367 bool VisitBinaryOperator(const BinaryOperator *E);
12368 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012369 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000012370
John McCallb1fb0d32010-05-07 22:08:54 +000012371 bool VisitUnaryReal(const UnaryOperator *E);
12372 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000012373
Richard Smithfddd3842011-12-30 21:15:51 +000012374 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000012375};
12376} // end anonymous namespace
12377
12378static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012379 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012380 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000012381}
12382
Jay Foad39c79802011-01-12 09:06:06 +000012383static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000012384 QualType ResultTy,
12385 const Expr *Arg,
12386 bool SNaN,
12387 llvm::APFloat &Result) {
12388 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12389 if (!S) return false;
12390
12391 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12392
12393 llvm::APInt fill;
12394
12395 // Treat empty strings as if they were zero.
12396 if (S->getString().empty())
12397 fill = llvm::APInt(32, 0);
12398 else if (S->getString().getAsInteger(0, fill))
12399 return false;
12400
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000012401 if (Context.getTargetInfo().isNan2008()) {
12402 if (SNaN)
12403 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12404 else
12405 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12406 } else {
12407 // Prior to IEEE 754-2008, architectures were allowed to choose whether
12408 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12409 // a different encoding to what became a standard in 2008, and for pre-
12410 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12411 // sNaN. This is now known as "legacy NaN" encoding.
12412 if (SNaN)
12413 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12414 else
12415 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12416 }
12417
John McCall16291492010-02-28 13:00:19 +000012418 return true;
12419}
12420
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012421bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000012422 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012423 default:
12424 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12425
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012426 case Builtin::BI__builtin_huge_val:
12427 case Builtin::BI__builtin_huge_valf:
12428 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012429 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012430 case Builtin::BI__builtin_inf:
12431 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012432 case Builtin::BI__builtin_infl:
12433 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012434 const llvm::fltSemantics &Sem =
12435 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000012436 Result = llvm::APFloat::getInf(Sem);
12437 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012438 }
Mike Stump11289f42009-09-09 15:08:12 +000012439
John McCall16291492010-02-28 13:00:19 +000012440 case Builtin::BI__builtin_nans:
12441 case Builtin::BI__builtin_nansf:
12442 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012443 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012444 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12445 true, Result))
12446 return Error(E);
12447 return true;
John McCall16291492010-02-28 13:00:19 +000012448
Chris Lattner0b7282e2008-10-06 06:31:58 +000012449 case Builtin::BI__builtin_nan:
12450 case Builtin::BI__builtin_nanf:
12451 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012452 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000012453 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000012454 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000012455 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12456 false, Result))
12457 return Error(E);
12458 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012459
12460 case Builtin::BI__builtin_fabs:
12461 case Builtin::BI__builtin_fabsf:
12462 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012463 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012464 if (!EvaluateFloat(E->getArg(0), Result, Info))
12465 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012466
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012467 if (Result.isNegative())
12468 Result.changeSign();
12469 return true;
12470
Richard Smith8889a3d2013-06-13 06:26:32 +000012471 // FIXME: Builtin::BI__builtin_powi
12472 // FIXME: Builtin::BI__builtin_powif
12473 // FIXME: Builtin::BI__builtin_powil
12474
Mike Stump11289f42009-09-09 15:08:12 +000012475 case Builtin::BI__builtin_copysign:
12476 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012477 case Builtin::BI__builtin_copysignl:
12478 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012479 APFloat RHS(0.);
12480 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12481 !EvaluateFloat(E->getArg(1), RHS, Info))
12482 return false;
12483 Result.copySign(RHS);
12484 return true;
12485 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012486 }
12487}
12488
John McCallb1fb0d32010-05-07 22:08:54 +000012489bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012490 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12491 ComplexValue CV;
12492 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12493 return false;
12494 Result = CV.FloatReal;
12495 return true;
12496 }
12497
12498 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000012499}
12500
12501bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012502 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12503 ComplexValue CV;
12504 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12505 return false;
12506 Result = CV.FloatImag;
12507 return true;
12508 }
12509
Richard Smith4a678122011-10-24 18:44:57 +000012510 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000012511 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12512 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000012513 return true;
12514}
12515
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012516bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012517 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012518 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012519 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000012520 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000012521 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000012522 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12523 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012524 Result.changeSign();
12525 return true;
12526 }
12527}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012528
Eli Friedman24c01542008-08-22 00:06:13 +000012529bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012530 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12531 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000012532
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012533 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000012534 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000012535 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000012536 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000012537 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12538 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000012539}
12540
12541bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12542 Result = E->getValue();
12543 return true;
12544}
12545
Peter Collingbournee9200682011-05-13 03:29:01 +000012546bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12547 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000012548
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012549 switch (E->getCastKind()) {
12550 default:
Richard Smith11562c52011-10-28 17:51:58 +000012551 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012552
12553 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012554 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000012555 return EvaluateInteger(SubExpr, IntResult, Info) &&
12556 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12557 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012558 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012559
12560 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012561 if (!Visit(SubExpr))
12562 return false;
Richard Smith357362d2011-12-13 06:39:58 +000012563 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12564 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012565 }
John McCalld7646252010-11-14 08:17:51 +000012566
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012567 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000012568 ComplexValue V;
12569 if (!EvaluateComplex(SubExpr, V, Info))
12570 return false;
12571 Result = V.getComplexFloatReal();
12572 return true;
12573 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012574 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012575}
12576
Eli Friedman24c01542008-08-22 00:06:13 +000012577//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012578// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000012579//===----------------------------------------------------------------------===//
12580
12581namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012582class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012583 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000012584 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000012585
Anders Carlsson537969c2008-11-16 20:27:53 +000012586public:
John McCall93d91dc2010-05-07 17:22:02 +000012587 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012588 : ExprEvaluatorBaseTy(info), Result(Result) {}
12589
Richard Smith2e312c82012-03-03 22:46:17 +000012590 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012591 Result.setFrom(V);
12592 return true;
12593 }
Mike Stump11289f42009-09-09 15:08:12 +000012594
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012595 bool ZeroInitialization(const Expr *E);
12596
Anders Carlsson537969c2008-11-16 20:27:53 +000012597 //===--------------------------------------------------------------------===//
12598 // Visitor Methods
12599 //===--------------------------------------------------------------------===//
12600
Peter Collingbournee9200682011-05-13 03:29:01 +000012601 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012602 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000012603 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012604 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012605 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012606};
12607} // end anonymous namespace
12608
John McCall93d91dc2010-05-07 17:22:02 +000012609static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12610 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012611 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012612 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012613}
12614
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012615bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000012616 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012617 if (ElemTy->isRealFloatingType()) {
12618 Result.makeComplexFloat();
12619 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12620 Result.FloatReal = Zero;
12621 Result.FloatImag = Zero;
12622 } else {
12623 Result.makeComplexInt();
12624 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12625 Result.IntReal = Zero;
12626 Result.IntImag = Zero;
12627 }
12628 return true;
12629}
12630
Peter Collingbournee9200682011-05-13 03:29:01 +000012631bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12632 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012633
12634 if (SubExpr->getType()->isRealFloatingType()) {
12635 Result.makeComplexFloat();
12636 APFloat &Imag = Result.FloatImag;
12637 if (!EvaluateFloat(SubExpr, Imag, Info))
12638 return false;
12639
12640 Result.FloatReal = APFloat(Imag.getSemantics());
12641 return true;
12642 } else {
12643 assert(SubExpr->getType()->isIntegerType() &&
12644 "Unexpected imaginary literal.");
12645
12646 Result.makeComplexInt();
12647 APSInt &Imag = Result.IntImag;
12648 if (!EvaluateInteger(SubExpr, Imag, Info))
12649 return false;
12650
12651 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12652 return true;
12653 }
12654}
12655
Peter Collingbournee9200682011-05-13 03:29:01 +000012656bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012657
John McCallfcef3cf2010-12-14 17:51:41 +000012658 switch (E->getCastKind()) {
12659 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012660 case CK_BaseToDerived:
12661 case CK_DerivedToBase:
12662 case CK_UncheckedDerivedToBase:
12663 case CK_Dynamic:
12664 case CK_ToUnion:
12665 case CK_ArrayToPointerDecay:
12666 case CK_FunctionToPointerDecay:
12667 case CK_NullToPointer:
12668 case CK_NullToMemberPointer:
12669 case CK_BaseToDerivedMemberPointer:
12670 case CK_DerivedToBaseMemberPointer:
12671 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000012672 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000012673 case CK_ConstructorConversion:
12674 case CK_IntegralToPointer:
12675 case CK_PointerToIntegral:
12676 case CK_PointerToBoolean:
12677 case CK_ToVoid:
12678 case CK_VectorSplat:
12679 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012680 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000012681 case CK_IntegralToBoolean:
12682 case CK_IntegralToFloating:
12683 case CK_FloatingToIntegral:
12684 case CK_FloatingToBoolean:
12685 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000012686 case CK_CPointerToObjCPointerCast:
12687 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012688 case CK_AnyPointerToBlockPointerCast:
12689 case CK_ObjCObjectLValueCast:
12690 case CK_FloatingComplexToReal:
12691 case CK_FloatingComplexToBoolean:
12692 case CK_IntegralComplexToReal:
12693 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000012694 case CK_ARCProduceObject:
12695 case CK_ARCConsumeObject:
12696 case CK_ARCReclaimReturnedObject:
12697 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012698 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000012699 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012700 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012701 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012702 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012703 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012704 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000012705 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012706 case CK_FixedPointToIntegral:
12707 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000012708 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000012709
John McCallfcef3cf2010-12-14 17:51:41 +000012710 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012711 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000012712 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012713 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012714 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012715
12716 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012717 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012718 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012719 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012720
12721 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012722 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000012723 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012724 return false;
12725
John McCallfcef3cf2010-12-14 17:51:41 +000012726 Result.makeComplexFloat();
12727 Result.FloatImag = APFloat(Real.getSemantics());
12728 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012729 }
12730
John McCallfcef3cf2010-12-14 17:51:41 +000012731 case CK_FloatingComplexCast: {
12732 if (!Visit(E->getSubExpr()))
12733 return false;
12734
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012735 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012736 QualType From
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012737 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012738
Richard Smith357362d2011-12-13 06:39:58 +000012739 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
12740 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012741 }
12742
12743 case CK_FloatingComplexToIntegralComplex: {
12744 if (!Visit(E->getSubExpr()))
12745 return false;
12746
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012747 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012748 QualType From
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012749 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012750 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000012751 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12752 To, Result.IntReal) &&
12753 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12754 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012755 }
12756
12757 case CK_IntegralRealToComplex: {
12758 APSInt &Real = Result.IntReal;
12759 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12760 return false;
12761
12762 Result.makeComplexInt();
12763 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12764 return true;
12765 }
12766
12767 case CK_IntegralComplexCast: {
12768 if (!Visit(E->getSubExpr()))
12769 return false;
12770
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012771 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012772 QualType From
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012773 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012774
Richard Smith911e1422012-01-30 22:27:01 +000012775 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12776 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012777 return true;
12778 }
12779
12780 case CK_IntegralComplexToFloatingComplex: {
12781 if (!Visit(E->getSubExpr()))
12782 return false;
12783
Ted Kremenek28831752012-08-23 20:46:57 +000012784 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012785 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000012786 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012787 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000012788 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12789 To, Result.FloatReal) &&
12790 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12791 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012792 }
12793 }
12794
12795 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012796}
12797
John McCall93d91dc2010-05-07 17:22:02 +000012798bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012799 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000012800 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12801
Chandler Carrutha216cad2014-10-11 00:57:18 +000012802 // Track whether the LHS or RHS is real at the type system level. When this is
12803 // the case we can simplify our evaluation strategy.
12804 bool LHSReal = false, RHSReal = false;
12805
12806 bool LHSOK;
12807 if (E->getLHS()->getType()->isRealFloatingType()) {
12808 LHSReal = true;
12809 APFloat &Real = Result.FloatReal;
12810 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12811 if (LHSOK) {
12812 Result.makeComplexFloat();
12813 Result.FloatImag = APFloat(Real.getSemantics());
12814 }
12815 } else {
12816 LHSOK = Visit(E->getLHS());
12817 }
George Burgess IVa145e252016-05-25 22:38:36 +000012818 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000012819 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012820
John McCall93d91dc2010-05-07 17:22:02 +000012821 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012822 if (E->getRHS()->getType()->isRealFloatingType()) {
12823 RHSReal = true;
12824 APFloat &Real = RHS.FloatReal;
12825 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12826 return false;
12827 RHS.makeComplexFloat();
12828 RHS.FloatImag = APFloat(Real.getSemantics());
12829 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000012830 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012831
Chandler Carrutha216cad2014-10-11 00:57:18 +000012832 assert(!(LHSReal && RHSReal) &&
12833 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012834 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012835 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012836 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012837 if (Result.isComplexFloat()) {
12838 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12839 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012840 if (LHSReal)
12841 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12842 else if (!RHSReal)
12843 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12844 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012845 } else {
12846 Result.getComplexIntReal() += RHS.getComplexIntReal();
12847 Result.getComplexIntImag() += RHS.getComplexIntImag();
12848 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012849 break;
John McCalle3027922010-08-25 11:45:40 +000012850 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012851 if (Result.isComplexFloat()) {
12852 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12853 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012854 if (LHSReal) {
12855 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12856 Result.getComplexFloatImag().changeSign();
12857 } else if (!RHSReal) {
12858 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12859 APFloat::rmNearestTiesToEven);
12860 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012861 } else {
12862 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12863 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12864 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012865 break;
John McCalle3027922010-08-25 11:45:40 +000012866 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012867 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012868 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012869 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012870 // following naming scheme:
12871 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000012872 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012873 APFloat &A = LHS.getComplexFloatReal();
12874 APFloat &B = LHS.getComplexFloatImag();
12875 APFloat &C = RHS.getComplexFloatReal();
12876 APFloat &D = RHS.getComplexFloatImag();
12877 APFloat &ResR = Result.getComplexFloatReal();
12878 APFloat &ResI = Result.getComplexFloatImag();
12879 if (LHSReal) {
12880 assert(!RHSReal && "Cannot have two real operands for a complex op!");
12881 ResR = A * C;
12882 ResI = A * D;
12883 } else if (RHSReal) {
12884 ResR = C * A;
12885 ResI = C * B;
12886 } else {
12887 // In the fully general case, we need to handle NaNs and infinities
12888 // robustly.
12889 APFloat AC = A * C;
12890 APFloat BD = B * D;
12891 APFloat AD = A * D;
12892 APFloat BC = B * C;
12893 ResR = AC - BD;
12894 ResI = AD + BC;
12895 if (ResR.isNaN() && ResI.isNaN()) {
12896 bool Recalc = false;
12897 if (A.isInfinity() || B.isInfinity()) {
12898 A = APFloat::copySign(
12899 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12900 B = APFloat::copySign(
12901 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12902 if (C.isNaN())
12903 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12904 if (D.isNaN())
12905 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12906 Recalc = true;
12907 }
12908 if (C.isInfinity() || D.isInfinity()) {
12909 C = APFloat::copySign(
12910 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12911 D = APFloat::copySign(
12912 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12913 if (A.isNaN())
12914 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12915 if (B.isNaN())
12916 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12917 Recalc = true;
12918 }
12919 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12920 AD.isInfinity() || BC.isInfinity())) {
12921 if (A.isNaN())
12922 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12923 if (B.isNaN())
12924 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12925 if (C.isNaN())
12926 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12927 if (D.isNaN())
12928 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12929 Recalc = true;
12930 }
12931 if (Recalc) {
12932 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12933 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12934 }
12935 }
12936 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012937 } else {
John McCall93d91dc2010-05-07 17:22:02 +000012938 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000012939 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012940 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12941 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000012942 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012943 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12944 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12945 }
12946 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012947 case BO_Div:
12948 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012949 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012950 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012951 // following naming scheme:
12952 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012953 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012954 APFloat &A = LHS.getComplexFloatReal();
12955 APFloat &B = LHS.getComplexFloatImag();
12956 APFloat &C = RHS.getComplexFloatReal();
12957 APFloat &D = RHS.getComplexFloatImag();
12958 APFloat &ResR = Result.getComplexFloatReal();
12959 APFloat &ResI = Result.getComplexFloatImag();
12960 if (RHSReal) {
12961 ResR = A / C;
12962 ResI = B / C;
12963 } else {
12964 if (LHSReal) {
12965 // No real optimizations we can do here, stub out with zero.
12966 B = APFloat::getZero(A.getSemantics());
12967 }
12968 int DenomLogB = 0;
12969 APFloat MaxCD = maxnum(abs(C), abs(D));
12970 if (MaxCD.isFinite()) {
12971 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000012972 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
12973 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012974 }
12975 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000012976 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
12977 APFloat::rmNearestTiesToEven);
12978 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
12979 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012980 if (ResR.isNaN() && ResI.isNaN()) {
12981 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
12982 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
12983 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
12984 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
12985 D.isFinite()) {
12986 A = APFloat::copySign(
12987 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12988 B = APFloat::copySign(
12989 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12990 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
12991 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
12992 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
12993 C = APFloat::copySign(
12994 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12995 D = APFloat::copySign(
12996 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12997 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
12998 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12999 }
13000 }
13001 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013002 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000013003 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13004 return Error(E, diag::note_expr_divide_by_zero);
13005
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013006 ComplexValue LHS = Result;
13007 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13008 RHS.getComplexIntImag() * RHS.getComplexIntImag();
13009 Result.getComplexIntReal() =
13010 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13011 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13012 Result.getComplexIntImag() =
13013 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13014 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13015 }
13016 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000013017 }
13018
John McCall93d91dc2010-05-07 17:22:02 +000013019 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000013020}
13021
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013022bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13023 // Get the operand value into 'Result'.
13024 if (!Visit(E->getSubExpr()))
13025 return false;
13026
13027 switch (E->getOpcode()) {
13028 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000013029 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013030 case UO_Extension:
13031 return true;
13032 case UO_Plus:
13033 // The result is always just the subexpr.
13034 return true;
13035 case UO_Minus:
13036 if (Result.isComplexFloat()) {
13037 Result.getComplexFloatReal().changeSign();
13038 Result.getComplexFloatImag().changeSign();
13039 }
13040 else {
13041 Result.getComplexIntReal() = -Result.getComplexIntReal();
13042 Result.getComplexIntImag() = -Result.getComplexIntImag();
13043 }
13044 return true;
13045 case UO_Not:
13046 if (Result.isComplexFloat())
13047 Result.getComplexFloatImag().changeSign();
13048 else
13049 Result.getComplexIntImag() = -Result.getComplexIntImag();
13050 return true;
13051 }
13052}
13053
Eli Friedmanc4b251d2012-01-10 04:58:17 +000013054bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13055 if (E->getNumInits() == 2) {
13056 if (E->getType()->isComplexType()) {
13057 Result.makeComplexFloat();
13058 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13059 return false;
13060 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13061 return false;
13062 } else {
13063 Result.makeComplexInt();
13064 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13065 return false;
13066 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13067 return false;
13068 }
13069 return true;
13070 }
13071 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13072}
13073
Anders Carlsson537969c2008-11-16 20:27:53 +000013074//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000013075// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13076// implicit conversion.
13077//===----------------------------------------------------------------------===//
13078
13079namespace {
13080class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000013081 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000013082 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000013083 APValue &Result;
13084public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000013085 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13086 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000013087
13088 bool Success(const APValue &V, const Expr *E) {
13089 Result = V;
13090 return true;
13091 }
13092
13093 bool ZeroInitialization(const Expr *E) {
13094 ImplicitValueInitExpr VIE(
13095 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000013096 // For atomic-qualified class (and array) types in C++, initialize the
13097 // _Atomic-wrapped subobject directly, in-place.
13098 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13099 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000013100 }
13101
13102 bool VisitCastExpr(const CastExpr *E) {
13103 switch (E->getCastKind()) {
13104 default:
13105 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13106 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000013107 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13108 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000013109 }
13110 }
13111};
13112} // end anonymous namespace
13113
Richard Smith64cb9ca2017-02-22 22:09:50 +000013114static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13115 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000013116 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000013117 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000013118}
13119
13120//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000013121// Void expression evaluation, primarily for a cast to void on the LHS of a
13122// comma operator
13123//===----------------------------------------------------------------------===//
13124
13125namespace {
13126class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000013127 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000013128public:
13129 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13130
Richard Smith2e312c82012-03-03 22:46:17 +000013131 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000013132
Richard Smith7cd577b2017-08-17 19:35:50 +000013133 bool ZeroInitialization(const Expr *E) { return true; }
13134
Richard Smith42d3af92011-12-07 00:43:50 +000013135 bool VisitCastExpr(const CastExpr *E) {
13136 switch (E->getCastKind()) {
13137 default:
13138 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13139 case CK_ToVoid:
13140 VisitIgnoredValue(E->getSubExpr());
13141 return true;
13142 }
13143 }
Hal Finkela8443c32014-07-17 14:49:58 +000013144
13145 bool VisitCallExpr(const CallExpr *E) {
13146 switch (E->getBuiltinCallee()) {
Hal Finkela8443c32014-07-17 14:49:58 +000013147 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000013148 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000013149 // The argument is not evaluated!
13150 return true;
Richard Smith19ad5232019-10-03 00:39:33 +000013151
13152 case Builtin::BI__builtin_operator_delete:
13153 return HandleOperatorDeleteCall(Info, E);
13154
13155 default:
13156 break;
Hal Finkela8443c32014-07-17 14:49:58 +000013157 }
Richard Smith19ad5232019-10-03 00:39:33 +000013158
13159 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Hal Finkela8443c32014-07-17 14:49:58 +000013160 }
Richard Smithda1b4342019-09-27 01:26:47 +000013161
13162 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
Richard Smith42d3af92011-12-07 00:43:50 +000013163};
13164} // end anonymous namespace
13165
Richard Smithda1b4342019-09-27 01:26:47 +000013166bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13167 // We cannot speculatively evaluate a delete expression.
13168 if (Info.SpeculativeEvaluationDepth)
13169 return false;
13170
13171 FunctionDecl *OperatorDelete = E->getOperatorDelete();
13172 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13173 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13174 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13175 return false;
13176 }
13177
13178 const Expr *Arg = E->getArgument();
13179
13180 LValue Pointer;
13181 if (!EvaluatePointer(Arg, Pointer, Info))
13182 return false;
13183 if (Pointer.Designator.Invalid)
13184 return false;
13185
13186 // Deleting a null pointer has no effect.
13187 if (Pointer.isNullPointer()) {
13188 // This is the only case where we need to produce an extension warning:
13189 // the only other way we can succeed is if we find a dynamic allocation,
13190 // and we will have warned when we allocated it in that case.
13191 if (!Info.getLangOpts().CPlusPlus2a)
13192 Info.CCEDiag(E, diag::note_constexpr_new);
13193 return true;
13194 }
13195
Richard Smith19ad5232019-10-03 00:39:33 +000013196 Optional<DynAlloc *> Alloc = CheckDeleteKind(
13197 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13198 if (!Alloc)
Richard Smithda1b4342019-09-27 01:26:47 +000013199 return false;
Richard Smithda1b4342019-09-27 01:26:47 +000013200 QualType AllocType = Pointer.Base.getDynamicAllocType();
13201
Richard Smithda1b4342019-09-27 01:26:47 +000013202 // For the non-array case, the designator must be empty if the static type
13203 // does not have a virtual destructor.
13204 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13205 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13206 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13207 << Arg->getType()->getPointeeType() << AllocType;
13208 return false;
13209 }
13210
Richard Smith61422f92019-09-27 20:24:36 +000013211 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13212 (*Alloc)->Value, AllocType))
Richard Smithda1b4342019-09-27 01:26:47 +000013213 return false;
13214
Richard Smith19ad5232019-10-03 00:39:33 +000013215 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
Richard Smithda1b4342019-09-27 01:26:47 +000013216 // The element was already erased. This means the destructor call also
13217 // deleted the object.
13218 // FIXME: This probably results in undefined behavior before we get this
13219 // far, and should be diagnosed elsewhere first.
13220 Info.FFDiag(E, diag::note_constexpr_double_delete);
13221 return false;
13222 }
13223
13224 return true;
13225}
13226
Richard Smith42d3af92011-12-07 00:43:50 +000013227static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13228 assert(E->isRValue() && E->getType()->isVoidType());
13229 return VoidExprEvaluator(Info).Visit(E);
13230}
13231
13232//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000013233// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000013234//===----------------------------------------------------------------------===//
13235
Richard Smith2e312c82012-03-03 22:46:17 +000013236static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000013237 // In C, function designators are not lvalues, but we evaluate them as if they
13238 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000013239 QualType T = E->getType();
13240 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000013241 LValue LV;
13242 if (!EvaluateLValue(E, LV, Info))
13243 return false;
13244 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000013245 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000013246 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000013247 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013248 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000013249 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013250 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013251 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000013252 LValue LV;
13253 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013254 return false;
Richard Smith725810a2011-10-16 21:26:27 +000013255 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000013256 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000013257 llvm::APFloat F(0.0);
13258 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013259 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000013260 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000013261 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000013262 ComplexValue C;
13263 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013264 return false;
Richard Smith725810a2011-10-16 21:26:27 +000013265 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000013266 } else if (T->isFixedPointType()) {
13267 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013268 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000013269 MemberPtr P;
13270 if (!EvaluateMemberPointer(E, P, Info))
13271 return false;
13272 P.moveInto(Result);
13273 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000013274 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000013275 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013276 APValue &Value =
13277 Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000013278 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000013279 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000013280 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000013281 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000013282 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013283 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000013284 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000013285 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000013286 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000013287 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013288 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000013289 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000013290 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000013291 if (!EvaluateVoid(E, Info))
13292 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013293 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000013294 QualType Unqual = T.getAtomicUnqualifiedType();
13295 if (Unqual->isArrayType() || Unqual->isRecordType()) {
13296 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013297 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013298 if (!EvaluateAtomic(E, &LV, Value, Info))
13299 return false;
13300 } else {
13301 if (!EvaluateAtomic(E, nullptr, Result, Info))
13302 return false;
13303 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013304 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000013305 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000013306 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013307 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000013308 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000013309 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013310 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013311
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000013312 return true;
13313}
13314
Richard Smithb228a862012-02-15 02:18:13 +000013315/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13316/// cases, the in-place evaluation is essential, since later initializers for
13317/// an object can indirectly refer to subobjects which were initialized earlier.
13318static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000013319 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000013320 assert(!E->isValueDependent());
13321
Richard Smith7525ff62013-05-09 07:14:00 +000013322 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000013323 return false;
13324
13325 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000013326 // Evaluate arrays and record types in-place, so that later initializers can
13327 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000013328 QualType T = E->getType();
13329 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000013330 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013331 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000013332 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013333 else if (T->isAtomicType()) {
13334 QualType Unqual = T.getAtomicUnqualifiedType();
13335 if (Unqual->isArrayType() || Unqual->isRecordType())
13336 return EvaluateAtomic(E, &This, Result, Info);
13337 }
Richard Smithed5165f2011-11-04 05:33:44 +000013338 }
13339
13340 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000013341 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000013342}
13343
Richard Smithf57d8cb2011-12-09 22:58:01 +000013344/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13345/// lvalue-to-rvalue cast if it is an lvalue.
13346static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Licker950b70d2019-09-13 09:46:16 +000013347 if (Info.EnableNewConstInterp) {
13348 auto &InterpCtx = Info.Ctx.getInterpContext();
13349 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
13350 case interp::InterpResult::Success:
13351 return true;
13352 case interp::InterpResult::Fail:
13353 return false;
13354 case interp::InterpResult::Bail:
13355 break;
13356 }
13357 }
13358
James Dennett0492ef02014-03-14 17:44:10 +000013359 if (E->getType().isNull())
13360 return false;
13361
Nick Lewyckyc190f962017-05-02 01:06:16 +000013362 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000013363 return false;
13364
Richard Smith2e312c82012-03-03 22:46:17 +000013365 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000013366 return false;
13367
13368 if (E->isGLValue()) {
13369 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000013370 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000013371 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000013372 return false;
13373 }
13374
Richard Smith2e312c82012-03-03 22:46:17 +000013375 // Check this core constant expression is a constant expression.
Richard Smithda1b4342019-09-27 01:26:47 +000013376 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13377 CheckMemoryLeaks(Info);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013378}
Richard Smith11562c52011-10-28 17:51:58 +000013379
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013380static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000013381 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013382 // Fast-path evaluations of integer literals, since we sometimes see files
13383 // containing vast quantities of these.
13384 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13385 Result.Val = APValue(APSInt(L->getValue(),
13386 L->getType()->isUnsignedIntegerType()));
13387 IsConst = true;
13388 return true;
13389 }
James Dennett0492ef02014-03-14 17:44:10 +000013390
13391 // This case should be rare, but we need to check it before we check on
13392 // the type below.
13393 if (Exp->getType().isNull()) {
13394 IsConst = false;
13395 return true;
13396 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013397
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013398 // FIXME: Evaluating values of large array and record types can cause
13399 // performance problems. Only do so in C++11 for now.
13400 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13401 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000013402 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013403 IsConst = false;
13404 return true;
13405 }
13406 return false;
13407}
13408
Fangrui Song407659a2018-11-30 23:41:18 +000013409static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13410 Expr::SideEffectsKind SEK) {
13411 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13412 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13413}
13414
13415static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13416 const ASTContext &Ctx, EvalInfo &Info) {
13417 bool IsConst;
13418 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13419 return IsConst;
13420
13421 return EvaluateAsRValue(Info, E, Result.Val);
13422}
13423
13424static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13425 const ASTContext &Ctx,
13426 Expr::SideEffectsKind AllowSideEffects,
13427 EvalInfo &Info) {
13428 if (!E->getType()->isIntegralOrEnumerationType())
13429 return false;
13430
13431 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13432 !ExprResult.Val.isInt() ||
13433 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13434 return false;
13435
13436 return true;
13437}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013438
Leonard Chand3f3e162019-01-18 21:04:25 +000013439static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13440 const ASTContext &Ctx,
13441 Expr::SideEffectsKind AllowSideEffects,
13442 EvalInfo &Info) {
13443 if (!E->getType()->isFixedPointType())
13444 return false;
13445
13446 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13447 return false;
13448
13449 if (!ExprResult.Val.isFixedPoint() ||
13450 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13451 return false;
13452
13453 return true;
13454}
13455
Richard Smith7b553f12011-10-29 00:50:52 +000013456/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000013457/// any crazy technique (that has nothing to do with language standards) that
13458/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000013459/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13460/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000013461bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13462 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013463 assert(!isValueDependent() &&
13464 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000013465 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013466 Info.InConstantContext = InConstantContext;
13467 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000013468}
13469
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013470bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13471 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013472 assert(!isValueDependent() &&
13473 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000013474 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013475 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000013476 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000013477}
13478
Fangrui Song407659a2018-11-30 23:41:18 +000013479bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013480 SideEffectsKind AllowSideEffects,
13481 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013482 assert(!isValueDependent() &&
13483 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000013484 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013485 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000013486 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000013487}
13488
Leonard Chand3f3e162019-01-18 21:04:25 +000013489bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013490 SideEffectsKind AllowSideEffects,
13491 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013492 assert(!isValueDependent() &&
13493 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000013494 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013495 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000013496 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13497}
13498
Richard Trieube234c32016-04-21 21:04:55 +000013499bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013500 SideEffectsKind AllowSideEffects,
13501 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013502 assert(!isValueDependent() &&
13503 "Expression evaluator can't be called on a dependent expression.");
13504
Richard Trieube234c32016-04-21 21:04:55 +000013505 if (!getType()->isRealFloatingType())
13506 return false;
13507
13508 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013509 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13510 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000013511 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000013512 return false;
13513
13514 Result = ExprResult.Val.getFloat();
13515 return true;
13516}
13517
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013518bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13519 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013520 assert(!isValueDependent() &&
13521 "Expression evaluator can't be called on a dependent expression.");
13522
Richard Smith6d4c6582013-11-05 22:18:15 +000013523 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013524 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000013525 LValue LV;
Richard Smith4566f872019-09-29 05:58:31 +000013526 CheckedTemporaries CheckedTemps;
Richard Smith457226e2019-09-23 03:48:44 +000013527 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13528 Result.HasSideEffects ||
Richard Smithb228a862012-02-15 02:18:13 +000013529 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000013530 Ctx.getLValueReferenceType(getType()), LV,
Richard Smith4566f872019-09-29 05:58:31 +000013531 Expr::EvaluateForCodeGen, CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +000013532 return false;
13533
Richard Smith2e312c82012-03-03 22:46:17 +000013534 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000013535 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000013536}
13537
Reid Kleckner1a840d22018-05-10 18:57:35 +000013538bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13539 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013540 assert(!isValueDependent() &&
13541 "Expression evaluator can't be called on a dependent expression.");
13542
Reid Kleckner1a840d22018-05-10 18:57:35 +000013543 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13544 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000013545 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000013546
Richard Smithda1b4342019-09-27 01:26:47 +000013547 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
Reid Kleckner1a840d22018-05-10 18:57:35 +000013548 return false;
13549
Richard Smith457226e2019-09-23 03:48:44 +000013550 if (!Info.discardCleanups())
13551 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13552
Reid Kleckner1a840d22018-05-10 18:57:35 +000013553 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
Richard Smithda1b4342019-09-27 01:26:47 +000013554 Usage) &&
13555 CheckMemoryLeaks(Info);
Reid Kleckner1a840d22018-05-10 18:57:35 +000013556}
13557
Richard Smithd0b4dd62011-12-19 06:19:21 +000013558bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13559 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013560 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013561 assert(!isValueDependent() &&
13562 "Expression evaluator can't be called on a dependent expression.");
13563
Richard Smithdafff942012-01-14 04:30:29 +000013564 // FIXME: Evaluating initializers for large array and record types can cause
13565 // performance problems. Only do so in C++11 for now.
13566 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013567 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000013568 return false;
13569
Richard Smithd0b4dd62011-12-19 06:19:21 +000013570 Expr::EvalStatus EStatus;
13571 EStatus.Diag = &Notes;
13572
Nandor Licker950b70d2019-09-13 09:46:16 +000013573 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000013574 ? EvalInfo::EM_ConstantExpression
13575 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000013576 Info.setEvaluatingDecl(VD, Value);
13577 Info.InConstantContext = true;
13578
13579 SourceLocation DeclLoc = VD->getLocation();
13580 QualType DeclTy = VD->getType();
13581
13582 if (Info.EnableNewConstInterp) {
13583 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13584 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
13585 case interp::InterpResult::Fail:
13586 // Bail out if an error was encountered.
13587 return false;
13588 case interp::InterpResult::Success:
13589 // Evaluation succeeded and value was set.
13590 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
13591 case interp::InterpResult::Bail:
13592 // Evaluate the value again for the tree evaluator to use.
13593 break;
13594 }
13595 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000013596
13597 LValue LVal;
13598 LVal.set(VD);
13599
Richard Smithfddd3842011-12-30 21:15:51 +000013600 // C++11 [basic.start.init]p2:
13601 // Variables with static storage duration or thread storage duration shall be
13602 // zero-initialized before any other initialization takes place.
13603 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013604 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Nandor Licker950b70d2019-09-13 09:46:16 +000013605 !DeclTy->isReferenceType()) {
13606 ImplicitValueInitExpr VIE(DeclTy);
13607 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000013608 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000013609 return false;
13610 }
13611
Nandor Licker950b70d2019-09-13 09:46:16 +000013612 if (!EvaluateInPlace(Value, Info, LVal, this,
Richard Smith7525ff62013-05-09 07:14:00 +000013613 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000013614 EStatus.HasSideEffects)
13615 return false;
13616
Richard Smith457226e2019-09-23 03:48:44 +000013617 // At this point, any lifetime-extended temporaries are completely
13618 // initialized.
13619 Info.performLifetimeExtension();
13620
13621 if (!Info.discardCleanups())
13622 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13623
Richard Smithda1b4342019-09-27 01:26:47 +000013624 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13625 CheckMemoryLeaks(Info);
Richard Smithd0b4dd62011-12-19 06:19:21 +000013626}
13627
Richard Smith2b4fa532019-09-29 05:08:46 +000013628bool VarDecl::evaluateDestruction(
13629 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13630 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
13631 "cannot evaluate destruction of non-constant-initialized variable");
13632
13633 Expr::EvalStatus EStatus;
13634 EStatus.Diag = &Notes;
13635
13636 // Make a copy of the value for the destructor to mutate.
13637 APValue DestroyedValue = *getEvaluatedValue();
13638
13639 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13640 Info.setEvaluatingDecl(this, DestroyedValue,
13641 EvalInfo::EvaluatingDeclKind::Dtor);
13642 Info.InConstantContext = true;
13643
13644 SourceLocation DeclLoc = getLocation();
13645 QualType DeclTy = getType();
13646
13647 LValue LVal;
13648 LVal.set(this);
13649
13650 // FIXME: Consider storing whether this variable has constant destruction in
13651 // the EvaluatedStmt so that CodeGen can query it.
13652 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13653 EStatus.HasSideEffects)
13654 return false;
13655
13656 if (!Info.discardCleanups())
13657 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13658
13659 ensureEvaluatedStmt()->HasConstantDestruction = true;
13660 return true;
13661}
13662
Richard Smith7b553f12011-10-29 00:50:52 +000013663/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13664/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000013665bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013666 assert(!isValueDependent() &&
13667 "Expression evaluator can't be called on a dependent expression.");
13668
Anders Carlsson5b3638b2008-12-01 06:44:05 +000013669 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000013670 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000013671 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000013672}
Anders Carlsson59689ed2008-11-22 21:04:56 +000013673
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000013674APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013675 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013676 assert(!isValueDependent() &&
13677 "Expression evaluator can't be called on a dependent expression.");
13678
Fangrui Song407659a2018-11-30 23:41:18 +000013679 EvalResult EVResult;
13680 EVResult.Diag = Diag;
13681 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13682 Info.InConstantContext = true;
13683
13684 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000013685 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000013686 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013687 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000013688
Fangrui Song407659a2018-11-30 23:41:18 +000013689 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000013690}
John McCall864e3962010-05-07 05:32:02 +000013691
David Bolvansky3b6ae572018-10-18 20:49:06 +000013692APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13693 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013694 assert(!isValueDependent() &&
13695 "Expression evaluator can't be called on a dependent expression.");
13696
Fangrui Song407659a2018-11-30 23:41:18 +000013697 EvalResult EVResult;
13698 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000013699 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013700 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013701 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013702
13703 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000013704 (void)Result;
13705 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013706 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000013707
Fangrui Song407659a2018-11-30 23:41:18 +000013708 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000013709}
13710
Richard Smithe9ff7702013-11-05 22:23:30 +000013711void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013712 assert(!isValueDependent() &&
13713 "Expression evaluator can't be called on a dependent expression.");
13714
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013715 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000013716 EvalResult EVResult;
13717 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000013718 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13719 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013720 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013721 }
13722}
13723
Richard Smithe6c01442013-06-05 00:46:14 +000013724bool Expr::EvalResult::isGlobalLValue() const {
13725 assert(Val.isLValue());
13726 return IsGlobalLValue(Val.getLValueBase());
13727}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000013728
13729
John McCall864e3962010-05-07 05:32:02 +000013730/// isIntegerConstantExpr - this recursive routine will test if an expression is
13731/// an integer constant expression.
13732
13733/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
13734/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000013735
13736// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000013737// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
13738// and a (possibly null) SourceLocation indicating the location of the problem.
13739//
John McCall864e3962010-05-07 05:32:02 +000013740// Note that to reduce code duplication, this helper does no evaluation
13741// itself; the caller checks whether the expression is evaluatable, and
13742// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000013743// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000013744
Dan Gohman28ade552010-07-26 21:25:24 +000013745namespace {
13746
Richard Smith9e575da2012-12-28 13:25:52 +000013747enum ICEKind {
13748 /// This expression is an ICE.
13749 IK_ICE,
13750 /// This expression is not an ICE, but if it isn't evaluated, it's
13751 /// a legal subexpression for an ICE. This return value is used to handle
13752 /// the comma operator in C99 mode, and non-constant subexpressions.
13753 IK_ICEIfUnevaluated,
13754 /// This expression is not an ICE, and is not a legal subexpression for one.
13755 IK_NotICE
13756};
13757
John McCall864e3962010-05-07 05:32:02 +000013758struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000013759 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000013760 SourceLocation Loc;
13761
Richard Smith9e575da2012-12-28 13:25:52 +000013762 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000013763};
13764
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013765}
Dan Gohman28ade552010-07-26 21:25:24 +000013766
Richard Smith9e575da2012-12-28 13:25:52 +000013767static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
13768
13769static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000013770
Craig Toppera31a8822013-08-22 07:09:37 +000013771static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013772 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000013773 Expr::EvalStatus Status;
13774 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13775
13776 Info.InConstantContext = true;
13777 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000013778 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013779 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000013780
John McCall864e3962010-05-07 05:32:02 +000013781 return NoDiag();
13782}
13783
Craig Toppera31a8822013-08-22 07:09:37 +000013784static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013785 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000013786 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013787 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013788
13789 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000013790#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000013791#define STMT(Node, Base) case Expr::Node##Class:
13792#define EXPR(Node, Base)
13793#include "clang/AST/StmtNodes.inc"
13794 case Expr::PredefinedExprClass:
13795 case Expr::FloatingLiteralClass:
13796 case Expr::ImaginaryLiteralClass:
13797 case Expr::StringLiteralClass:
13798 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000013799 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000013800 case Expr::MemberExprClass:
13801 case Expr::CompoundAssignOperatorClass:
13802 case Expr::CompoundLiteralExprClass:
13803 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000013804 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000013805 case Expr::ArrayInitLoopExprClass:
13806 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000013807 case Expr::NoInitExprClass:
13808 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000013809 case Expr::ImplicitValueInitExprClass:
13810 case Expr::ParenListExprClass:
13811 case Expr::VAArgExprClass:
13812 case Expr::AddrLabelExprClass:
13813 case Expr::StmtExprClass:
13814 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000013815 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000013816 case Expr::CXXDynamicCastExprClass:
13817 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000013818 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000013819 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000013820 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013821 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000013822 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013823 case Expr::CXXThisExprClass:
13824 case Expr::CXXThrowExprClass:
13825 case Expr::CXXNewExprClass:
13826 case Expr::CXXDeleteExprClass:
13827 case Expr::CXXPseudoDestructorExprClass:
13828 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000013829 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000013830 case Expr::DependentScopeDeclRefExprClass:
13831 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000013832 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000013833 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000013834 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000013835 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000013836 case Expr::CXXTemporaryObjectExprClass:
13837 case Expr::CXXUnresolvedConstructExprClass:
13838 case Expr::CXXDependentScopeMemberExprClass:
13839 case Expr::UnresolvedMemberExprClass:
13840 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000013841 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013842 case Expr::ObjCArrayLiteralClass:
13843 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013844 case Expr::ObjCEncodeExprClass:
13845 case Expr::ObjCMessageExprClass:
13846 case Expr::ObjCSelectorExprClass:
13847 case Expr::ObjCProtocolExprClass:
13848 case Expr::ObjCIvarRefExprClass:
13849 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013850 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000013851 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000013852 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000013853 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000013854 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000013855 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000013856 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000013857 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000013858 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000013859 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000013860 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000013861 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000013862 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000013863 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000013864 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000013865 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000013866 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000013867 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013868 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000013869 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013870 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013871 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000013872
Richard Smithf137f932014-01-25 20:50:08 +000013873 case Expr::InitListExprClass: {
13874 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13875 // form "T x = { a };" is equivalent to "T x = a;".
13876 // Unless we're initializing a reference, T is a scalar as it is known to be
13877 // of integral or enumeration type.
13878 if (E->isRValue())
13879 if (cast<InitListExpr>(E)->getNumInits() == 1)
13880 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013881 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000013882 }
13883
Douglas Gregor820ba7b2011-01-04 17:33:58 +000013884 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000013885 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000013886 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000013887 return NoDiag();
13888
John McCall7c454bb2011-07-15 05:09:51 +000013889 case Expr::SubstNonTypeTemplateParmExprClass:
13890 return
13891 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13892
Bill Wendling7c44da22018-10-31 03:48:47 +000013893 case Expr::ConstantExprClass:
13894 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13895
John McCall864e3962010-05-07 05:32:02 +000013896 case Expr::ParenExprClass:
13897 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000013898 case Expr::GenericSelectionExprClass:
13899 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013900 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000013901 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013902 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013903 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000013904 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000013905 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000013906 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000013907 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000013908 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000013909 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013910 return NoDiag();
13911 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000013912 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000013913 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13914 // constant expressions, but they can never be ICEs because an ICE cannot
13915 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000013916 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000013917 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000013918 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013919 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013920 }
Richard Smith6365c912012-02-24 22:12:32 +000013921 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013922 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13923 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000013924 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000013925 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000013926 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000013927 // Parameter variables are never constants. Without this check,
13928 // getAnyInitializer() can find a default argument, which leads
13929 // to chaos.
13930 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000013931 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013932
13933 // C++ 7.1.5.1p2
13934 // A variable of non-volatile const-qualified integral or enumeration
13935 // type initialized by an ICE can be used in ICEs.
13936 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000013937 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000013938 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000013939
Richard Smithd0b4dd62011-12-19 06:19:21 +000013940 const VarDecl *VD;
13941 // Look for a declaration of this variable that has an initializer, and
13942 // check whether it is an ICE.
13943 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13944 return NoDiag();
13945 else
Richard Smith9e575da2012-12-28 13:25:52 +000013946 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013947 }
13948 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013949 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000013950 }
John McCall864e3962010-05-07 05:32:02 +000013951 case Expr::UnaryOperatorClass: {
13952 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13953 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013954 case UO_PostInc:
13955 case UO_PostDec:
13956 case UO_PreInc:
13957 case UO_PreDec:
13958 case UO_AddrOf:
13959 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000013960 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000013961 // C99 6.6/3 allows increment and decrement within unevaluated
13962 // subexpressions of constant expressions, but they can never be ICEs
13963 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013964 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000013965 case UO_Extension:
13966 case UO_LNot:
13967 case UO_Plus:
13968 case UO_Minus:
13969 case UO_Not:
13970 case UO_Real:
13971 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000013972 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013973 }
Reid Klecknere540d972018-11-01 17:51:48 +000013974 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000013975 }
13976 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000013977 // Note that per C99, offsetof must be an ICE. And AFAIK, using
13978 // EvaluateAsRValue matches the proposed gcc behavior for cases like
13979 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
13980 // compliance: we should warn earlier for offsetof expressions with
13981 // array subscripts that aren't ICEs, and if the array subscripts
13982 // are ICEs, the value of the offsetof must be an integer constant.
13983 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000013984 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000013985 case Expr::UnaryExprOrTypeTraitExprClass: {
13986 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
13987 if ((Exp->getKind() == UETT_SizeOf) &&
13988 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013989 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013990 return NoDiag();
13991 }
13992 case Expr::BinaryOperatorClass: {
13993 const BinaryOperator *Exp = cast<BinaryOperator>(E);
13994 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013995 case BO_PtrMemD:
13996 case BO_PtrMemI:
13997 case BO_Assign:
13998 case BO_MulAssign:
13999 case BO_DivAssign:
14000 case BO_RemAssign:
14001 case BO_AddAssign:
14002 case BO_SubAssign:
14003 case BO_ShlAssign:
14004 case BO_ShrAssign:
14005 case BO_AndAssign:
14006 case BO_XorAssign:
14007 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000014008 // C99 6.6/3 allows assignments within unevaluated subexpressions of
14009 // constant expressions, but they can never be ICEs because an ICE cannot
14010 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014011 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014012
John McCalle3027922010-08-25 11:45:40 +000014013 case BO_Mul:
14014 case BO_Div:
14015 case BO_Rem:
14016 case BO_Add:
14017 case BO_Sub:
14018 case BO_Shl:
14019 case BO_Shr:
14020 case BO_LT:
14021 case BO_GT:
14022 case BO_LE:
14023 case BO_GE:
14024 case BO_EQ:
14025 case BO_NE:
14026 case BO_And:
14027 case BO_Xor:
14028 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000014029 case BO_Comma:
14030 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000014031 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14032 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000014033 if (Exp->getOpcode() == BO_Div ||
14034 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000014035 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000014036 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000014037 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000014038 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000014039 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014040 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014041 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000014042 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000014043 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014044 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014045 }
14046 }
14047 }
John McCalle3027922010-08-25 11:45:40 +000014048 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014049 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000014050 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14051 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000014052 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014053 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014054 } else {
14055 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014056 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014057 }
14058 }
Richard Smith9e575da2012-12-28 13:25:52 +000014059 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000014060 }
John McCalle3027922010-08-25 11:45:40 +000014061 case BO_LAnd:
14062 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000014063 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14064 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014065 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000014066 // Rare case where the RHS has a comma "side-effect"; we need
14067 // to actually check the condition to see whether the side
14068 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000014069 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000014070 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000014071 return RHSResult;
14072 return NoDiag();
14073 }
14074
Richard Smith9e575da2012-12-28 13:25:52 +000014075 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000014076 }
14077 }
Reid Klecknere540d972018-11-01 17:51:48 +000014078 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000014079 }
14080 case Expr::ImplicitCastExprClass:
14081 case Expr::CStyleCastExprClass:
14082 case Expr::CXXFunctionalCastExprClass:
14083 case Expr::CXXStaticCastExprClass:
14084 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000014085 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000014086 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000014087 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000014088 if (isa<ExplicitCastExpr>(E)) {
14089 if (const FloatingLiteral *FL
14090 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14091 unsigned DestWidth = Ctx.getIntWidth(E->getType());
14092 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14093 APSInt IgnoredVal(DestWidth, !DestSigned);
14094 bool Ignored;
14095 // If the value does not fit in the destination type, the behavior is
14096 // undefined, so we are not required to treat it as a constant
14097 // expression.
14098 if (FL->getValue().convertToInteger(IgnoredVal,
14099 llvm::APFloat::rmTowardZero,
14100 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014101 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000014102 return NoDiag();
14103 }
14104 }
Eli Friedman76d4e432011-09-29 21:49:34 +000014105 switch (cast<CastExpr>(E)->getCastKind()) {
14106 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000014107 case CK_AtomicToNonAtomic:
14108 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000014109 case CK_NoOp:
14110 case CK_IntegralToBoolean:
14111 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000014112 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000014113 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014114 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000014115 }
John McCall864e3962010-05-07 05:32:02 +000014116 }
John McCallc07a0c72011-02-17 10:25:35 +000014117 case Expr::BinaryConditionalOperatorClass: {
14118 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14119 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014120 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000014121 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014122 if (FalseResult.Kind == IK_NotICE) return FalseResult;
14123 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14124 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000014125 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000014126 return FalseResult;
14127 }
John McCall864e3962010-05-07 05:32:02 +000014128 case Expr::ConditionalOperatorClass: {
14129 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14130 // If the condition (ignoring parens) is a __builtin_constant_p call,
14131 // then only the true side is actually considered in an integer constant
14132 // expression, and it is fully evaluated. This is an important GNU
14133 // extension. See GCC PR38377 for discussion.
14134 if (const CallExpr *CallCE
14135 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000014136 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000014137 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000014138 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014139 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014140 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000014141
Richard Smithf57d8cb2011-12-09 22:58:01 +000014142 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14143 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000014144
Richard Smith9e575da2012-12-28 13:25:52 +000014145 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014146 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014147 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014148 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014149 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000014150 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014151 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000014152 return NoDiag();
14153 // Rare case where the diagnostics depend on which side is evaluated
14154 // Note that if we get here, CondResult is 0, and at least one of
14155 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000014156 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000014157 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000014158 return TrueResult;
14159 }
14160 case Expr::CXXDefaultArgExprClass:
14161 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000014162 case Expr::CXXDefaultInitExprClass:
14163 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014164 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000014165 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014166 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000014167 case Expr::BuiltinBitCastExprClass: {
14168 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14169 return ICEDiag(IK_NotICE, E->getBeginLoc());
14170 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14171 }
John McCall864e3962010-05-07 05:32:02 +000014172 }
14173
David Blaikiee4d798f2012-01-20 21:50:17 +000014174 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000014175}
14176
Richard Smithf57d8cb2011-12-09 22:58:01 +000014177/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000014178static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000014179 const Expr *E,
14180 llvm::APSInt *Value,
14181 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000014182 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000014183 if (Loc) *Loc = E->getExprLoc();
14184 return false;
14185 }
14186
Richard Smith66e05fe2012-01-18 05:21:49 +000014187 APValue Result;
14188 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000014189 return false;
14190
Richard Smith98710fc2014-11-13 23:03:19 +000014191 if (!Result.isInt()) {
14192 if (Loc) *Loc = E->getExprLoc();
14193 return false;
14194 }
14195
Richard Smith66e05fe2012-01-18 05:21:49 +000014196 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000014197 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000014198}
14199
Craig Toppera31a8822013-08-22 07:09:37 +000014200bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14201 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014202 assert(!isValueDependent() &&
14203 "Expression evaluator can't be called on a dependent expression.");
14204
Richard Smith2bf7fdb2013-01-02 11:42:31 +000014205 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000014206 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000014207
Richard Smith9e575da2012-12-28 13:25:52 +000014208 ICEDiag D = CheckICE(this, Ctx);
14209 if (D.Kind != IK_ICE) {
14210 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000014211 return false;
14212 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000014213 return true;
14214}
14215
Craig Toppera31a8822013-08-22 07:09:37 +000014216bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000014217 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014218 assert(!isValueDependent() &&
14219 "Expression evaluator can't be called on a dependent expression.");
14220
Richard Smith2bf7fdb2013-01-02 11:42:31 +000014221 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000014222 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14223
14224 if (!isIntegerConstantExpr(Ctx, Loc))
14225 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000014226
Richard Smith5c40f092015-12-04 03:00:44 +000014227 // The only possible side-effects here are due to UB discovered in the
14228 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14229 // required to treat the expression as an ICE, so we produce the folded
14230 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000014231 EvalResult ExprResult;
14232 Expr::EvalStatus Status;
14233 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14234 Info.InConstantContext = true;
14235
14236 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000014237 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000014238
14239 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000014240 return true;
14241}
Richard Smith66e05fe2012-01-18 05:21:49 +000014242
Craig Toppera31a8822013-08-22 07:09:37 +000014243bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014244 assert(!isValueDependent() &&
14245 "Expression evaluator can't be called on a dependent expression.");
14246
Richard Smith9e575da2012-12-28 13:25:52 +000014247 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000014248}
14249
Craig Toppera31a8822013-08-22 07:09:37 +000014250bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000014251 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014252 assert(!isValueDependent() &&
14253 "Expression evaluator can't be called on a dependent expression.");
14254
Richard Smith66e05fe2012-01-18 05:21:49 +000014255 // We support this checking in C++98 mode in order to diagnose compatibility
14256 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000014257 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000014258
Richard Smith98a0a492012-02-14 21:38:30 +000014259 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000014260 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014261 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000014262 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000014263 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000014264
14265 APValue Scratch;
Richard Smith457226e2019-09-23 03:48:44 +000014266 bool IsConstExpr =
14267 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14268 // FIXME: We don't produce a diagnostic for this, but the callers that
14269 // call us on arbitrary full-expressions should generally not care.
Richard Smithda1b4342019-09-27 01:26:47 +000014270 Info.discardCleanups() && !Status.HasSideEffects;
Richard Smith66e05fe2012-01-18 05:21:49 +000014271
14272 if (!Diags.empty()) {
14273 IsConstExpr = false;
14274 if (Loc) *Loc = Diags[0].first;
14275 } else if (!IsConstExpr) {
14276 // FIXME: This shouldn't happen.
14277 if (Loc) *Loc = getExprLoc();
14278 }
14279
14280 return IsConstExpr;
14281}
Richard Smith253c2a32012-01-27 01:14:48 +000014282
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014283bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14284 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000014285 ArrayRef<const Expr*> Args,
14286 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014287 assert(!isValueDependent() &&
14288 "Expression evaluator can't be called on a dependent expression.");
14289
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014290 Expr::EvalStatus Status;
14291 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014292 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014293
George Burgess IV177399e2017-01-09 04:12:14 +000014294 LValue ThisVal;
14295 const LValue *ThisPtr = nullptr;
14296 if (This) {
14297#ifndef NDEBUG
14298 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14299 assert(MD && "Don't provide `this` for non-methods.");
14300 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14301#endif
14302 if (EvaluateObjectArgument(Info, This, ThisVal))
14303 ThisPtr = &ThisVal;
14304 if (Info.EvalStatus.HasSideEffects)
14305 return false;
14306 }
14307
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014308 ArgVector ArgValues(Args.size());
14309 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14310 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000014311 if ((*I)->isValueDependent() ||
14312 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014313 // If evaluation fails, throw away the argument entirely.
14314 ArgValues[I - Args.begin()] = APValue();
14315 if (Info.EvalStatus.HasSideEffects)
14316 return false;
14317 }
14318
14319 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000014320 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014321 ArgValues.data());
Richard Smith457226e2019-09-23 03:48:44 +000014322 return Evaluate(Value, Info, this) && Info.discardCleanups() &&
14323 !Info.EvalStatus.HasSideEffects;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014324}
14325
Richard Smith253c2a32012-01-27 01:14:48 +000014326bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014327 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000014328 PartialDiagnosticAt> &Diags) {
14329 // FIXME: It would be useful to check constexpr function templates, but at the
14330 // moment the constant expression evaluator cannot cope with the non-rigorous
14331 // ASTs which we build for dependent expressions.
14332 if (FD->isDependentContext())
14333 return true;
14334
14335 Expr::EvalStatus Status;
14336 Status.Diag = &Diags;
14337
Richard Smith045b2272019-09-10 21:24:09 +000014338 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000014339 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014340 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000014341
Nandor Licker950b70d2019-09-13 09:46:16 +000014342 // The constexpr VM attempts to compile all methods to bytecode here.
14343 if (Info.EnableNewConstInterp) {
14344 auto &InterpCtx = Info.Ctx.getInterpContext();
14345 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
14346 case interp::InterpResult::Success:
14347 case interp::InterpResult::Fail:
14348 return Diags.empty();
14349 case interp::InterpResult::Bail:
14350 break;
14351 }
14352 }
14353
Richard Smith253c2a32012-01-27 01:14:48 +000014354 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000014355 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000014356
Richard Smith7525ff62013-05-09 07:14:00 +000014357 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000014358 // is a temporary being used as the 'this' pointer.
14359 LValue This;
14360 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000014361 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000014362
Richard Smith253c2a32012-01-27 01:14:48 +000014363 ArrayRef<const Expr*> Args;
14364
Richard Smith2e312c82012-03-03 22:46:17 +000014365 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000014366 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14367 // Evaluate the call as a constant initializer, to allow the construction
14368 // of objects of non-literal types.
14369 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000014370 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14371 } else {
14372 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000014373 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000014374 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000014375 }
Richard Smith253c2a32012-01-27 01:14:48 +000014376
14377 return Diags.empty();
14378}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014379
14380bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14381 const FunctionDecl *FD,
14382 SmallVectorImpl<
14383 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014384 assert(!E->isValueDependent() &&
14385 "Expression evaluator can't be called on a dependent expression.");
14386
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014387 Expr::EvalStatus Status;
14388 Status.Diag = &Diags;
14389
14390 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000014391 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014392 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014393 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014394
14395 // Fabricate a call stack frame to give the arguments a plausible cover story.
14396 ArrayRef<const Expr*> Args;
14397 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014398 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014399 (void)Success;
14400 assert(Success &&
14401 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000014402 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014403
14404 APValue ResultScratch;
14405 Evaluate(ResultScratch, Info, E);
14406 return Diags.empty();
14407}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014408
14409bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14410 unsigned Type) const {
14411 if (!getType()->isPointerType())
14412 return false;
14413
14414 Expr::EvalStatus Status;
14415 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000014416 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014417}