blob: 669acd3a66693fef7246eaac5f70379eb102394f [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 Smith254a73d2011-10-28 22:34:42 +0000597 };
598
Richard Smith852c9db2013-04-20 22:23:05 +0000599 /// Temporarily override 'this'.
600 class ThisOverrideRAII {
601 public:
602 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
603 : Frame(Frame), OldThis(Frame.This) {
604 if (Enable)
605 Frame.This = NewThis;
606 }
607 ~ThisOverrideRAII() {
608 Frame.This = OldThis;
609 }
610 private:
611 CallStackFrame &Frame;
612 const LValue *OldThis;
613 };
Richard Smith457226e2019-09-23 03:48:44 +0000614}
Richard Smith852c9db2013-04-20 22:23:05 +0000615
Richard Smith61422f92019-09-27 20:24:36 +0000616static bool HandleDestruction(EvalInfo &Info, const Expr *E,
617 const LValue &This, QualType ThisType);
618static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
619 APValue::LValueBase LVBase, APValue &Value,
620 QualType T);
Richard Smith457226e2019-09-23 03:48:44 +0000621
622namespace {
Richard Smith08d6a2c2013-07-24 07:11:57 +0000623 /// A cleanup, and a flag indicating whether it is lifetime-extended.
624 class Cleanup {
625 llvm::PointerIntPair<APValue*, 1, bool> Value;
Richard Smith457226e2019-09-23 03:48:44 +0000626 APValue::LValueBase Base;
627 QualType T;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000628
629 public:
Richard Smith457226e2019-09-23 03:48:44 +0000630 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
631 bool IsLifetimeExtended)
632 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
Richard Smith08d6a2c2013-07-24 07:11:57 +0000633
634 bool isLifetimeExtended() const { return Value.getInt(); }
Richard Smith457226e2019-09-23 03:48:44 +0000635 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
Richard Smithda1b4342019-09-27 01:26:47 +0000636 if (RunDestructors) {
637 SourceLocation Loc;
638 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
639 Loc = VD->getLocation();
640 else if (const Expr *E = Base.dyn_cast<const Expr*>())
641 Loc = E->getExprLoc();
Richard Smith61422f92019-09-27 20:24:36 +0000642 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
Richard Smithda1b4342019-09-27 01:26:47 +0000643 }
Richard Smith08d6a2c2013-07-24 07:11:57 +0000644 *Value.getPointer() = APValue();
Richard Smith457226e2019-09-23 03:48:44 +0000645 return true;
646 }
647
648 bool hasSideEffect() {
649 return T.isDestructedType();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000650 }
651 };
652
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000653 /// A reference to an object whose construction we are currently evaluating.
654 struct ObjectUnderConstruction {
655 APValue::LValueBase Base;
656 ArrayRef<APValue::LValuePathEntry> Path;
657 friend bool operator==(const ObjectUnderConstruction &LHS,
658 const ObjectUnderConstruction &RHS) {
659 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
660 }
661 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
662 return llvm::hash_combine(Obj.Base, Obj.Path);
663 }
664 };
Richard Smith457226e2019-09-23 03:48:44 +0000665 enum class ConstructionPhase {
666 None,
667 Bases,
668 AfterBases,
669 Destroying,
670 DestroyingBases
671 };
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000672}
673
674namespace llvm {
675template<> struct DenseMapInfo<ObjectUnderConstruction> {
676 using Base = DenseMapInfo<APValue::LValueBase>;
677 static ObjectUnderConstruction getEmptyKey() {
678 return {Base::getEmptyKey(), {}}; }
679 static ObjectUnderConstruction getTombstoneKey() {
680 return {Base::getTombstoneKey(), {}};
681 }
682 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
683 return hash_value(Object);
684 }
685 static bool isEqual(const ObjectUnderConstruction &LHS,
686 const ObjectUnderConstruction &RHS) {
687 return LHS == RHS;
688 }
689};
690}
691
692namespace {
Richard Smith19ad5232019-10-03 00:39:33 +0000693 /// A dynamically-allocated heap object.
694 struct DynAlloc {
695 /// The value of this heap-allocated object.
696 APValue Value;
697 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
698 /// or a CallExpr (the latter is for direct calls to operator new inside
699 /// std::allocator<T>::allocate).
700 const Expr *AllocExpr = nullptr;
701
702 enum Kind {
703 New,
704 ArrayNew,
705 StdAllocator
706 };
707
708 /// Get the kind of the allocation. This must match between allocation
709 /// and deallocation.
710 Kind getKind() const {
711 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
712 return NE->isArray() ? ArrayNew : New;
713 assert(isa<CallExpr>(AllocExpr));
714 return StdAllocator;
715 }
716 };
717
718 struct DynAllocOrder {
719 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
720 return L.getIndex() < R.getIndex();
721 }
722 };
723
Richard Smithb228a862012-02-15 02:18:13 +0000724 /// EvalInfo - This is a private struct used by the evaluator to capture
725 /// information about a subexpression as it is folded. It retains information
726 /// about the AST context, but also maintains information about the folded
727 /// expression.
728 ///
729 /// If an expression could be evaluated, it is still possible it is not a C
730 /// "integer constant expression" or constant expression. If not, this struct
731 /// captures information about how and why not.
732 ///
733 /// One bit of information passed *into* the request for constant folding
734 /// indicates whether the subexpression is "evaluated" or not according to C
735 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
736 /// evaluate the expression regardless of what the RHS is, but C only allows
737 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000738 class EvalInfo : public interp::State {
739 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000740 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000741
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000742 /// EvalStatus - Contains information about the evaluation.
743 Expr::EvalStatus &EvalStatus;
744
745 /// CurrentCall - The top of the constexpr call stack.
746 CallStackFrame *CurrentCall;
747
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000748 /// CallStackDepth - The number of calls in the call stack right now.
749 unsigned CallStackDepth;
750
Richard Smithb228a862012-02-15 02:18:13 +0000751 /// NextCallIndex - The next call index to assign.
752 unsigned NextCallIndex;
753
Richard Smitha3d3bd22013-05-08 02:12:03 +0000754 /// StepsLeft - The remaining number of evaluation steps we're permitted
755 /// to perform. This is essentially a limit for the number of statements
756 /// we will evaluate.
757 unsigned StepsLeft;
758
Nandor Licker950b70d2019-09-13 09:46:16 +0000759 /// Force the use of the experimental new constant interpreter, bailing out
760 /// with an error if a feature is not supported.
761 bool ForceNewConstInterp;
762
763 /// Enable the experimental new constant interpreter.
764 bool EnableNewConstInterp;
765
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000766 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000767 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000768 CallStackFrame BottomFrame;
769
Richard Smith08d6a2c2013-07-24 07:11:57 +0000770 /// A stack of values whose lifetimes end at the end of some surrounding
771 /// evaluation frame.
772 llvm::SmallVector<Cleanup, 16> CleanupStack;
773
Richard Smithd62306a2011-11-10 06:34:14 +0000774 /// EvaluatingDecl - This is the declaration whose initializer is being
775 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000776 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000777
Richard Smith2b4fa532019-09-29 05:08:46 +0000778 enum class EvaluatingDeclKind {
779 None,
780 /// We're evaluating the construction of EvaluatingDecl.
781 Ctor,
782 /// We're evaluating the destruction of EvaluatingDecl.
783 Dtor,
784 };
785 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
786
Richard Smithd62306a2011-11-10 06:34:14 +0000787 /// EvaluatingDeclValue - This is the value being constructed for the
788 /// declaration whose initializer is being evaluated, if any.
789 APValue *EvaluatingDeclValue;
790
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000791 /// Set of objects that are currently being constructed.
792 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
793 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000794
Richard Smithda1b4342019-09-27 01:26:47 +0000795 /// Current heap allocations, along with the location where each was
796 /// allocated. We use std::map here because we need stable addresses
797 /// for the stored APValues.
798 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
799
800 /// The number of heap allocations performed so far in this evaluation.
801 unsigned NumHeapAllocs = 0;
802
Erik Pilkington42925492017-10-04 00:18:55 +0000803 struct EvaluatingConstructorRAII {
804 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000805 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000806 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000807 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
808 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000809 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000810 DidInsert =
811 EI.ObjectsUnderConstruction
812 .insert({Object, HasBases ? ConstructionPhase::Bases
813 : ConstructionPhase::AfterBases})
814 .second;
815 }
816 void finishedConstructingBases() {
817 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000818 }
819 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000820 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000821 }
822 };
823
Richard Smith457226e2019-09-23 03:48:44 +0000824 struct EvaluatingDestructorRAII {
825 EvalInfo &EI;
826 ObjectUnderConstruction Object;
Richard Smithda1b4342019-09-27 01:26:47 +0000827 bool DidInsert;
Richard Smith457226e2019-09-23 03:48:44 +0000828 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
829 : EI(EI), Object(Object) {
Richard Smithda1b4342019-09-27 01:26:47 +0000830 DidInsert = EI.ObjectsUnderConstruction
831 .insert({Object, ConstructionPhase::Destroying})
832 .second;
Richard Smith457226e2019-09-23 03:48:44 +0000833 }
834 void startedDestroyingBases() {
835 EI.ObjectsUnderConstruction[Object] =
836 ConstructionPhase::DestroyingBases;
837 }
838 ~EvaluatingDestructorRAII() {
Richard Smithda1b4342019-09-27 01:26:47 +0000839 if (DidInsert)
840 EI.ObjectsUnderConstruction.erase(Object);
Richard Smith457226e2019-09-23 03:48:44 +0000841 }
842 };
843
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000844 ConstructionPhase
Richard Smith457226e2019-09-23 03:48:44 +0000845 isEvaluatingCtorDtor(APValue::LValueBase Base,
846 ArrayRef<APValue::LValuePathEntry> Path) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000847 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000848 }
849
Richard Smith37be3362019-05-04 04:00:45 +0000850 /// If we're currently speculatively evaluating, the outermost call stack
851 /// depth at which we can mutate state, otherwise 0.
852 unsigned SpeculativeEvaluationDepth = 0;
853
Richard Smith410306b2016-12-12 02:53:20 +0000854 /// The current array initialization index, if we're performing array
855 /// initialization.
856 uint64_t ArrayInitIndex = -1;
857
Richard Smith357362d2011-12-13 06:39:58 +0000858 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
859 /// notes attached to it will also be stored, otherwise they will not be.
860 bool HasActiveDiagnostic;
861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000862 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000863 /// fold (not just why it's not strictly a constant expression)?
864 bool HasFoldFailureDiagnostic;
865
Fangrui Song407659a2018-11-30 23:41:18 +0000866 /// Whether or not we're in a context where the front end requires a
867 /// constant value.
868 bool InConstantContext;
869
Richard Smith045b2272019-09-10 21:24:09 +0000870 /// Whether we're checking that an expression is a potential constant
871 /// expression. If so, do not fail on constructs that could become constant
872 /// later on (such as a use of an undefined global).
873 bool CheckingPotentialConstantExpression = false;
874
875 /// Whether we're checking for an expression that has undefined behavior.
876 /// If so, we will produce warnings if we encounter an operation that is
877 /// always undefined.
878 bool CheckingForUndefinedBehavior = false;
879
Richard Smith6d4c6582013-11-05 22:18:15 +0000880 enum EvaluationMode {
881 /// Evaluate as a constant expression. Stop if we find that the expression
882 /// is not a constant expression.
883 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000884
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000885 /// Evaluate as a constant expression. Stop if we find that the expression
886 /// is not a constant expression. Some expressions can be retried in the
887 /// optimizer if we don't constant fold them here, but in an unevaluated
888 /// context we try to fold them immediately since the optimizer never
889 /// gets a chance to look at it.
890 EM_ConstantExpressionUnevaluated,
891
Richard Smith045b2272019-09-10 21:24:09 +0000892 /// Fold the expression to a constant. Stop if we hit a side-effect that
893 /// we can't model.
894 EM_ConstantFold,
895
896 /// Evaluate in any way we know how. Don't worry about side-effects that
897 /// can't be modeled.
898 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000899 } EvalMode;
900
901 /// Are we checking whether the expression is a potential constant
902 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000903 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000904 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000905 }
906
907 /// Are we checking an expression for overflow?
908 // FIXME: We should check for any kind of undefined or suspicious behavior
909 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000910 bool checkingForUndefinedBehavior() const override {
911 return CheckingForUndefinedBehavior;
912 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000913
914 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000915 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
916 CallStackDepth(0), NextCallIndex(1),
917 StepsLeft(getLangOpts().ConstexprStepLimit),
918 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
919 EnableNewConstInterp(ForceNewConstInterp ||
920 getLangOpts().EnableNewConstInterp),
921 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
922 EvaluatingDecl((const ValueDecl *)nullptr),
923 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
924 HasFoldFailureDiagnostic(false), InConstantContext(false),
925 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000926
Richard Smith457226e2019-09-23 03:48:44 +0000927 ~EvalInfo() {
928 discardCleanups();
929 }
930
Richard Smith2b4fa532019-09-29 05:08:46 +0000931 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
932 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
Richard Smith7525ff62013-05-09 07:14:00 +0000933 EvaluatingDecl = Base;
Richard Smith2b4fa532019-09-29 05:08:46 +0000934 IsEvaluatingDecl = EDK;
Richard Smithd62306a2011-11-10 06:34:14 +0000935 EvaluatingDeclValue = &Value;
936 }
937
Richard Smith357362d2011-12-13 06:39:58 +0000938 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000939 // Don't perform any constexpr calls (other than the call we're checking)
940 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000942 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000943 if (NextCallIndex == 0) {
944 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000945 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000946 return false;
947 }
Richard Smith357362d2011-12-13 06:39:58 +0000948 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
949 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000950 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000951 << getLangOpts().ConstexprCallDepth;
952 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000953 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000954
Richard Smith37be3362019-05-04 04:00:45 +0000955 std::pair<CallStackFrame *, unsigned>
956 getCallFrameAndDepth(unsigned CallIndex) {
957 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000958 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
959 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000960 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000961 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000962 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000963 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000964 --Depth;
965 }
966 if (Frame->Index == CallIndex)
967 return {Frame, Depth};
968 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000969 }
970
Richard Smitha3d3bd22013-05-08 02:12:03 +0000971 bool nextStep(const Stmt *S) {
972 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000973 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000974 return false;
975 }
976 --StepsLeft;
977 return true;
978 }
979
Richard Smithda1b4342019-09-27 01:26:47 +0000980 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
981
982 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
983 Optional<DynAlloc*> Result;
984 auto It = HeapAllocs.find(DA);
985 if (It != HeapAllocs.end())
986 Result = &It->second;
987 return Result;
988 }
989
Richard Smith19ad5232019-10-03 00:39:33 +0000990 /// Information about a stack frame for std::allocator<T>::[de]allocate.
991 struct StdAllocatorCaller {
992 unsigned FrameIndex;
993 QualType ElemType;
994 explicit operator bool() const { return FrameIndex != 0; };
995 };
996
997 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
998 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
999 Call = Call->Caller) {
1000 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1001 if (!MD)
1002 continue;
1003 const IdentifierInfo *FnII = MD->getIdentifier();
1004 if (!FnII || !FnII->isStr(FnName))
1005 continue;
1006
1007 const auto *CTSD =
1008 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1009 if (!CTSD)
1010 continue;
1011
1012 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1013 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1014 if (CTSD->isInStdNamespace() && ClassII &&
1015 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1016 TAL[0].getKind() == TemplateArgument::Type)
1017 return {Call->Index, TAL[0].getAsType()};
1018 }
1019
1020 return {};
1021 }
1022
Richard Smith457226e2019-09-23 03:48:44 +00001023 void performLifetimeExtension() {
1024 // Disable the cleanups for lifetime-extended temporaries.
1025 CleanupStack.erase(
1026 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1027 [](Cleanup &C) { return C.isLifetimeExtended(); }),
1028 CleanupStack.end());
1029 }
1030
1031 /// Throw away any remaining cleanups at the end of evaluation. If any
1032 /// cleanups would have had a side-effect, note that as an unmodeled
1033 /// side-effect and return false. Otherwise, return true.
1034 bool discardCleanups() {
1035 for (Cleanup &C : CleanupStack)
1036 if (C.hasSideEffect())
1037 if (!noteSideEffect())
1038 return false;
1039 return true;
1040 }
1041
Richard Smith357362d2011-12-13 06:39:58 +00001042 private:
Nandor Licker950b70d2019-09-13 09:46:16 +00001043 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1044 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1045
1046 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1047 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1048
1049 void setFoldFailureDiagnostic(bool Flag) override {
1050 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +00001051 }
1052
Nandor Licker950b70d2019-09-13 09:46:16 +00001053 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +00001054
Nandor Licker950b70d2019-09-13 09:46:16 +00001055 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +00001056
Nandor Licker950b70d2019-09-13 09:46:16 +00001057 // If we have a prior diagnostic, it will be noting that the expression
1058 // isn't a constant expression. This diagnostic is more important,
1059 // unless we require this evaluation to produce a constant expression.
1060 //
1061 // FIXME: We might want to show both diagnostics to the user in
1062 // EM_ConstantFold mode.
1063 bool hasPriorDiagnostic() override {
1064 if (!EvalStatus.Diag->empty()) {
1065 switch (EvalMode) {
1066 case EM_ConstantFold:
1067 case EM_IgnoreSideEffects:
1068 if (!HasFoldFailureDiagnostic)
1069 break;
1070 // We've already failed to fold something. Keep that diagnostic.
1071 LLVM_FALLTHROUGH;
1072 case EM_ConstantExpression:
1073 case EM_ConstantExpressionUnevaluated:
1074 setActiveDiagnostic(false);
1075 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +00001076 }
Richard Smith92b1ce02011-12-12 09:28:41 +00001077 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001078 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +00001079 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001080
1081 unsigned getCallStackDepth() override { return CallStackDepth; }
1082
Faisal Valie690b7a2016-07-02 22:34:24 +00001083 public:
Richard Smith6d4c6582013-11-05 22:18:15 +00001084 /// Should we continue evaluation after encountering a side-effect that we
1085 /// couldn't model?
1086 bool keepEvaluatingAfterSideEffect() {
1087 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001088 case EM_IgnoreSideEffects:
1089 return true;
1090
Richard Smith6d4c6582013-11-05 22:18:15 +00001091 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001092 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001093 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +00001094 // By default, assume any side effect might be valid in some other
1095 // evaluation of this expression from a different context.
1096 return checkingPotentialConstantExpression() ||
1097 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001099 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001100 }
1101
1102 /// Note that we have had a side-effect, and determine whether we should
1103 /// keep evaluating.
1104 bool noteSideEffect() {
1105 EvalStatus.HasSideEffects = true;
1106 return keepEvaluatingAfterSideEffect();
1107 }
1108
Richard Smithce8eca52015-12-08 03:21:47 +00001109 /// Should we continue evaluation after encountering undefined behavior?
1110 bool keepEvaluatingAfterUndefinedBehavior() {
1111 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +00001112 case EM_IgnoreSideEffects:
1113 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001114 return true;
1115
Richard Smithce8eca52015-12-08 03:21:47 +00001116 case EM_ConstantExpression:
1117 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +00001118 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +00001119 }
1120 llvm_unreachable("Missed EvalMode case");
1121 }
1122
1123 /// Note that we hit something that was technically undefined behavior, but
1124 /// that we can evaluate past it (such as signed overflow or floating-point
1125 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +00001126 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +00001127 EvalStatus.HasUndefinedBehavior = true;
1128 return keepEvaluatingAfterUndefinedBehavior();
1129 }
1130
Richard Smith253c2a32012-01-27 01:14:48 +00001131 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001132 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +00001133 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +00001134 if (!StepsLeft)
1135 return false;
1136
1137 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001138 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001139 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001140 case EM_ConstantFold:
1141 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +00001142 return checkingPotentialConstantExpression() ||
1143 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001144 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001145 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001146 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001147
George Burgess IV8c892b52016-05-25 22:31:54 +00001148 /// Notes that we failed to evaluate an expression that other expressions
1149 /// directly depend on, and determine if we should keep evaluating. This
1150 /// should only be called if we actually intend to keep evaluating.
1151 ///
1152 /// Call noteSideEffect() instead if we may be able to ignore the value that
1153 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1154 ///
1155 /// (Foo(), 1) // use noteSideEffect
1156 /// (Foo() || true) // use noteSideEffect
1157 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001158 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001159 // Failure when evaluating some expression often means there is some
1160 // subexpression whose evaluation was skipped. Therefore, (because we
1161 // don't track whether we skipped an expression when unwinding after an
1162 // evaluation failure) every evaluation failure that bubbles up from a
1163 // subexpression implies that a side-effect has potentially happened. We
1164 // skip setting the HasSideEffects flag to true until we decide to
1165 // continue evaluating after that point, which happens here.
1166 bool KeepGoing = keepEvaluatingAfterFailure();
1167 EvalStatus.HasSideEffects |= KeepGoing;
1168 return KeepGoing;
1169 }
1170
Richard Smith410306b2016-12-12 02:53:20 +00001171 class ArrayInitLoopIndex {
1172 EvalInfo &Info;
1173 uint64_t OuterIndex;
1174
1175 public:
1176 ArrayInitLoopIndex(EvalInfo &Info)
1177 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1178 Info.ArrayInitIndex = 0;
1179 }
1180 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1181
1182 operator uint64_t&() { return Info.ArrayInitIndex; }
1183 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001184 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001185
1186 /// Object used to treat all foldable expressions as constant expressions.
1187 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001188 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001189 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001190 bool HadNoPriorDiags;
1191 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001192
Richard Smith6d4c6582013-11-05 22:18:15 +00001193 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1194 : Info(Info),
1195 Enabled(Enabled),
1196 HadNoPriorDiags(Info.EvalStatus.Diag &&
1197 Info.EvalStatus.Diag->empty() &&
1198 !Info.EvalStatus.HasSideEffects),
1199 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001200 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001201 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001202 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001203 void keepDiagnostics() { Enabled = false; }
1204 ~FoldConstant() {
1205 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001206 !Info.EvalStatus.HasSideEffects)
1207 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001208 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001209 }
1210 };
Richard Smith17100ba2012-02-16 02:46:34 +00001211
James Y Knight892b09b2018-10-10 02:53:43 +00001212 /// RAII object used to set the current evaluation mode to ignore
1213 /// side-effects.
1214 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001215 EvalInfo &Info;
1216 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001217 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001218 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001219 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001220 }
1221
James Y Knight892b09b2018-10-10 02:53:43 +00001222 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001223 };
1224
George Burgess IV8c892b52016-05-25 22:31:54 +00001225 /// RAII object used to optionally suppress diagnostics and side-effects from
1226 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001227 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001228 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001229 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001230 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001231
George Burgess IV8c892b52016-05-25 22:31:54 +00001232 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001233 Info = Other.Info;
1234 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001235 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001236 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001237 }
1238
1239 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001240 if (!Info)
1241 return;
1242
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001243 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001244 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001245 }
1246
Richard Smith17100ba2012-02-16 02:46:34 +00001247 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001248 SpeculativeEvaluationRAII() = default;
1249
1250 SpeculativeEvaluationRAII(
1251 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001252 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001253 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001254 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001255 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001256 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001257
1258 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1259 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1260 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001261 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001262
1263 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1264 maybeRestoreState();
1265 moveFromAndCancel(std::move(Other));
1266 return *this;
1267 }
1268
1269 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001270 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001271
1272 /// RAII object wrapping a full-expression or block scope, and handling
1273 /// the ending of the lifetime of temporaries created within it.
1274 template<bool IsFullExpression>
1275 class ScopeRAII {
1276 EvalInfo &Info;
1277 unsigned OldStackSize;
1278 public:
1279 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001280 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1281 // Push a new temporary version. This is needed to distinguish between
1282 // temporaries created in different iterations of a loop.
1283 Info.CurrentCall->pushTempVersion();
1284 }
Richard Smith457226e2019-09-23 03:48:44 +00001285 bool destroy(bool RunDestructors = true) {
1286 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1287 OldStackSize = -1U;
1288 return OK;
1289 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001290 ~ScopeRAII() {
Richard Smith457226e2019-09-23 03:48:44 +00001291 if (OldStackSize != -1U)
1292 destroy(false);
Richard Smith08d6a2c2013-07-24 07:11:57 +00001293 // Body moved to a static method to encourage the compiler to inline away
1294 // instances of this class.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001295 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001296 }
1297 private:
Richard Smithda1b4342019-09-27 01:26:47 +00001298 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1299 unsigned OldStackSize) {
1300 assert(OldStackSize <= Info.CleanupStack.size() &&
1301 "running cleanups out of order?");
1302
Richard Smith457226e2019-09-23 03:48:44 +00001303 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1304 // for a full-expression scope.
Richard Smith49494732019-09-27 05:36:16 +00001305 bool Success = true;
Richard Smith457226e2019-09-23 03:48:44 +00001306 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
Richard Smithda1b4342019-09-27 01:26:47 +00001307 if (!(IsFullExpression &&
1308 Info.CleanupStack[I - 1].isLifetimeExtended())) {
Richard Smith49494732019-09-27 05:36:16 +00001309 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1310 Success = false;
1311 break;
1312 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001313 }
1314 }
Richard Smith457226e2019-09-23 03:48:44 +00001315
1316 // Compact lifetime-extended cleanups.
1317 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1318 if (IsFullExpression)
1319 NewEnd =
1320 std::remove_if(NewEnd, Info.CleanupStack.end(),
1321 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1322 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
Richard Smith49494732019-09-27 05:36:16 +00001323 return Success;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001324 }
1325 };
1326 typedef ScopeRAII<false> BlockScopeRAII;
1327 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001328}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001329
Richard Smitha8105bc2012-01-06 16:39:00 +00001330bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1331 CheckSubobjectKind CSK) {
1332 if (Invalid)
1333 return false;
1334 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001335 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001336 << CSK;
1337 setInvalid();
1338 return false;
1339 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001340 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1341 // must actually be at least one array element; even a VLA cannot have a
1342 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 return true;
1344}
1345
Richard Smith6f4f0f12017-10-20 22:56:25 +00001346void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1347 const Expr *E) {
1348 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1349 // Do not set the designator as invalid: we can represent this situation,
1350 // and correct handling of __builtin_object_size requires us to do so.
1351}
1352
Richard Smitha8105bc2012-01-06 16:39:00 +00001353void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001354 const Expr *E,
1355 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001356 // If we're complaining, we must be able to statically determine the size of
1357 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001358 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001359 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001360 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001361 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001362 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001363 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001364 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001365 setInvalid();
1366}
1367
Richard Smithf6f003a2011-12-16 19:06:07 +00001368CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1369 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001370 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001371 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1372 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001373 Info.CurrentCall = this;
1374 ++Info.CallStackDepth;
1375}
1376
1377CallStackFrame::~CallStackFrame() {
1378 assert(Info.CurrentCall == this && "calls retired out of order");
1379 --Info.CallStackDepth;
1380 Info.CurrentCall = Caller;
1381}
1382
Richard Smithc667cdc2019-09-18 17:37:44 +00001383static bool isRead(AccessKinds AK) {
1384 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1385}
1386
Richard Smithdebad642019-05-12 09:39:08 +00001387static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001388 switch (AK) {
1389 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001390 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001391 case AK_MemberCall:
1392 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001393 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001394 return false;
1395 case AK_Assign:
1396 case AK_Increment:
1397 case AK_Decrement:
Richard Smith61422f92019-09-27 20:24:36 +00001398 case AK_Destroy:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001399 return true;
1400 }
1401 llvm_unreachable("unknown access kind");
1402}
1403
Richard Smith61422f92019-09-27 20:24:36 +00001404static bool isAnyAccess(AccessKinds AK) {
1405 return isRead(AK) || isModification(AK);
1406}
1407
Richard Smith7bd54ab2019-05-15 20:22:21 +00001408/// Is this an access per the C++ definition?
1409static bool isFormalAccess(AccessKinds AK) {
Richard Smith61422f92019-09-27 20:24:36 +00001410 return isAnyAccess(AK) && AK != AK_Destroy;
Richard Smithdebad642019-05-12 09:39:08 +00001411}
1412
Richard Smithf6f003a2011-12-16 19:06:07 +00001413namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001414 struct ComplexValue {
1415 private:
1416 bool IsInt;
1417
1418 public:
1419 APSInt IntReal, IntImag;
1420 APFloat FloatReal, FloatImag;
1421
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001422 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001423
1424 void makeComplexFloat() { IsInt = false; }
1425 bool isComplexFloat() const { return !IsInt; }
1426 APFloat &getComplexFloatReal() { return FloatReal; }
1427 APFloat &getComplexFloatImag() { return FloatImag; }
1428
1429 void makeComplexInt() { IsInt = true; }
1430 bool isComplexInt() const { return IsInt; }
1431 APSInt &getComplexIntReal() { return IntReal; }
1432 APSInt &getComplexIntImag() { return IntImag; }
1433
Richard Smith2e312c82012-03-03 22:46:17 +00001434 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001435 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001436 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001437 else
Richard Smith2e312c82012-03-03 22:46:17 +00001438 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001439 }
Richard Smith2e312c82012-03-03 22:46:17 +00001440 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001441 assert(v.isComplexFloat() || v.isComplexInt());
1442 if (v.isComplexFloat()) {
1443 makeComplexFloat();
1444 FloatReal = v.getComplexFloatReal();
1445 FloatImag = v.getComplexFloatImag();
1446 } else {
1447 makeComplexInt();
1448 IntReal = v.getComplexIntReal();
1449 IntImag = v.getComplexIntImag();
1450 }
1451 }
John McCall93d91dc2010-05-07 17:22:02 +00001452 };
John McCall45d55e42010-05-07 21:00:08 +00001453
1454 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001455 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001456 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001457 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001458 bool IsNullPtr : 1;
1459 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001460
Richard Smithce40ad62011-11-12 22:28:03 +00001461 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001462 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001463 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001464 SubobjectDesignator &getLValueDesignator() { return Designator; }
1465 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001466 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001467
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001468 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1469 unsigned getLValueVersion() const { return Base.getVersion(); }
1470
Richard Smith2e312c82012-03-03 22:46:17 +00001471 void moveInto(APValue &V) const {
1472 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001473 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001474 else {
1475 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001476 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001477 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001478 }
John McCall45d55e42010-05-07 21:00:08 +00001479 }
Richard Smith2e312c82012-03-03 22:46:17 +00001480 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001481 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001482 Base = V.getLValueBase();
1483 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001484 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001485 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001486 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001487 }
1488
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001489 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001490#ifndef NDEBUG
1491 // We only allow a few types of invalid bases. Enforce that here.
1492 if (BInvalid) {
1493 const auto *E = B.get<const Expr *>();
1494 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1495 "Unexpected type of invalid base");
1496 }
1497#endif
1498
Richard Smithce40ad62011-11-12 22:28:03 +00001499 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001500 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001501 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001502 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001503 IsNullPtr = false;
1504 }
1505
Richard Smith19ad5232019-10-03 00:39:33 +00001506 void setNull(ASTContext &Ctx, QualType PointerTy) {
Tim Northover01503332017-05-26 02:16:00 +00001507 Base = (Expr *)nullptr;
Richard Smith19ad5232019-10-03 00:39:33 +00001508 Offset =
1509 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
Tim Northover01503332017-05-26 02:16:00 +00001510 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001511 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1512 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001513 }
1514
George Burgess IV3a03fab2015-09-04 21:28:13 +00001515 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001516 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001517 }
1518
Richard Smith19ad5232019-10-03 00:39:33 +00001519 std::string toString(ASTContext &Ctx, QualType T) const {
1520 APValue Printable;
1521 moveInto(Printable);
1522 return Printable.getAsString(Ctx, T);
1523 }
1524
Hubert Tong147b7432018-12-12 16:53:43 +00001525 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001526 // Check that this LValue is not based on a null pointer. If it is, produce
1527 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001528 template <typename GenDiagType>
1529 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001530 if (Designator.Invalid)
1531 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001532 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001533 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001534 Designator.setInvalid();
1535 return false;
1536 }
1537 return true;
1538 }
1539
Hubert Tong147b7432018-12-12 16:53:43 +00001540 public:
1541 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1542 CheckSubobjectKind CSK) {
1543 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1544 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1545 });
1546 }
1547
1548 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1549 AccessKinds AK) {
1550 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1551 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1552 });
1553 }
1554
Richard Smitha8105bc2012-01-06 16:39:00 +00001555 // Check this LValue refers to an object. If not, set the designator to be
1556 // invalid and emit a diagnostic.
1557 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001558 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001559 Designator.checkSubobject(Info, E, CSK);
1560 }
1561
1562 void addDecl(EvalInfo &Info, const Expr *E,
1563 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001564 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1565 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001566 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001567 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1568 if (!Designator.Entries.empty()) {
1569 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1570 Designator.setInvalid();
1571 return;
1572 }
Richard Smithefdb5032017-11-15 03:03:56 +00001573 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1574 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1575 Designator.FirstEntryIsAnUnsizedArray = true;
1576 Designator.addUnsizedArrayUnchecked(ElemTy);
1577 }
George Burgess IVe3763372016-12-22 02:50:20 +00001578 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001579 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001580 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1581 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001582 }
Richard Smith66c96992012-02-18 22:04:06 +00001583 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001584 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1585 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001586 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001587 void clearIsNullPointer() {
1588 IsNullPtr = false;
1589 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001590 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1591 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001592 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1593 // but we're not required to diagnose it and it's valid in C++.)
1594 if (!Index)
1595 return;
1596
1597 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1598 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1599 // offsets.
1600 uint64_t Offset64 = Offset.getQuantity();
1601 uint64_t ElemSize64 = ElementSize.getQuantity();
1602 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1603 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1604
1605 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001606 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001607 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001608 }
1609 void adjustOffset(CharUnits N) {
1610 Offset += N;
1611 if (N.getQuantity())
1612 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001613 }
John McCall45d55e42010-05-07 21:00:08 +00001614 };
Richard Smith027bf112011-11-17 22:56:20 +00001615
1616 struct MemberPtr {
1617 MemberPtr() {}
1618 explicit MemberPtr(const ValueDecl *Decl) :
1619 DeclAndIsDerivedMember(Decl, false), Path() {}
1620
1621 /// The member or (direct or indirect) field referred to by this member
1622 /// pointer, or 0 if this is a null member pointer.
1623 const ValueDecl *getDecl() const {
1624 return DeclAndIsDerivedMember.getPointer();
1625 }
1626 /// Is this actually a member of some type derived from the relevant class?
1627 bool isDerivedMember() const {
1628 return DeclAndIsDerivedMember.getInt();
1629 }
1630 /// Get the class which the declaration actually lives in.
1631 const CXXRecordDecl *getContainingRecord() const {
1632 return cast<CXXRecordDecl>(
1633 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1634 }
1635
Richard Smith2e312c82012-03-03 22:46:17 +00001636 void moveInto(APValue &V) const {
1637 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001638 }
Richard Smith2e312c82012-03-03 22:46:17 +00001639 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001640 assert(V.isMemberPointer());
1641 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1642 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1643 Path.clear();
1644 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1645 Path.insert(Path.end(), P.begin(), P.end());
1646 }
1647
1648 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1649 /// whether the member is a member of some class derived from the class type
1650 /// of the member pointer.
1651 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1652 /// Path - The path of base/derived classes from the member declaration's
1653 /// class (exclusive) to the class type of the member pointer (inclusive).
1654 SmallVector<const CXXRecordDecl*, 4> Path;
1655
1656 /// Perform a cast towards the class of the Decl (either up or down the
1657 /// hierarchy).
1658 bool castBack(const CXXRecordDecl *Class) {
1659 assert(!Path.empty());
1660 const CXXRecordDecl *Expected;
1661 if (Path.size() >= 2)
1662 Expected = Path[Path.size() - 2];
1663 else
1664 Expected = getContainingRecord();
1665 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1666 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1667 // if B does not contain the original member and is not a base or
1668 // derived class of the class containing the original member, the result
1669 // of the cast is undefined.
1670 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1671 // (D::*). We consider that to be a language defect.
1672 return false;
1673 }
1674 Path.pop_back();
1675 return true;
1676 }
1677 /// Perform a base-to-derived member pointer cast.
1678 bool castToDerived(const CXXRecordDecl *Derived) {
1679 if (!getDecl())
1680 return true;
1681 if (!isDerivedMember()) {
1682 Path.push_back(Derived);
1683 return true;
1684 }
1685 if (!castBack(Derived))
1686 return false;
1687 if (Path.empty())
1688 DeclAndIsDerivedMember.setInt(false);
1689 return true;
1690 }
1691 /// Perform a derived-to-base member pointer cast.
1692 bool castToBase(const CXXRecordDecl *Base) {
1693 if (!getDecl())
1694 return true;
1695 if (Path.empty())
1696 DeclAndIsDerivedMember.setInt(true);
1697 if (isDerivedMember()) {
1698 Path.push_back(Base);
1699 return true;
1700 }
1701 return castBack(Base);
1702 }
1703 };
Richard Smith357362d2011-12-13 06:39:58 +00001704
Richard Smith7bb00672012-02-01 01:42:44 +00001705 /// Compare two member pointers, which are assumed to be of the same type.
1706 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1707 if (!LHS.getDecl() || !RHS.getDecl())
1708 return !LHS.getDecl() && !RHS.getDecl();
1709 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1710 return false;
1711 return LHS.Path == RHS.Path;
1712 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001713}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001714
Richard Smith2e312c82012-03-03 22:46:17 +00001715static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001716static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1717 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001718 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001719static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1720 bool InvalidBaseOK = false);
1721static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1722 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001723static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1724 EvalInfo &Info);
1725static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001726static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001727static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001728 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001729static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001730static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001731static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1732 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001733static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001734
Leonard Chand3f3e162019-01-18 21:04:25 +00001735/// Evaluate an integer or fixed point expression into an APResult.
1736static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1737 EvalInfo &Info);
1738
1739/// Evaluate only a fixed point expression into an APResult.
1740static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1741 EvalInfo &Info);
1742
Chris Lattner05706e882008-07-11 18:11:29 +00001743//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001744// Misc utilities
1745//===----------------------------------------------------------------------===//
1746
Richard Smithd6cc1982017-01-31 02:23:02 +00001747/// Negate an APSInt in place, converting it to a signed form if necessary, and
1748/// preserving its value (by extending by up to one bit as needed).
1749static void negateAsSigned(APSInt &Int) {
1750 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1751 Int = Int.extend(Int.getBitWidth() + 1);
1752 Int.setIsSigned(true);
1753 }
1754 Int = -Int;
1755}
1756
Richard Smith457226e2019-09-23 03:48:44 +00001757template<typename KeyT>
1758APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1759 bool IsLifetimeExtended, LValue &LV) {
Richard Smithda1b4342019-09-27 01:26:47 +00001760 unsigned Version = getTempVersion();
Richard Smith457226e2019-09-23 03:48:44 +00001761 APValue::LValueBase Base(Key, Index, Version);
1762 LV.set(Base);
1763 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1764 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smithda1b4342019-09-27 01:26:47 +00001765
1766 // If we're creating a temporary immediately in the operand of a speculative
1767 // evaluation, don't register a cleanup to be run outside the speculative
1768 // evaluation context, since we won't actually be able to initialize this
1769 // object.
1770 if (Index <= Info.SpeculativeEvaluationDepth) {
1771 if (T.isDestructedType())
1772 Info.noteSideEffect();
1773 } else {
1774 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1775 }
Richard Smith457226e2019-09-23 03:48:44 +00001776 return Result;
1777}
1778
Richard Smithda1b4342019-09-27 01:26:47 +00001779APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1780 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1781 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1782 return nullptr;
1783 }
1784
1785 DynamicAllocLValue DA(NumHeapAllocs++);
1786 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1787 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1788 std::forward_as_tuple(DA), std::tuple<>());
1789 assert(Result.second && "reused a heap alloc index?");
1790 Result.first->second.AllocExpr = E;
1791 return &Result.first->second.Value;
1792}
1793
Richard Smith84401042013-06-03 05:03:02 +00001794/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001795void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001796 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001797 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1798 !isa<CXXConstructorDecl>(Callee) &&
1799 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001800
1801 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001802 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001803
Nandor Licker950b70d2019-09-13 09:46:16 +00001804 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001805 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001806 This->moveInto(Val);
1807 Val.printPretty(Out, Info.Ctx,
1808 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001809 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001810 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001811 IsMemberCall = false;
1812 }
1813
Nandor Licker950b70d2019-09-13 09:46:16 +00001814 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1815 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001816 if (ArgIndex > (unsigned)IsMemberCall)
1817 Out << ", ";
1818
1819 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001820 const APValue &Arg = Arguments[ArgIndex];
1821 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001822
1823 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001824 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001825 }
1826
1827 Out << ')';
1828}
1829
Richard Smithd9f663b2013-04-22 15:31:51 +00001830/// Evaluate an expression to see if it had side-effects, and discard its
1831/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001832/// \return \c true if the caller should keep evaluating.
1833static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001834 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001835 if (!Evaluate(Scratch, Info, E))
1836 // We don't need the value, but we might have skipped a side effect here.
1837 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001838 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001839}
1840
Richard Smithd62306a2011-11-10 06:34:14 +00001841/// Should this call expression be treated as a string literal?
1842static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001843 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001844 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1845 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1846}
1847
Richard Smithce40ad62011-11-12 22:28:03 +00001848static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001849 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1850 // constant expression of pointer type that evaluates to...
1851
1852 // ... a null pointer value, or a prvalue core constant expression of type
1853 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001854 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001855
Richard Smithce40ad62011-11-12 22:28:03 +00001856 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1857 // ... the address of an object with static storage duration,
1858 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1859 return VD->hasGlobalStorage();
1860 // ... the address of a function,
1861 return isa<FunctionDecl>(D);
1862 }
1863
Richard Smithda1b4342019-09-27 01:26:47 +00001864 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +00001865 return true;
1866
Richard Smithce40ad62011-11-12 22:28:03 +00001867 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001868 switch (E->getStmtClass()) {
1869 default:
1870 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001871 case Expr::CompoundLiteralExprClass: {
1872 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1873 return CLE->isFileScope() && CLE->isLValue();
1874 }
Richard Smithe6c01442013-06-05 00:46:14 +00001875 case Expr::MaterializeTemporaryExprClass:
1876 // A materialized temporary might have been lifetime-extended to static
1877 // storage duration.
1878 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001879 // A string literal has static storage duration.
1880 case Expr::StringLiteralClass:
1881 case Expr::PredefinedExprClass:
1882 case Expr::ObjCStringLiteralClass:
1883 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001884 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001885 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001886 case Expr::ObjCBoxedExprClass:
1887 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001888 case Expr::CallExprClass:
1889 return IsStringLiteralCall(cast<CallExpr>(E));
1890 // For GCC compatibility, &&label has static storage duration.
1891 case Expr::AddrLabelExprClass:
1892 return true;
1893 // A Block literal expression may be used as the initialization value for
1894 // Block variables at global or local static scope.
1895 case Expr::BlockExprClass:
1896 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001897 case Expr::ImplicitValueInitExprClass:
1898 // FIXME:
1899 // We can never form an lvalue with an implicit value initialization as its
1900 // base through expression evaluation, so these only appear in one case: the
1901 // implicit variable declaration we invent when checking whether a constexpr
1902 // constructor can produce a constant expression. We must assume that such
1903 // an expression might be a global lvalue.
1904 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001905 }
John McCall95007602010-05-10 23:27:23 +00001906}
1907
Richard Smith06f71b52018-08-04 00:57:17 +00001908static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1909 return LVal.Base.dyn_cast<const ValueDecl*>();
1910}
1911
1912static bool IsLiteralLValue(const LValue &Value) {
1913 if (Value.getLValueCallIndex())
1914 return false;
1915 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1916 return E && !isa<MaterializeTemporaryExpr>(E);
1917}
1918
1919static bool IsWeakLValue(const LValue &Value) {
1920 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1921 return Decl && Decl->isWeak();
1922}
1923
1924static bool isZeroSized(const LValue &Value) {
1925 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1926 if (Decl && isa<VarDecl>(Decl)) {
1927 QualType Ty = Decl->getType();
1928 if (Ty->isArrayType())
1929 return Ty->isIncompleteType() ||
1930 Decl->getASTContext().getTypeSize(Ty) == 0;
1931 }
1932 return false;
1933}
1934
1935static bool HasSameBase(const LValue &A, const LValue &B) {
1936 if (!A.getLValueBase())
1937 return !B.getLValueBase();
1938 if (!B.getLValueBase())
1939 return false;
1940
1941 if (A.getLValueBase().getOpaqueValue() !=
1942 B.getLValueBase().getOpaqueValue()) {
1943 const Decl *ADecl = GetLValueBaseDecl(A);
1944 if (!ADecl)
1945 return false;
1946 const Decl *BDecl = GetLValueBaseDecl(B);
1947 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1948 return false;
1949 }
1950
1951 return IsGlobalLValue(A.getLValueBase()) ||
1952 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1953 A.getLValueVersion() == B.getLValueVersion());
1954}
1955
Richard Smithb228a862012-02-15 02:18:13 +00001956static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1957 assert(Base && "no location for a null lvalue");
1958 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1959 if (VD)
1960 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001961 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1962 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
Richard Smithda1b4342019-09-27 01:26:47 +00001963 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1964 // FIXME: Produce a note for dangling pointers too.
Richard Smith19ad5232019-10-03 00:39:33 +00001965 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
Richard Smithda1b4342019-09-27 01:26:47 +00001966 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1967 diag::note_constexpr_dynamic_alloc_here);
1968 }
Richard Smithee0ce3022019-05-17 07:06:46 +00001969 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001970}
1971
Richard Smith4566f872019-09-29 05:58:31 +00001972enum class CheckEvaluationResultKind {
1973 ConstantExpression,
1974 FullyInitialized,
1975};
1976
1977/// Materialized temporaries that we've already checked to determine if they're
1978/// initializsed by a constant expression.
1979using CheckedTemporaries =
1980 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
1981
1982static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
1983 EvalInfo &Info, SourceLocation DiagLoc,
1984 QualType Type, const APValue &Value,
1985 Expr::ConstExprUsage Usage,
1986 SourceLocation SubobjectLoc,
1987 CheckedTemporaries &CheckedTemps);
1988
Richard Smith80815602011-11-07 05:07:52 +00001989/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001990/// value for an address or reference constant expression. Return true if we
1991/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001992static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001993 QualType Type, const LValue &LVal,
Richard Smith4566f872019-09-29 05:58:31 +00001994 Expr::ConstExprUsage Usage,
1995 CheckedTemporaries &CheckedTemps) {
Richard Smithb228a862012-02-15 02:18:13 +00001996 bool IsReferenceType = Type->isReferenceType();
1997
Richard Smith357362d2011-12-13 06:39:58 +00001998 APValue::LValueBase Base = LVal.getLValueBase();
1999 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2000
Richard Smith0dea49e2012-02-18 04:58:18 +00002001 // Check that the object is a global. Note that the fake 'this' object we
2002 // manufacture when checking potential constant expressions is conservatively
2003 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00002004 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002005 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002006 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00002007 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00002008 << IsReferenceType << !Designator.Entries.empty()
2009 << !!VD << VD;
2010 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002011 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002012 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00002013 }
Richard Smith02ab9c22012-01-12 06:08:57 +00002014 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00002015 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002016 }
Richard Smith6d4c6582013-11-05 22:18:15 +00002017 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00002018 LVal.getLValueCallIndex() == 0) &&
2019 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00002020
Richard Smithda1b4342019-09-27 01:26:47 +00002021 if (Base.is<DynamicAllocLValue>()) {
2022 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2023 << IsReferenceType << !Designator.Entries.empty();
2024 NoteLValueLocation(Info, Base);
2025 return false;
2026 }
2027
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002028 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2029 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00002030 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00002031 if (Var->getTLSKind())
Richard Smithda1b4342019-09-27 01:26:47 +00002032 // FIXME: Diagnostic!
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002033 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00002034
Hans Wennborg82dd8772014-06-25 22:19:48 +00002035 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002036 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00002037 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00002038 return false;
2039 }
2040 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2041 // __declspec(dllimport) must be handled very carefully:
2042 // We must never initialize an expression with the thunk in C++.
2043 // Doing otherwise would allow the same id-expression to yield
2044 // different addresses for the same function in different translation
2045 // units. However, this means that we must dynamically initialize the
2046 // expression with the contents of the import address table at runtime.
2047 //
2048 // The C language has no notion of ODR; furthermore, it has no notion of
2049 // dynamic initialization. This means that we are permitted to
2050 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002051 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2052 FD->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00002053 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00002054 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002055 }
Richard Smith4566f872019-09-29 05:58:31 +00002056 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2057 Base.dyn_cast<const Expr *>())) {
2058 if (CheckedTemps.insert(MTE).second) {
Richard Smith1e8c0852019-09-29 06:22:54 +00002059 QualType TempType = getType(Base);
2060 if (TempType.isDestructedType()) {
2061 Info.FFDiag(MTE->getExprLoc(),
2062 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2063 << TempType;
2064 return false;
2065 }
2066
Richard Smith4566f872019-09-29 05:58:31 +00002067 APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2068 assert(V && "evasluation result refers to uninitialised temporary");
2069 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
Richard Smith1e8c0852019-09-29 06:22:54 +00002070 Info, MTE->getExprLoc(), TempType, *V,
Richard Smith4566f872019-09-29 05:58:31 +00002071 Usage, SourceLocation(), CheckedTemps))
2072 return false;
2073 }
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002074 }
2075
Richard Smitha8105bc2012-01-06 16:39:00 +00002076 // Allow address constant expressions to be past-the-end pointers. This is
2077 // an extension: the standard requires them to point to an object.
2078 if (!IsReferenceType)
2079 return true;
2080
2081 // A reference constant expression must refer to an object.
2082 if (!Base) {
2083 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00002084 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00002085 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00002086 }
2087
Richard Smith357362d2011-12-13 06:39:58 +00002088 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00002089 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00002090 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00002091 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00002092 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00002093 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002094 }
2095
Richard Smith80815602011-11-07 05:07:52 +00002096 return true;
2097}
2098
Reid Klecknercd016d82017-07-07 22:04:29 +00002099/// Member pointers are constant expressions unless they point to a
2100/// non-virtual dllimport member function.
2101static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2102 SourceLocation Loc,
2103 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002104 const APValue &Value,
2105 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002106 const ValueDecl *Member = Value.getMemberPointerDecl();
2107 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2108 if (!FD)
2109 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002110 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2111 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002112}
2113
Richard Smithfddd3842011-12-30 21:15:51 +00002114/// Check that this core constant expression is of literal type, and if not,
2115/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002116static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002117 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002118 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002119 return true;
2120
Richard Smith7525ff62013-05-09 07:14:00 +00002121 // C++1y: A constant initializer for an object o [...] may also invoke
2122 // constexpr constructors for o and its subobjects even if those objects
2123 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002124 //
2125 // C++11 missed this detail for aggregates, so classes like this:
2126 // struct foo_t { union { int i; volatile int j; } u; };
2127 // are not (obviously) initializable like so:
2128 // __attribute__((__require_constant_initialization__))
2129 // static const foo_t x = {{0}};
2130 // because "i" is a subobject with non-literal initialization (due to the
2131 // volatile member of the union). See:
2132 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2133 // Therefore, we use the C++1y behavior.
2134 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002135 return true;
2136
Richard Smithfddd3842011-12-30 21:15:51 +00002137 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002138 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002139 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002140 << E->getType();
2141 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002142 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002143 return false;
2144}
2145
Richard Smith4566f872019-09-29 05:58:31 +00002146static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2147 EvalInfo &Info, SourceLocation DiagLoc,
2148 QualType Type, const APValue &Value,
2149 Expr::ConstExprUsage Usage,
2150 SourceLocation SubobjectLoc,
2151 CheckedTemporaries &CheckedTemps) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002152 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002153 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002154 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002155 if (SubobjectLoc.isValid())
2156 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002157 return false;
2158 }
2159
Richard Smith77be48a2014-07-31 06:31:19 +00002160 // We allow _Atomic(T) to be initialized from anything that T can be
2161 // initialized from.
2162 if (const AtomicType *AT = Type->getAs<AtomicType>())
2163 Type = AT->getValueType();
2164
Richard Smithb228a862012-02-15 02:18:13 +00002165 // Core issue 1454: For a literal constant expression of array or class type,
2166 // each subobject of its value shall have been initialized by a constant
2167 // expression.
2168 if (Value.isArray()) {
2169 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2170 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002171 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2172 Value.getArrayInitializedElt(I), Usage,
Richard Smith4566f872019-09-29 05:58:31 +00002173 SubobjectLoc, CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002174 return false;
2175 }
2176 if (!Value.hasArrayFiller())
2177 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00002178 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
Richard Smith4566f872019-09-29 05:58:31 +00002179 Value.getArrayFiller(), Usage, SubobjectLoc,
2180 CheckedTemps);
Richard Smith80815602011-11-07 05:07:52 +00002181 }
Richard Smithb228a862012-02-15 02:18:13 +00002182 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002183 return CheckEvaluationResult(
2184 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
Richard Smith4566f872019-09-29 05:58:31 +00002185 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2186 CheckedTemps);
Richard Smithb228a862012-02-15 02:18:13 +00002187 }
2188 if (Value.isStruct()) {
2189 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2190 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2191 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002192 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002193 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2194 Value.getStructBase(BaseIndex), Usage,
Richard Smith4566f872019-09-29 05:58:31 +00002195 BS.getBeginLoc(), CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002196 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002197 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002198 }
2199 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002200 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002201 if (I->isUnnamedBitfield())
2202 continue;
2203
Richard Smithc667cdc2019-09-18 17:37:44 +00002204 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2205 Value.getStructField(I->getFieldIndex()),
Richard Smith4566f872019-09-29 05:58:31 +00002206 Usage, I->getLocation(), CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002207 return false;
2208 }
2209 }
2210
Richard Smithc667cdc2019-09-18 17:37:44 +00002211 if (Value.isLValue() &&
2212 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00002213 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002214 LVal.setFrom(Info.Ctx, Value);
Richard Smith4566f872019-09-29 05:58:31 +00002215 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2216 CheckedTemps);
Richard Smithb228a862012-02-15 02:18:13 +00002217 }
2218
Richard Smithc667cdc2019-09-18 17:37:44 +00002219 if (Value.isMemberPointer() &&
2220 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00002221 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002222
Richard Smithb228a862012-02-15 02:18:13 +00002223 // Everything else is fine.
2224 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002225}
2226
Richard Smithc667cdc2019-09-18 17:37:44 +00002227/// Check that this core constant expression value is a valid value for a
2228/// constant expression. If not, report an appropriate diagnostic. Does not
2229/// check that the expression is of literal type.
2230static bool
2231CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2232 const APValue &Value,
2233 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith4566f872019-09-29 05:58:31 +00002234 CheckedTemporaries CheckedTemps;
Richard Smithc667cdc2019-09-18 17:37:44 +00002235 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
Richard Smith4566f872019-09-29 05:58:31 +00002236 Info, DiagLoc, Type, Value, Usage,
2237 SourceLocation(), CheckedTemps);
Richard Smithc667cdc2019-09-18 17:37:44 +00002238}
2239
2240/// Check that this evaluated value is fully-initialized and can be loaded by
2241/// an lvalue-to-rvalue conversion.
2242static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2243 QualType Type, const APValue &Value) {
Richard Smith4566f872019-09-29 05:58:31 +00002244 CheckedTemporaries CheckedTemps;
2245 return CheckEvaluationResult(
2246 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2247 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
Richard Smithc667cdc2019-09-18 17:37:44 +00002248}
2249
Richard Smithda1b4342019-09-27 01:26:47 +00002250/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2251/// "the allocated storage is deallocated within the evaluation".
2252static bool CheckMemoryLeaks(EvalInfo &Info) {
2253 if (!Info.HeapAllocs.empty()) {
2254 // We can still fold to a constant despite a compile-time memory leak,
2255 // so long as the heap allocation isn't referenced in the result (we check
2256 // that in CheckConstantExpression).
2257 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2258 diag::note_constexpr_memory_leak)
2259 << unsigned(Info.HeapAllocs.size() - 1);
2260 }
2261 return true;
2262}
2263
Richard Smith2e312c82012-03-03 22:46:17 +00002264static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002265 // A null base expression indicates a null pointer. These are always
2266 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002267 if (!Value.getLValueBase()) {
2268 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002269 return true;
2270 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002271
Richard Smith027bf112011-11-17 22:56:20 +00002272 // We have a non-null base. These are generally known to be true, but if it's
2273 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002274 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002275 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002276 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002277}
2278
Richard Smith2e312c82012-03-03 22:46:17 +00002279static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002280 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002281 case APValue::None:
2282 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002283 return false;
2284 case APValue::Int:
2285 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002286 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002287 case APValue::FixedPoint:
2288 Result = Val.getFixedPoint().getBoolValue();
2289 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002290 case APValue::Float:
2291 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002292 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002293 case APValue::ComplexInt:
2294 Result = Val.getComplexIntReal().getBoolValue() ||
2295 Val.getComplexIntImag().getBoolValue();
2296 return true;
2297 case APValue::ComplexFloat:
2298 Result = !Val.getComplexFloatReal().isZero() ||
2299 !Val.getComplexFloatImag().isZero();
2300 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002301 case APValue::LValue:
2302 return EvalPointerValueAsBool(Val, Result);
2303 case APValue::MemberPointer:
2304 Result = Val.getMemberPointerDecl();
2305 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002306 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002307 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002308 case APValue::Struct:
2309 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002310 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002311 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002312 }
2313
Richard Smith11562c52011-10-28 17:51:58 +00002314 llvm_unreachable("unknown APValue kind");
2315}
2316
2317static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2318 EvalInfo &Info) {
2319 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002320 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002321 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002322 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002323 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002324}
2325
Richard Smith357362d2011-12-13 06:39:58 +00002326template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002327static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002328 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002329 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002330 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002331 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002332}
2333
2334static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2335 QualType SrcType, const APFloat &Value,
2336 QualType DestType, APSInt &Result) {
2337 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002338 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002339 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002340
Richard Smith357362d2011-12-13 06:39:58 +00002341 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002342 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002343 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2344 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002345 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002346 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002347}
2348
Richard Smith357362d2011-12-13 06:39:58 +00002349static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2350 QualType SrcType, QualType DestType,
2351 APFloat &Result) {
2352 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002353 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002354 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2355 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002356 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002357}
2358
Richard Smith911e1422012-01-30 22:27:01 +00002359static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2360 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002361 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002362 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002363 // Figure out if this is a truncate, extend or noop cast.
2364 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002365 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002366 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002367 if (DestType->isBooleanType())
2368 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002369 return Result;
2370}
2371
Richard Smith357362d2011-12-13 06:39:58 +00002372static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2373 QualType SrcType, const APSInt &Value,
2374 QualType DestType, APFloat &Result) {
2375 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002376 Result.convertFromAPInt(Value, Value.isSigned(),
2377 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002378 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002379}
2380
Richard Smith49ca8aa2013-08-06 07:09:20 +00002381static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2382 APValue &Value, const FieldDecl *FD) {
2383 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2384
2385 if (!Value.isInt()) {
2386 // Trying to store a pointer-cast-to-integer into a bitfield.
2387 // FIXME: In this case, we should provide the diagnostic for casting
2388 // a pointer to an integer.
2389 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002390 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002391 return false;
2392 }
2393
2394 APSInt &Int = Value.getInt();
2395 unsigned OldBitWidth = Int.getBitWidth();
2396 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2397 if (NewBitWidth < OldBitWidth)
2398 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2399 return true;
2400}
2401
Eli Friedman803acb32011-12-22 03:51:45 +00002402static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2403 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002404 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002405 if (!Evaluate(SVal, Info, E))
2406 return false;
2407 if (SVal.isInt()) {
2408 Res = SVal.getInt();
2409 return true;
2410 }
2411 if (SVal.isFloat()) {
2412 Res = SVal.getFloat().bitcastToAPInt();
2413 return true;
2414 }
2415 if (SVal.isVector()) {
2416 QualType VecTy = E->getType();
2417 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2418 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2419 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2420 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2421 Res = llvm::APInt::getNullValue(VecSize);
2422 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2423 APValue &Elt = SVal.getVectorElt(i);
2424 llvm::APInt EltAsInt;
2425 if (Elt.isInt()) {
2426 EltAsInt = Elt.getInt();
2427 } else if (Elt.isFloat()) {
2428 EltAsInt = Elt.getFloat().bitcastToAPInt();
2429 } else {
2430 // Don't try to handle vectors of anything other than int or float
2431 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002432 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002433 return false;
2434 }
2435 unsigned BaseEltSize = EltAsInt.getBitWidth();
2436 if (BigEndian)
2437 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2438 else
2439 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2440 }
2441 return true;
2442 }
2443 // Give up if the input isn't an int, float, or vector. For example, we
2444 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002445 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002446 return false;
2447}
2448
Richard Smith43e77732013-05-07 04:50:00 +00002449/// Perform the given integer operation, which is known to need at most BitWidth
2450/// bits, and check for overflow in the original type (if that type was not an
2451/// unsigned type).
2452template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002453static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2454 const APSInt &LHS, const APSInt &RHS,
2455 unsigned BitWidth, Operation Op,
2456 APSInt &Result) {
2457 if (LHS.isUnsigned()) {
2458 Result = Op(LHS, RHS);
2459 return true;
2460 }
Richard Smith43e77732013-05-07 04:50:00 +00002461
2462 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002463 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002464 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002465 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002466 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002467 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002468 << Result.toString(10) << E->getType();
2469 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002470 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002471 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002472 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002473}
2474
2475/// Perform the given binary integer operation.
2476static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2477 BinaryOperatorKind Opcode, APSInt RHS,
2478 APSInt &Result) {
2479 switch (Opcode) {
2480 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002481 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002482 return false;
2483 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002484 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2485 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002486 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002487 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2488 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002489 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002490 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2491 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002492 case BO_And: Result = LHS & RHS; return true;
2493 case BO_Xor: Result = LHS ^ RHS; return true;
2494 case BO_Or: Result = LHS | RHS; return true;
2495 case BO_Div:
2496 case BO_Rem:
2497 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002498 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002499 return false;
2500 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002501 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2502 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2503 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002504 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2505 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002506 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2507 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002508 return true;
2509 case BO_Shl: {
2510 if (Info.getLangOpts().OpenCL)
2511 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2512 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2513 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2514 RHS.isUnsigned());
2515 else if (RHS.isSigned() && RHS.isNegative()) {
2516 // During constant-folding, a negative shift is an opposite shift. Such
2517 // a shift is not a constant expression.
2518 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2519 RHS = -RHS;
2520 goto shift_right;
2521 }
2522 shift_left:
2523 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2524 // the shifted type.
2525 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2526 if (SA != RHS) {
2527 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2528 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002529 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002530 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2531 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002532 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2533 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002534 if (LHS.isNegative())
2535 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2536 else if (LHS.countLeadingZeros() < SA)
2537 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2538 }
2539 Result = LHS << SA;
2540 return true;
2541 }
2542 case BO_Shr: {
2543 if (Info.getLangOpts().OpenCL)
2544 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2545 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2546 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2547 RHS.isUnsigned());
2548 else if (RHS.isSigned() && RHS.isNegative()) {
2549 // During constant-folding, a negative shift is an opposite shift. Such a
2550 // shift is not a constant expression.
2551 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2552 RHS = -RHS;
2553 goto shift_left;
2554 }
2555 shift_right:
2556 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2557 // shifted type.
2558 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2559 if (SA != RHS)
2560 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2561 << RHS << E->getType() << LHS.getBitWidth();
2562 Result = LHS >> SA;
2563 return true;
2564 }
2565
2566 case BO_LT: Result = LHS < RHS; return true;
2567 case BO_GT: Result = LHS > RHS; return true;
2568 case BO_LE: Result = LHS <= RHS; return true;
2569 case BO_GE: Result = LHS >= RHS; return true;
2570 case BO_EQ: Result = LHS == RHS; return true;
2571 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002572 case BO_Cmp:
2573 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002574 }
2575}
2576
Richard Smith861b5b52013-05-07 23:34:45 +00002577/// Perform the given binary floating-point operation, in-place, on LHS.
2578static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2579 APFloat &LHS, BinaryOperatorKind Opcode,
2580 const APFloat &RHS) {
2581 switch (Opcode) {
2582 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002583 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002584 return false;
2585 case BO_Mul:
2586 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2587 break;
2588 case BO_Add:
2589 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2590 break;
2591 case BO_Sub:
2592 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2593 break;
2594 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002595 // [expr.mul]p4:
2596 // If the second operand of / or % is zero the behavior is undefined.
2597 if (RHS.isZero())
2598 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002599 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2600 break;
2601 }
2602
Richard Smith9e52c432019-07-06 21:05:52 +00002603 // [expr.pre]p4:
2604 // If during the evaluation of an expression, the result is not
2605 // mathematically defined [...], the behavior is undefined.
2606 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2607 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002608 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002609 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002610 }
Richard Smith861b5b52013-05-07 23:34:45 +00002611 return true;
2612}
2613
Richard Smitha8105bc2012-01-06 16:39:00 +00002614/// Cast an lvalue referring to a base subobject to a derived class, by
2615/// truncating the lvalue's path to the given length.
2616static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2617 const RecordDecl *TruncatedType,
2618 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002619 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002620
2621 // Check we actually point to a derived class object.
2622 if (TruncatedElements == D.Entries.size())
2623 return true;
2624 assert(TruncatedElements >= D.MostDerivedPathLength &&
2625 "not casting to a derived class");
2626 if (!Result.checkSubobject(Info, E, CSK_Derived))
2627 return false;
2628
2629 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002630 const RecordDecl *RD = TruncatedType;
2631 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002632 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002633 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2634 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002635 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002636 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002637 else
Richard Smithd62306a2011-11-10 06:34:14 +00002638 Result.Offset -= Layout.getBaseClassOffset(Base);
2639 RD = Base;
2640 }
Richard Smith027bf112011-11-17 22:56:20 +00002641 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002642 return true;
2643}
2644
John McCalld7bca762012-05-01 00:38:49 +00002645static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002646 const CXXRecordDecl *Derived,
2647 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002648 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002649 if (!RL) {
2650 if (Derived->isInvalidDecl()) return false;
2651 RL = &Info.Ctx.getASTRecordLayout(Derived);
2652 }
2653
Richard Smithd62306a2011-11-10 06:34:14 +00002654 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002655 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002656 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002657}
2658
Richard Smitha8105bc2012-01-06 16:39:00 +00002659static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002660 const CXXRecordDecl *DerivedDecl,
2661 const CXXBaseSpecifier *Base) {
2662 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2663
John McCalld7bca762012-05-01 00:38:49 +00002664 if (!Base->isVirtual())
2665 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002666
Richard Smitha8105bc2012-01-06 16:39:00 +00002667 SubobjectDesignator &D = Obj.Designator;
2668 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002669 return false;
2670
Richard Smitha8105bc2012-01-06 16:39:00 +00002671 // Extract most-derived object and corresponding type.
2672 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2673 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2674 return false;
2675
2676 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002677 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002678 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2679 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002680 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002681 return true;
2682}
2683
Richard Smith84401042013-06-03 05:03:02 +00002684static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2685 QualType Type, LValue &Result) {
2686 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2687 PathE = E->path_end();
2688 PathI != PathE; ++PathI) {
2689 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2690 *PathI))
2691 return false;
2692 Type = (*PathI)->getType();
2693 }
2694 return true;
2695}
2696
Richard Smith921f1322019-05-13 23:35:21 +00002697/// Cast an lvalue referring to a derived class to a known base subobject.
2698static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2699 const CXXRecordDecl *DerivedRD,
2700 const CXXRecordDecl *BaseRD) {
2701 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2702 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2703 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2704 llvm_unreachable("Class must be derived from the passed in base class!");
2705
2706 for (CXXBasePathElement &Elem : Paths.front())
2707 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2708 return false;
2709 return true;
2710}
2711
Richard Smithd62306a2011-11-10 06:34:14 +00002712/// Update LVal to refer to the given field, which must be a member of the type
2713/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002714static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002715 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002716 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002717 if (!RL) {
2718 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002719 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002720 }
Richard Smithd62306a2011-11-10 06:34:14 +00002721
2722 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002723 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002724 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002725 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002726}
2727
Richard Smith1b78b3d2012-01-25 22:15:11 +00002728/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002729static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002730 LValue &LVal,
2731 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002732 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002733 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002734 return false;
2735 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002736}
2737
Richard Smithd62306a2011-11-10 06:34:14 +00002738/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002739static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2740 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002741 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2742 // extension.
2743 if (Type->isVoidType() || Type->isFunctionType()) {
2744 Size = CharUnits::One();
2745 return true;
2746 }
2747
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002748 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002749 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002750 return false;
2751 }
2752
Richard Smithd62306a2011-11-10 06:34:14 +00002753 if (!Type->isConstantSizeType()) {
2754 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002755 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002756 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002757 return false;
2758 }
2759
2760 Size = Info.Ctx.getTypeSizeInChars(Type);
2761 return true;
2762}
2763
2764/// Update a pointer value to model pointer arithmetic.
2765/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002766/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002767/// \param LVal - The pointer value to be updated.
2768/// \param EltTy - The pointee type represented by LVal.
2769/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002770static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2771 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002772 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002773 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002774 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002775 return false;
2776
Yaxun Liu402804b2016-12-15 08:09:08 +00002777 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002778 return true;
2779}
2780
Richard Smithd6cc1982017-01-31 02:23:02 +00002781static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2782 LValue &LVal, QualType EltTy,
2783 int64_t Adjustment) {
2784 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2785 APSInt::get(Adjustment));
2786}
2787
Richard Smith66c96992012-02-18 22:04:06 +00002788/// Update an lvalue to refer to a component of a complex number.
2789/// \param Info - Information about the ongoing evaluation.
2790/// \param LVal - The lvalue to be updated.
2791/// \param EltTy - The complex number's component type.
2792/// \param Imag - False for the real component, true for the imaginary.
2793static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2794 LValue &LVal, QualType EltTy,
2795 bool Imag) {
2796 if (Imag) {
2797 CharUnits SizeOfComponent;
2798 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2799 return false;
2800 LVal.Offset += SizeOfComponent;
2801 }
2802 LVal.addComplex(Info, E, EltTy, Imag);
2803 return true;
2804}
2805
Richard Smith27908702011-10-24 17:54:18 +00002806/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002807///
2808/// \param Info Information about the ongoing evaluation.
2809/// \param E An expression to be used when printing diagnostics.
2810/// \param VD The variable whose initializer should be obtained.
2811/// \param Frame The frame in which the variable was created. Must be null
2812/// if this variable is not local to the evaluation.
2813/// \param Result Filled in with a pointer to the value of the variable.
2814static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2815 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002816 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002817
Richard Smith254a73d2011-10-28 22:34:42 +00002818 // If this is a parameter to an active constexpr function call, perform
2819 // argument substitution.
2820 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002821 // Assume arguments of a potential constant expression are unknown
2822 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002823 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002824 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002825 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002826 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002827 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002828 }
Richard Smith3229b742013-05-05 21:17:10 +00002829 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002830 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002831 }
Richard Smith27908702011-10-24 17:54:18 +00002832
Richard Smithd9f663b2013-04-22 15:31:51 +00002833 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002834 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002835 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2836 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002837 if (!Result) {
2838 // Assume variables referenced within a lambda's call operator that were
2839 // not declared within the call operator are captures and during checking
2840 // of a potential constant expression, assume they are unknown constant
2841 // expressions.
2842 assert(isLambdaCallOperator(Frame->Callee) &&
2843 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2844 "missing value for local variable");
2845 if (Info.checkingPotentialConstantExpression())
2846 return false;
2847 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002848 Info.FFDiag(E->getBeginLoc(),
2849 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002850 << "captures not currently allowed";
2851 return false;
2852 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002853 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002854 }
2855
Richard Smithd0b4dd62011-12-19 06:19:21 +00002856 // Dig out the initializer, and use the declaration which it's attached to.
2857 const Expr *Init = VD->getAnyInitializer(VD);
2858 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002859 // If we're checking a potential constant expression, the variable could be
2860 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002861 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002862 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002863 return false;
2864 }
2865
Richard Smithd62306a2011-11-10 06:34:14 +00002866 // If we're currently evaluating the initializer of this declaration, use that
2867 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002868 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002869 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002870 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002871 }
2872
Richard Smithcecf1842011-11-01 21:06:14 +00002873 // Never evaluate the initializer of a weak variable. We can't be sure that
2874 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002875 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002876 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002877 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002878 }
Richard Smithcecf1842011-11-01 21:06:14 +00002879
Richard Smithd0b4dd62011-12-19 06:19:21 +00002880 // Check that we can fold the initializer. In C++, we will have already done
2881 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002882 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002883 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002884 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002885 Notes.size() + 1) << VD;
2886 Info.Note(VD->getLocation(), diag::note_declared_at);
2887 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002888 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002889 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002890 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002891 Notes.size() + 1) << VD;
2892 Info.Note(VD->getLocation(), diag::note_declared_at);
2893 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002894 }
Richard Smith27908702011-10-24 17:54:18 +00002895
Richard Smith3229b742013-05-05 21:17:10 +00002896 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002897 return true;
Richard Smith27908702011-10-24 17:54:18 +00002898}
2899
Richard Smith11562c52011-10-28 17:51:58 +00002900static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002901 Qualifiers Quals = T.getQualifiers();
2902 return Quals.hasConst() && !Quals.hasVolatile();
2903}
2904
Richard Smithe97cbd72011-11-11 04:05:33 +00002905/// Get the base index of the given base class within an APValue representing
2906/// the given derived class.
2907static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2908 const CXXRecordDecl *Base) {
2909 Base = Base->getCanonicalDecl();
2910 unsigned Index = 0;
2911 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2912 E = Derived->bases_end(); I != E; ++I, ++Index) {
2913 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2914 return Index;
2915 }
2916
2917 llvm_unreachable("base class missing from derived class's bases list");
2918}
2919
Richard Smith3da88fa2013-04-26 14:36:30 +00002920/// Extract the value of a character from a string literal.
2921static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2922 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002923 assert(!isa<SourceLocExpr>(Lit) &&
2924 "SourceLocExpr should have already been converted to a StringLiteral");
2925
Akira Hatanakabc332642017-01-31 02:31:39 +00002926 // FIXME: Support MakeStringConstant
2927 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2928 std::string Str;
2929 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2930 assert(Index <= Str.size() && "Index too large");
2931 return APSInt::getUnsigned(Str.c_str()[Index]);
2932 }
2933
Alexey Bataevec474782014-10-09 08:45:04 +00002934 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2935 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002936 const StringLiteral *S = cast<StringLiteral>(Lit);
2937 const ConstantArrayType *CAT =
2938 Info.Ctx.getAsConstantArrayType(S->getType());
2939 assert(CAT && "string literal isn't an array");
2940 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002941 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002942
2943 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002944 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002945 if (Index < S->getLength())
2946 Value = S->getCodeUnit(Index);
2947 return Value;
2948}
2949
Richard Smith3da88fa2013-04-26 14:36:30 +00002950// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002951//
2952// FIXME: This is inefficient; we should probably introduce something similar
2953// to the LLVM ConstantDataArray to make this cheaper.
2954static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smithda1b4342019-09-27 01:26:47 +00002955 APValue &Result,
2956 QualType AllocType = QualType()) {
2957 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2958 AllocType.isNull() ? S->getType() : AllocType);
Richard Smith3da88fa2013-04-26 14:36:30 +00002959 assert(CAT && "string literal isn't an array");
2960 QualType CharType = CAT->getElementType();
2961 assert(CharType->isIntegerType() && "unexpected character type");
2962
2963 unsigned Elts = CAT->getSize().getZExtValue();
2964 Result = APValue(APValue::UninitArray(),
2965 std::min(S->getLength(), Elts), Elts);
2966 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2967 CharType->isUnsignedIntegerType());
2968 if (Result.hasArrayFiller())
2969 Result.getArrayFiller() = APValue(Value);
2970 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2971 Value = S->getCodeUnit(I);
2972 Result.getArrayInitializedElt(I) = APValue(Value);
2973 }
2974}
2975
2976// Expand an array so that it has more than Index filled elements.
2977static void expandArray(APValue &Array, unsigned Index) {
2978 unsigned Size = Array.getArraySize();
2979 assert(Index < Size);
2980
2981 // Always at least double the number of elements for which we store a value.
2982 unsigned OldElts = Array.getArrayInitializedElts();
2983 unsigned NewElts = std::max(Index+1, OldElts * 2);
2984 NewElts = std::min(Size, std::max(NewElts, 8u));
2985
2986 // Copy the data across.
2987 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2988 for (unsigned I = 0; I != OldElts; ++I)
2989 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2990 for (unsigned I = OldElts; I != NewElts; ++I)
2991 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2992 if (NewValue.hasArrayFiller())
2993 NewValue.getArrayFiller() = Array.getArrayFiller();
2994 Array.swap(NewValue);
2995}
2996
Richard Smithb01fe402014-09-16 01:24:02 +00002997/// Determine whether a type would actually be read by an lvalue-to-rvalue
2998/// conversion. If it's of class type, we may assume that the copy operation
2999/// is trivial. Note that this is never true for a union type with fields
3000/// (because the copy always "reads" the active member) and always true for
3001/// a non-class type.
3002static bool isReadByLvalueToRvalueConversion(QualType T) {
3003 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3004 if (!RD || (RD->isUnion() && !RD->field_empty()))
3005 return true;
3006 if (RD->isEmpty())
3007 return false;
3008
3009 for (auto *Field : RD->fields())
3010 if (isReadByLvalueToRvalueConversion(Field->getType()))
3011 return true;
3012
3013 for (auto &BaseSpec : RD->bases())
3014 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3015 return true;
3016
3017 return false;
3018}
3019
3020/// Diagnose an attempt to read from any unreadable field within the specified
3021/// type, which might be a class type.
Richard Smith2b4fa532019-09-29 05:08:46 +00003022static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3023 QualType T) {
Richard Smithb01fe402014-09-16 01:24:02 +00003024 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3025 if (!RD)
3026 return false;
3027
3028 if (!RD->hasMutableFields())
3029 return false;
3030
3031 for (auto *Field : RD->fields()) {
3032 // If we're actually going to read this field in some way, then it can't
3033 // be mutable. If we're in a union, then assigning to a mutable field
3034 // (even an empty one) can change the active member, so that's not OK.
3035 // FIXME: Add core issue number for the union case.
3036 if (Field->isMutable() &&
3037 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003038 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00003039 Info.Note(Field->getLocation(), diag::note_declared_at);
3040 return true;
3041 }
3042
Richard Smith2b4fa532019-09-29 05:08:46 +00003043 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00003044 return true;
3045 }
3046
3047 for (auto &BaseSpec : RD->bases())
Richard Smith2b4fa532019-09-29 05:08:46 +00003048 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00003049 return true;
3050
3051 // All mutable fields were empty, and thus not actually read.
3052 return false;
3053}
3054
Richard Smithdebad642019-05-12 09:39:08 +00003055static bool lifetimeStartedInEvaluation(EvalInfo &Info,
Richard Smith2b4fa532019-09-29 05:08:46 +00003056 APValue::LValueBase Base,
3057 bool MutableSubobject = false) {
Richard Smithdebad642019-05-12 09:39:08 +00003058 // A temporary we created.
3059 if (Base.getCallIndex())
3060 return true;
3061
3062 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3063 if (!Evaluating)
3064 return false;
3065
Richard Smith2b4fa532019-09-29 05:08:46 +00003066 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
Richard Smithdebad642019-05-12 09:39:08 +00003067
Richard Smith2b4fa532019-09-29 05:08:46 +00003068 switch (Info.IsEvaluatingDecl) {
3069 case EvalInfo::EvaluatingDeclKind::None:
3070 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003071
Richard Smith2b4fa532019-09-29 05:08:46 +00003072 case EvalInfo::EvaluatingDeclKind::Ctor:
3073 // The variable whose initializer we're evaluating.
3074 if (BaseD)
3075 return declaresSameEntity(Evaluating, BaseD);
3076
3077 // A temporary lifetime-extended by the variable whose initializer we're
3078 // evaluating.
3079 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3080 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3081 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3082 return false;
3083
3084 case EvalInfo::EvaluatingDeclKind::Dtor:
3085 // C++2a [expr.const]p6:
3086 // [during constant destruction] the lifetime of a and its non-mutable
3087 // subobjects (but not its mutable subobjects) [are] considered to start
3088 // within e.
3089 //
3090 // FIXME: We can meaningfully extend this to cover non-const objects, but
3091 // we will need special handling: we should be able to access only
3092 // subobjects of such objects that are themselves declared const.
3093 if (!BaseD ||
3094 !(BaseD->getType().isConstQualified() ||
3095 BaseD->getType()->isReferenceType()) ||
3096 MutableSubobject)
3097 return false;
3098 return declaresSameEntity(Evaluating, BaseD);
3099 }
3100
3101 llvm_unreachable("unknown evaluating decl kind");
Richard Smithdebad642019-05-12 09:39:08 +00003102}
3103
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003104namespace {
Richard Smith3229b742013-05-05 21:17:10 +00003105/// A handle to a complete object (an object that is not a subobject of
3106/// another object).
3107struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003108 /// The identity of the object.
3109 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00003110 /// The value of the complete object.
3111 APValue *Value;
3112 /// The type of the complete object.
3113 QualType Type;
3114
Craig Topper36250ad2014-05-12 05:36:57 +00003115 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00003116 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3117 : Base(Base), Value(Value), Type(Type) {}
3118
Richard Smith2b4fa532019-09-29 05:08:46 +00003119 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
Richard Smithdebad642019-05-12 09:39:08 +00003120 // In C++14 onwards, it is permitted to read a mutable member whose
3121 // lifetime began within the evaluation.
3122 // FIXME: Should we also allow this in C++11?
3123 if (!Info.getLangOpts().CPlusPlus14)
3124 return false;
Richard Smith2b4fa532019-09-29 05:08:46 +00003125 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
Richard Smith3229b742013-05-05 21:17:10 +00003126 }
3127
Richard Smithdebad642019-05-12 09:39:08 +00003128 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00003129};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003130} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00003131
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003132static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3133 bool IsMutable = false) {
3134 // C++ [basic.type.qualifier]p1:
3135 // - A const object is an object of type const T or a non-mutable subobject
3136 // of a const object.
3137 if (ObjType.isConstQualified() && !IsMutable)
3138 SubobjType.addConst();
3139 // - A volatile object is an object of type const T or a subobject of a
3140 // volatile object.
3141 if (ObjType.isVolatileQualified())
3142 SubobjType.addVolatile();
3143 return SubobjType;
3144}
3145
Richard Smith3da88fa2013-04-26 14:36:30 +00003146/// Find the designated sub-object of an rvalue.
3147template<typename SubobjectHandler>
3148typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00003149findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003150 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003151 if (Sub.Invalid)
3152 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00003153 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00003154 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003155 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00003156 Info.FFDiag(E, Sub.isOnePastTheEnd()
3157 ? diag::note_constexpr_access_past_end
3158 : diag::note_constexpr_access_unsized_array)
3159 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003160 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003162 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00003163 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003164
Richard Smith3229b742013-05-05 21:17:10 +00003165 APValue *O = Obj.Value;
3166 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00003167 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003168 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003169
Richard Smithd62306a2011-11-10 06:34:14 +00003170 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003171 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003172 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithc667cdc2019-09-18 17:37:44 +00003173 if (O->isAbsent() ||
3174 (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
3175 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003176 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003177 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003178 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003179 return handler.failed();
3180 }
3181
Richard Smith457226e2019-09-23 03:48:44 +00003182 // C++ [class.ctor]p5, C++ [class.dtor]p5:
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003183 // const and volatile semantics are not applied on an object under
Richard Smith457226e2019-09-23 03:48:44 +00003184 // {con,de}struction.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003185 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3186 ObjType->isRecordType() &&
Richard Smith457226e2019-09-23 03:48:44 +00003187 Info.isEvaluatingCtorDtor(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003188 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3189 Sub.Entries.begin() + I)) !=
3190 ConstructionPhase::None) {
3191 ObjType = Info.Ctx.getCanonicalType(ObjType);
3192 ObjType.removeLocalConst();
3193 ObjType.removeLocalVolatile();
3194 }
3195
3196 // If this is our last pass, check that the final object type is OK.
3197 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3198 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003199 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003200 if (Info.getLangOpts().CPlusPlus) {
3201 int DiagKind;
3202 SourceLocation Loc;
3203 const NamedDecl *Decl = nullptr;
3204 if (VolatileField) {
3205 DiagKind = 2;
3206 Loc = VolatileField->getLocation();
3207 Decl = VolatileField;
3208 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3209 DiagKind = 1;
3210 Loc = VD->getLocation();
3211 Decl = VD;
3212 } else {
3213 DiagKind = 0;
3214 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3215 Loc = E->getExprLoc();
3216 }
3217 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3218 << handler.AccessKind << DiagKind << Decl;
3219 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3220 } else {
3221 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3222 }
3223 return handler.failed();
3224 }
3225
Richard Smithb01fe402014-09-16 01:24:02 +00003226 // If we are reading an object of class type, there may still be more
3227 // things we need to check: if there are any mutable subobjects, we
3228 // cannot perform this read. (This only happens when performing a trivial
3229 // copy or assignment.)
Richard Smith2b4fa532019-09-29 05:08:46 +00003230 if (ObjType->isRecordType() &&
3231 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3232 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003233 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003234 }
Richard Smithb01fe402014-09-16 01:24:02 +00003235
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003236 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003237 if (!handler.found(*O, ObjType))
3238 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003239
Richard Smith49ca8aa2013-08-06 07:09:20 +00003240 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003241 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003242 LastField && LastField->isBitField() &&
3243 !truncateBitfieldValue(Info, E, *O, LastField))
3244 return false;
3245
3246 return true;
3247 }
3248
Craig Topper36250ad2014-05-12 05:36:57 +00003249 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003250 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003251 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003252 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003253 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003254 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003255 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003256 // Note, it should not be possible to form a pointer with a valid
3257 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003258 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003259 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003260 << handler.AccessKind;
3261 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003262 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003263 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003264 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003265
3266 ObjType = CAT->getElementType();
3267
Richard Smith3da88fa2013-04-26 14:36:30 +00003268 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003269 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00003270 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003271 expandArray(*O, Index);
3272 O = &O->getArrayInitializedElt(Index);
3273 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003274 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003275 } else if (ObjType->isAnyComplexType()) {
3276 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003277 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003278 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003279 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003280 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003281 << handler.AccessKind;
3282 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003283 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003284 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003285 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003286
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003287 ObjType = getSubobjectType(
3288 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003289
Richard Smith66c96992012-02-18 22:04:06 +00003290 assert(I == N - 1 && "extracting subobject of scalar?");
3291 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003292 return handler.found(Index ? O->getComplexIntImag()
3293 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003294 } else {
3295 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003296 return handler.found(Index ? O->getComplexFloatImag()
3297 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003298 }
Richard Smithd62306a2011-11-10 06:34:14 +00003299 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003300 if (Field->isMutable() &&
3301 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3302 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3303 << handler.AccessKind << Field;
Richard Smith5a294e62012-02-09 03:29:58 +00003304 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003305 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003306 }
3307
Richard Smithd62306a2011-11-10 06:34:14 +00003308 // Next subobject is a class, struct or union field.
3309 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3310 if (RD->isUnion()) {
3311 const FieldDecl *UnionField = O->getUnionField();
3312 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003313 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith61422f92019-09-27 20:24:36 +00003314 // FIXME: If O->getUnionValue() is absent, report that there's no
3315 // active union member rather than reporting the prior active union
3316 // member. We'll need to fix nullptr_t to not use APValue() as its
3317 // representation first.
Faisal Valie690b7a2016-07-02 22:34:24 +00003318 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003319 << handler.AccessKind << Field << !UnionField << UnionField;
3320 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003321 }
Richard Smithd62306a2011-11-10 06:34:14 +00003322 O = &O->getUnionValue();
3323 } else
3324 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003325
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003326 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003327 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003328 if (Field->getType().isVolatileQualified())
3329 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003330 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003331 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003332 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3333 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3334 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003335
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003336 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003337 }
3338 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003339}
3340
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003341namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003342struct ExtractSubobjectHandler {
3343 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003344 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003345 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003346 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003347
3348 typedef bool result_type;
3349 bool failed() { return false; }
3350 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003351 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003352 if (AccessKind == AK_ReadObjectRepresentation)
3353 return true;
3354 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003355 }
3356 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003357 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003358 return true;
3359 }
3360 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003361 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003362 return true;
3363 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003364};
Richard Smith3229b742013-05-05 21:17:10 +00003365} // end anonymous namespace
3366
Richard Smith3da88fa2013-04-26 14:36:30 +00003367/// Extract the designated sub-object of an rvalue.
3368static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003369 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003370 const SubobjectDesignator &Sub, APValue &Result,
3371 AccessKinds AK = AK_Read) {
3372 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3373 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003374 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003375}
3376
Richard Smith3229b742013-05-05 21:17:10 +00003377namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003378struct ModifySubobjectHandler {
3379 EvalInfo &Info;
3380 APValue &NewVal;
3381 const Expr *E;
3382
3383 typedef bool result_type;
3384 static const AccessKinds AccessKind = AK_Assign;
3385
3386 bool checkConst(QualType QT) {
3387 // Assigning to a const object has undefined behavior.
3388 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003389 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003390 return false;
3391 }
3392 return true;
3393 }
3394
3395 bool failed() { return false; }
3396 bool found(APValue &Subobj, QualType SubobjType) {
3397 if (!checkConst(SubobjType))
3398 return false;
3399 // We've been given ownership of NewVal, so just swap it in.
3400 Subobj.swap(NewVal);
3401 return true;
3402 }
3403 bool found(APSInt &Value, QualType SubobjType) {
3404 if (!checkConst(SubobjType))
3405 return false;
3406 if (!NewVal.isInt()) {
3407 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003408 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003409 return false;
3410 }
3411 Value = NewVal.getInt();
3412 return true;
3413 }
3414 bool found(APFloat &Value, QualType SubobjType) {
3415 if (!checkConst(SubobjType))
3416 return false;
3417 Value = NewVal.getFloat();
3418 return true;
3419 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003420};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003421} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003422
Richard Smith3229b742013-05-05 21:17:10 +00003423const AccessKinds ModifySubobjectHandler::AccessKind;
3424
Richard Smith3da88fa2013-04-26 14:36:30 +00003425/// Update the designated sub-object of an rvalue to the given value.
3426static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003427 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003428 const SubobjectDesignator &Sub,
3429 APValue &NewVal) {
3430 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003431 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003432}
3433
Richard Smith84f6dcf2012-02-02 01:16:57 +00003434/// Find the position where two subobject designators diverge, or equivalently
3435/// the length of the common initial subsequence.
3436static unsigned FindDesignatorMismatch(QualType ObjType,
3437 const SubobjectDesignator &A,
3438 const SubobjectDesignator &B,
3439 bool &WasArrayIndex) {
3440 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3441 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003442 if (!ObjType.isNull() &&
3443 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003444 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003445 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003446 WasArrayIndex = true;
3447 return I;
3448 }
Richard Smith66c96992012-02-18 22:04:06 +00003449 if (ObjType->isAnyComplexType())
3450 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3451 else
3452 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003453 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003454 if (A.Entries[I].getAsBaseOrMember() !=
3455 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003456 WasArrayIndex = false;
3457 return I;
3458 }
3459 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3460 // Next subobject is a field.
3461 ObjType = FD->getType();
3462 else
3463 // Next subobject is a base class.
3464 ObjType = QualType();
3465 }
3466 }
3467 WasArrayIndex = false;
3468 return I;
3469}
3470
3471/// Determine whether the given subobject designators refer to elements of the
3472/// same array object.
3473static bool AreElementsOfSameArray(QualType ObjType,
3474 const SubobjectDesignator &A,
3475 const SubobjectDesignator &B) {
3476 if (A.Entries.size() != B.Entries.size())
3477 return false;
3478
George Burgess IVa51c4072015-10-16 01:49:01 +00003479 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003480 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3481 // A is a subobject of the array element.
3482 return false;
3483
3484 // If A (and B) designates an array element, the last entry will be the array
3485 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3486 // of length 1' case, and the entire path must match.
3487 bool WasArrayIndex;
3488 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3489 return CommonLength >= A.Entries.size() - IsArray;
3490}
3491
Richard Smith3229b742013-05-05 21:17:10 +00003492/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003493static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3494 AccessKinds AK, const LValue &LVal,
3495 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003496 if (LVal.InvalidBase) {
3497 Info.FFDiag(E);
3498 return CompleteObject();
3499 }
3500
Richard Smith3229b742013-05-05 21:17:10 +00003501 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003502 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003503 return CompleteObject();
3504 }
3505
Craig Topper36250ad2014-05-12 05:36:57 +00003506 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003507 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003508 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003509 std::tie(Frame, Depth) =
3510 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003511 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003512 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003513 << AK << LVal.Base.is<const ValueDecl*>();
3514 NoteLValueLocation(Info, LVal.Base);
3515 return CompleteObject();
3516 }
Richard Smith3229b742013-05-05 21:17:10 +00003517 }
3518
Richard Smith61422f92019-09-27 20:24:36 +00003519 bool IsAccess = isAnyAccess(AK);
Richard Smith7bd54ab2019-05-15 20:22:21 +00003520
Richard Smith3229b742013-05-05 21:17:10 +00003521 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3522 // is not a constant expression (even if the object is non-volatile). We also
3523 // apply this rule to C++98, in order to conform to the expected 'volatile'
3524 // semantics.
Richard Smith61422f92019-09-27 20:24:36 +00003525 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003526 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003527 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003528 << AK << LValType;
3529 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003530 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003531 return CompleteObject();
3532 }
3533
3534 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003535 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003536 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003537
3538 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3539 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3540 // In C++11, constexpr, non-volatile variables initialized with constant
3541 // expressions are constant expressions too. Inside constexpr functions,
3542 // parameters are constant expressions even if they're non-const.
3543 // In C++1y, objects local to a constant expression (those with a Frame) are
3544 // both readable and writable inside constant expressions.
3545 // In C, such things can also be folded, although they are not ICEs.
3546 const VarDecl *VD = dyn_cast<VarDecl>(D);
3547 if (VD) {
3548 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3549 VD = VDef;
3550 }
3551 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003552 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003553 return CompleteObject();
3554 }
3555
Richard Smith3229b742013-05-05 21:17:10 +00003556 // Unless we're looking at a local variable or argument in a constexpr call,
3557 // the variable we're reading must be const.
3558 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003559 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003560 lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003561 // OK, we can read and modify an object if we're in the process of
3562 // evaluating its initializer, because its lifetime began in this
3563 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003564 } else if (isModification(AK)) {
3565 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003566 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003567 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003568 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003569 // OK, we can read this variable.
3570 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003571 // In OpenCL if a variable is in constant address space it is a const
3572 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003573 if (!(BaseType.isConstQualified() ||
3574 (Info.getLangOpts().OpenCL &&
3575 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003576 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003577 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003578 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003579 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003580 Info.Note(VD->getLocation(), diag::note_declared_at);
3581 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003582 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003583 }
3584 return CompleteObject();
3585 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003586 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003587 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003588 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3589 // We support folding of const floating-point types, in order to make
3590 // static const data members of such types (supported as an extension)
3591 // more useful.
3592 if (Info.getLangOpts().CPlusPlus11) {
3593 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3594 Info.Note(VD->getLocation(), diag::note_declared_at);
3595 } else {
3596 Info.CCEDiag(E);
3597 }
George Burgess IVb5316982016-12-27 05:33:20 +00003598 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3599 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3600 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003601 } else {
3602 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003603 if (Info.checkingPotentialConstantExpression() &&
3604 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3605 // The definition of this variable could be constexpr. We can't
3606 // access it right now, but may be able to in future.
3607 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003608 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003609 Info.Note(VD->getLocation(), diag::note_declared_at);
3610 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003611 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003612 }
3613 return CompleteObject();
3614 }
3615 }
3616
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003617 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003618 return CompleteObject();
Richard Smithda1b4342019-09-27 01:26:47 +00003619 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
Richard Smith19ad5232019-10-03 00:39:33 +00003620 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
Richard Smithda1b4342019-09-27 01:26:47 +00003621 if (!Alloc) {
3622 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3623 return CompleteObject();
3624 }
3625 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3626 LVal.Base.getDynamicAllocType());
Richard Smith3229b742013-05-05 21:17:10 +00003627 } else {
3628 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3629
3630 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003631 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003632 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003633 assert(MTE->getStorageDuration() == SD_Static &&
3634 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003635
Richard Smithe6c01442013-06-05 00:46:14 +00003636 // Per C++1y [expr.const]p2:
3637 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3638 // - a [...] glvalue of integral or enumeration type that refers to
3639 // a non-volatile const object [...]
3640 // [...]
3641 // - a [...] glvalue of literal type that refers to a non-volatile
3642 // object whose lifetime began within the evaluation of e.
3643 //
3644 // C++11 misses the 'began within the evaluation of e' check and
3645 // instead allows all temporaries, including things like:
3646 // int &&r = 1;
3647 // int x = ++r;
3648 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003649 // Therefore we use the C++14 rules in C++11 too.
Richard Smith2b4fa532019-09-29 05:08:46 +00003650 //
3651 // Note that temporaries whose lifetimes began while evaluating a
3652 // variable's constructor are not usable while evaluating the
3653 // corresponding destructor, not even if they're of const-qualified
3654 // types.
Richard Smithe6c01442013-06-05 00:46:14 +00003655 if (!(BaseType.isConstQualified() &&
3656 BaseType->isIntegralOrEnumerationType()) &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003657 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003658 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003659 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003660 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003661 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3662 return CompleteObject();
3663 }
3664
3665 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3666 assert(BaseVal && "got reference to unevaluated temporary");
3667 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003668 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003669 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003670 APValue Val;
3671 LVal.moveInto(Val);
3672 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3673 << AK
3674 << Val.getAsString(Info.Ctx,
3675 Info.Ctx.getLValueReferenceType(LValType));
3676 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003677 return CompleteObject();
3678 }
3679 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003680 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003681 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003682 }
Richard Smith7525ff62013-05-09 07:14:00 +00003683 }
3684
Richard Smith9defb7d2018-02-21 03:38:30 +00003685 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003686 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003687 //
3688 // FIXME: Not all local state is mutable. Allow local constant subobjects
3689 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003690 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3691 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003692 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003693 return CompleteObject();
3694
Richard Smithdebad642019-05-12 09:39:08 +00003695 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003696}
3697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003698/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003699/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3700/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003701///
3702/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003703/// \param Conv - The expression for which we are performing the conversion.
3704/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003705/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3706/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003707/// \param LVal - The glvalue on which we are attempting to perform this action.
3708/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003709/// \param WantObjectRepresentation - If true, we're looking for the object
3710/// representation rather than the value, and in particular,
3711/// there is no requirement that the result be fully initialized.
3712static bool
3713handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3714 const LValue &LVal, APValue &RVal,
3715 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003716 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003717 return false;
3718
Richard Smith3229b742013-05-05 21:17:10 +00003719 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003720 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003721
Richard Smithc667cdc2019-09-18 17:37:44 +00003722 AccessKinds AK =
3723 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3724
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003725 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003726 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3727 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3728 // initializer until now for such expressions. Such an expression can't be
3729 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003730 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003731 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003732 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003733 }
Richard Smith3229b742013-05-05 21:17:10 +00003734 APValue Lit;
3735 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3736 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003737 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003738 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003739 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003740 // Special-case character extraction so we don't have to construct an
3741 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003742 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003743 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003744 if (LVal.Designator.Entries.empty()) {
3745 // Fail for now for LValue to RValue conversion of an array.
3746 // (This shouldn't show up in C/C++, but it could be triggered by a
3747 // weird EvaluateAsRValue call from a tool.)
3748 Info.FFDiag(Conv);
3749 return false;
3750 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003751 if (LVal.Designator.isOnePastTheEnd()) {
3752 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003753 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003754 else
3755 Info.FFDiag(Conv);
3756 return false;
3757 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003758 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003759 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3760 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003761 }
Richard Smith11562c52011-10-28 17:51:58 +00003762 }
3763
Richard Smithc667cdc2019-09-18 17:37:44 +00003764 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3765 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003766}
3767
3768/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003769static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003770 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003771 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003772 return false;
3773
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003774 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003775 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003776 return false;
3777 }
3778
Richard Smith3229b742013-05-05 21:17:10 +00003779 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003780 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3781}
3782
3783namespace {
3784struct CompoundAssignSubobjectHandler {
3785 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003786 const Expr *E;
3787 QualType PromotedLHSType;
3788 BinaryOperatorKind Opcode;
3789 const APValue &RHS;
3790
3791 static const AccessKinds AccessKind = AK_Assign;
3792
3793 typedef bool result_type;
3794
3795 bool checkConst(QualType QT) {
3796 // Assigning to a const object has undefined behavior.
3797 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003798 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003799 return false;
3800 }
3801 return true;
3802 }
3803
3804 bool failed() { return false; }
3805 bool found(APValue &Subobj, QualType SubobjType) {
3806 switch (Subobj.getKind()) {
3807 case APValue::Int:
3808 return found(Subobj.getInt(), SubobjType);
3809 case APValue::Float:
3810 return found(Subobj.getFloat(), SubobjType);
3811 case APValue::ComplexInt:
3812 case APValue::ComplexFloat:
3813 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003814 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003815 return false;
3816 case APValue::LValue:
3817 return foundPointer(Subobj, SubobjType);
3818 default:
3819 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003820 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003821 return false;
3822 }
3823 }
3824 bool found(APSInt &Value, QualType SubobjType) {
3825 if (!checkConst(SubobjType))
3826 return false;
3827
Tan S. B.9f935e82018-12-18 07:38:06 +00003828 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003829 // We don't support compound assignment on integer-cast-to-pointer
3830 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003831 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003832 return false;
3833 }
3834
Tan S. B.9f935e82018-12-18 07:38:06 +00003835 if (RHS.isInt()) {
3836 APSInt LHS =
3837 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3838 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3839 return false;
3840 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3841 return true;
3842 } else if (RHS.isFloat()) {
3843 APFloat FValue(0.0);
3844 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3845 FValue) &&
3846 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3847 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3848 Value);
3849 }
3850
3851 Info.FFDiag(E);
3852 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003853 }
3854 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003855 return checkConst(SubobjType) &&
3856 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3857 Value) &&
3858 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3859 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003860 }
3861 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3862 if (!checkConst(SubobjType))
3863 return false;
3864
3865 QualType PointeeType;
3866 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3867 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003868
3869 if (PointeeType.isNull() || !RHS.isInt() ||
3870 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003871 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003872 return false;
3873 }
3874
Richard Smithd6cc1982017-01-31 02:23:02 +00003875 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003876 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003877 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003878
3879 LValue LVal;
3880 LVal.setFrom(Info.Ctx, Subobj);
3881 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3882 return false;
3883 LVal.moveInto(Subobj);
3884 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003885 }
Richard Smith43e77732013-05-07 04:50:00 +00003886};
3887} // end anonymous namespace
3888
3889const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3890
3891/// Perform a compound assignment of LVal <op>= RVal.
3892static bool handleCompoundAssignment(
3893 EvalInfo &Info, const Expr *E,
3894 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3895 BinaryOperatorKind Opcode, const APValue &RVal) {
3896 if (LVal.Designator.Invalid)
3897 return false;
3898
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003899 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003900 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003901 return false;
3902 }
3903
3904 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3905 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3906 RVal };
3907 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3908}
3909
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003910namespace {
3911struct IncDecSubobjectHandler {
3912 EvalInfo &Info;
3913 const UnaryOperator *E;
3914 AccessKinds AccessKind;
3915 APValue *Old;
3916
Richard Smith243ef902013-05-05 23:31:59 +00003917 typedef bool result_type;
3918
3919 bool checkConst(QualType QT) {
3920 // Assigning to a const object has undefined behavior.
3921 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003922 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003923 return false;
3924 }
3925 return true;
3926 }
3927
3928 bool failed() { return false; }
3929 bool found(APValue &Subobj, QualType SubobjType) {
3930 // Stash the old value. Also clear Old, so we don't clobber it later
3931 // if we're post-incrementing a complex.
3932 if (Old) {
3933 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003934 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003935 }
3936
3937 switch (Subobj.getKind()) {
3938 case APValue::Int:
3939 return found(Subobj.getInt(), SubobjType);
3940 case APValue::Float:
3941 return found(Subobj.getFloat(), SubobjType);
3942 case APValue::ComplexInt:
3943 return found(Subobj.getComplexIntReal(),
3944 SubobjType->castAs<ComplexType>()->getElementType()
3945 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3946 case APValue::ComplexFloat:
3947 return found(Subobj.getComplexFloatReal(),
3948 SubobjType->castAs<ComplexType>()->getElementType()
3949 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3950 case APValue::LValue:
3951 return foundPointer(Subobj, SubobjType);
3952 default:
3953 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003954 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003955 return false;
3956 }
3957 }
3958 bool found(APSInt &Value, QualType SubobjType) {
3959 if (!checkConst(SubobjType))
3960 return false;
3961
3962 if (!SubobjType->isIntegerType()) {
3963 // We don't support increment / decrement on integer-cast-to-pointer
3964 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003965 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003966 return false;
3967 }
3968
3969 if (Old) *Old = APValue(Value);
3970
3971 // bool arithmetic promotes to int, and the conversion back to bool
3972 // doesn't reduce mod 2^n, so special-case it.
3973 if (SubobjType->isBooleanType()) {
3974 if (AccessKind == AK_Increment)
3975 Value = 1;
3976 else
3977 Value = !Value;
3978 return true;
3979 }
3980
3981 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003982 if (AccessKind == AK_Increment) {
3983 ++Value;
3984
3985 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3986 APSInt ActualValue(Value, /*IsUnsigned*/true);
3987 return HandleOverflow(Info, E, ActualValue, SubobjType);
3988 }
3989 } else {
3990 --Value;
3991
3992 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3993 unsigned BitWidth = Value.getBitWidth();
3994 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3995 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003996 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003997 }
3998 }
3999 return true;
4000 }
4001 bool found(APFloat &Value, QualType SubobjType) {
4002 if (!checkConst(SubobjType))
4003 return false;
4004
4005 if (Old) *Old = APValue(Value);
4006
4007 APFloat One(Value.getSemantics(), 1);
4008 if (AccessKind == AK_Increment)
4009 Value.add(One, APFloat::rmNearestTiesToEven);
4010 else
4011 Value.subtract(One, APFloat::rmNearestTiesToEven);
4012 return true;
4013 }
4014 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4015 if (!checkConst(SubobjType))
4016 return false;
4017
4018 QualType PointeeType;
4019 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4020 PointeeType = PT->getPointeeType();
4021 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004022 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00004023 return false;
4024 }
4025
4026 LValue LVal;
4027 LVal.setFrom(Info.Ctx, Subobj);
4028 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4029 AccessKind == AK_Increment ? 1 : -1))
4030 return false;
4031 LVal.moveInto(Subobj);
4032 return true;
4033 }
Richard Smith243ef902013-05-05 23:31:59 +00004034};
4035} // end anonymous namespace
4036
4037/// Perform an increment or decrement on LVal.
4038static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4039 QualType LValType, bool IsIncrement, APValue *Old) {
4040 if (LVal.Designator.Invalid)
4041 return false;
4042
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004043 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004044 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00004045 return false;
4046 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00004047
4048 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4049 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4050 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4051 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4052}
4053
Richard Smithe97cbd72011-11-11 04:05:33 +00004054/// Build an lvalue for the object argument of a member function call.
4055static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4056 LValue &This) {
Richard Smith5e18f4d2019-10-02 01:13:57 +00004057 if (Object->getType()->isPointerType() && Object->isRValue())
Richard Smithe97cbd72011-11-11 04:05:33 +00004058 return EvaluatePointer(Object, This, Info);
4059
4060 if (Object->isGLValue())
4061 return EvaluateLValue(Object, This, Info);
4062
Richard Smithd9f663b2013-04-22 15:31:51 +00004063 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00004064 return EvaluateTemporary(Object, This, Info);
4065
Faisal Valie690b7a2016-07-02 22:34:24 +00004066 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004067 return false;
4068}
4069
4070/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4071/// lvalue referring to the result.
4072///
4073/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00004074/// \param LV - An lvalue referring to the base of the member pointer.
4075/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00004076/// \param IncludeMember - Specifies whether the member itself is included in
4077/// the resulting LValue subobject designator. This is not possible when
4078/// creating a bound member function.
4079/// \return The field or method declaration to which the member pointer refers,
4080/// or 0 if evaluation fails.
4081static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00004082 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00004083 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00004084 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00004085 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00004086 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00004087 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00004088 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004089
4090 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4091 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00004092 if (!MemPtr.getDecl()) {
4093 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00004094 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004095 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004096 }
Richard Smith253c2a32012-01-27 01:14:48 +00004097
Richard Smith027bf112011-11-17 22:56:20 +00004098 if (MemPtr.isDerivedMember()) {
4099 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00004100 // The end of the derived-to-base path for the base object must match the
4101 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00004102 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00004103 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004104 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004105 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004106 }
Richard Smith027bf112011-11-17 22:56:20 +00004107 unsigned PathLengthToMember =
4108 LV.Designator.Entries.size() - MemPtr.Path.size();
4109 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4110 const CXXRecordDecl *LVDecl = getAsBaseClass(
4111 LV.Designator.Entries[PathLengthToMember + I]);
4112 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00004113 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004114 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004115 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004116 }
Richard Smith027bf112011-11-17 22:56:20 +00004117 }
4118
4119 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00004120 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004121 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00004122 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004123 } else if (!MemPtr.Path.empty()) {
4124 // Extend the LValue path with the member pointer's path.
4125 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4126 MemPtr.Path.size() + IncludeMember);
4127
4128 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00004129 if (const PointerType *PT = LVType->getAs<PointerType>())
4130 LVType = PT->getPointeeType();
4131 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4132 assert(RD && "member pointer access on non-class-type expression");
4133 // The first class in the path is that of the lvalue.
4134 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4135 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00004136 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00004137 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004138 RD = Base;
4139 }
4140 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00004141 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4142 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00004143 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004144 }
4145
4146 // Add the member. Note that we cannot build bound member functions here.
4147 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00004148 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004149 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00004150 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004151 } else if (const IndirectFieldDecl *IFD =
4152 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004153 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00004154 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004155 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004156 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00004157 }
Richard Smith027bf112011-11-17 22:56:20 +00004158 }
4159
4160 return MemPtr.getDecl();
4161}
4162
Richard Smith84401042013-06-03 05:03:02 +00004163static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4164 const BinaryOperator *BO,
4165 LValue &LV,
4166 bool IncludeMember = true) {
4167 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4168
4169 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00004170 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00004171 MemberPtr MemPtr;
4172 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4173 }
Craig Topper36250ad2014-05-12 05:36:57 +00004174 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004175 }
4176
4177 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4178 BO->getRHS(), IncludeMember);
4179}
4180
Richard Smith027bf112011-11-17 22:56:20 +00004181/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4182/// the provided lvalue, which currently refers to the base object.
4183static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4184 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00004185 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00004186 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00004187 return false;
4188
Richard Smitha8105bc2012-01-06 16:39:00 +00004189 QualType TargetQT = E->getType();
4190 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4191 TargetQT = PT->getPointeeType();
4192
4193 // Check this cast lands within the final derived-to-base subobject path.
4194 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004195 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004196 << D.MostDerivedType << TargetQT;
4197 return false;
4198 }
4199
Richard Smith027bf112011-11-17 22:56:20 +00004200 // Check the type of the final cast. We don't need to check the path,
4201 // since a cast can only be formed if the path is unique.
4202 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004203 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4204 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004205 if (NewEntriesSize == D.MostDerivedPathLength)
4206 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4207 else
Richard Smith027bf112011-11-17 22:56:20 +00004208 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004209 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004210 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004211 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004212 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004213 }
Richard Smith027bf112011-11-17 22:56:20 +00004214
4215 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004216 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004217}
4218
Richard Smithc667cdc2019-09-18 17:37:44 +00004219/// Get the value to use for a default-initialized object of type T.
4220static APValue getDefaultInitValue(QualType T) {
4221 if (auto *RD = T->getAsCXXRecordDecl()) {
4222 if (RD->isUnion())
4223 return APValue((const FieldDecl*)nullptr);
4224
4225 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4226 std::distance(RD->field_begin(), RD->field_end()));
4227
4228 unsigned Index = 0;
4229 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4230 End = RD->bases_end(); I != End; ++I, ++Index)
4231 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4232
4233 for (const auto *I : RD->fields()) {
4234 if (I->isUnnamedBitfield())
4235 continue;
4236 Struct.getStructField(I->getFieldIndex()) =
4237 getDefaultInitValue(I->getType());
4238 }
4239 return Struct;
4240 }
4241
4242 if (auto *AT =
4243 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4244 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4245 if (Array.hasArrayFiller())
4246 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4247 return Array;
4248 }
4249
4250 return APValue::IndeterminateValue();
4251}
4252
Mike Stump876387b2009-10-27 22:09:17 +00004253namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004254enum EvalStmtResult {
4255 /// Evaluation failed.
4256 ESR_Failed,
4257 /// Hit a 'return' statement.
4258 ESR_Returned,
4259 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004260 ESR_Succeeded,
4261 /// Hit a 'continue' statement.
4262 ESR_Continue,
4263 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004264 ESR_Break,
4265 /// Still scanning for 'case' or 'default' statement.
4266 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004267};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004268}
Richard Smith254a73d2011-10-28 22:34:42 +00004269
Richard Smith97fcf4b2016-08-14 23:15:52 +00004270static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4271 // We don't need to evaluate the initializer for a static local.
4272 if (!VD->hasLocalStorage())
4273 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004274
Richard Smith97fcf4b2016-08-14 23:15:52 +00004275 LValue Result;
Richard Smith457226e2019-09-23 03:48:44 +00004276 APValue &Val =
4277 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
Richard Smithd9f663b2013-04-22 15:31:51 +00004278
Richard Smith97fcf4b2016-08-14 23:15:52 +00004279 const Expr *InitE = VD->getInit();
4280 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00004281 Val = getDefaultInitValue(VD->getType());
4282 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00004283 }
Richard Smith51f03172013-06-20 03:00:05 +00004284
Richard Smith97fcf4b2016-08-14 23:15:52 +00004285 if (InitE->isValueDependent())
4286 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004287
Richard Smith97fcf4b2016-08-14 23:15:52 +00004288 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4289 // Wipe out any partially-computed value, to allow tracking that this
4290 // evaluation failed.
4291 Val = APValue();
4292 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004293 }
4294
4295 return true;
4296}
4297
Richard Smith97fcf4b2016-08-14 23:15:52 +00004298static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4299 bool OK = true;
4300
4301 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4302 OK &= EvaluateVarDecl(Info, VD);
4303
4304 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4305 for (auto *BD : DD->bindings())
4306 if (auto *VD = BD->getHoldingVar())
4307 OK &= EvaluateDecl(Info, VD);
4308
4309 return OK;
4310}
4311
4312
Richard Smith4e18ca52013-05-06 05:56:11 +00004313/// Evaluate a condition (either a variable declaration or an expression).
4314static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4315 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004316 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004317 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4318 return false;
Richard Smith457226e2019-09-23 03:48:44 +00004319 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4320 return false;
4321 return Scope.destroy();
Richard Smith4e18ca52013-05-06 05:56:11 +00004322}
4323
Richard Smith89210072016-04-04 23:29:43 +00004324namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004325/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004326/// statement should be stored.
4327struct StmtResult {
4328 /// The APValue that should be filled in with the returned value.
4329 APValue &Value;
4330 /// The location containing the result, if any (used to support RVO).
4331 const LValue *Slot;
4332};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004333
4334struct TempVersionRAII {
4335 CallStackFrame &Frame;
4336
4337 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4338 Frame.pushTempVersion();
4339 }
4340
4341 ~TempVersionRAII() {
4342 Frame.popTempVersion();
4343 }
4344};
4345
Richard Smith89210072016-04-04 23:29:43 +00004346}
Richard Smith52a980a2015-08-28 02:43:42 +00004347
4348static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004349 const Stmt *S,
4350 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004351
4352/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004353static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004354 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004355 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004356 BlockScopeRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004357
4358 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4359 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4360 ESR = ESR_Failed;
4361
4362 switch (ESR) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004363 case ESR_Break:
4364 return ESR_Succeeded;
4365 case ESR_Succeeded:
4366 case ESR_Continue:
4367 return ESR_Continue;
4368 case ESR_Failed:
4369 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004370 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004371 return ESR;
4372 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004373 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004374}
4375
Richard Smith496ddcf2013-05-12 17:32:42 +00004376/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004377static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004378 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004379 BlockScopeRAII Scope(Info);
4380
Richard Smith496ddcf2013-05-12 17:32:42 +00004381 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004382 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004383 {
Richard Smitha547eb22016-07-14 00:11:03 +00004384 if (const Stmt *Init = SS->getInit()) {
4385 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004386 if (ESR != ESR_Succeeded) {
4387 if (ESR != ESR_Failed && !Scope.destroy())
4388 ESR = ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004389 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004390 }
Richard Smitha547eb22016-07-14 00:11:03 +00004391 }
Richard Smith457226e2019-09-23 03:48:44 +00004392
4393 FullExpressionRAII CondScope(Info);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004394 if (SS->getConditionVariable() &&
4395 !EvaluateDecl(Info, SS->getConditionVariable()))
4396 return ESR_Failed;
4397 if (!EvaluateInteger(SS->getCond(), Value, Info))
4398 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004399 if (!CondScope.destroy())
4400 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004401 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004402
4403 // Find the switch case corresponding to the value of the condition.
4404 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004405 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004406 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4407 SC = SC->getNextSwitchCase()) {
4408 if (isa<DefaultStmt>(SC)) {
4409 Found = SC;
4410 continue;
4411 }
4412
4413 const CaseStmt *CS = cast<CaseStmt>(SC);
4414 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4415 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4416 : LHS;
4417 if (LHS <= Value && Value <= RHS) {
4418 Found = SC;
4419 break;
4420 }
4421 }
4422
4423 if (!Found)
Richard Smith457226e2019-09-23 03:48:44 +00004424 return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
Richard Smith496ddcf2013-05-12 17:32:42 +00004425
4426 // Search the switch body for the switch case and evaluate it from there.
Richard Smith457226e2019-09-23 03:48:44 +00004427 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4428 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4429 return ESR_Failed;
4430
4431 switch (ESR) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004432 case ESR_Break:
4433 return ESR_Succeeded;
4434 case ESR_Succeeded:
4435 case ESR_Continue:
4436 case ESR_Failed:
4437 case ESR_Returned:
4438 return ESR;
4439 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004440 // This can only happen if the switch case is nested within a statement
4441 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004442 Info.FFDiag(Found->getBeginLoc(),
4443 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004444 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004445 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004446 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004447}
4448
Richard Smith254a73d2011-10-28 22:34:42 +00004449// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004450static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004451 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004452 if (!Info.nextStep(S))
4453 return ESR_Failed;
4454
Richard Smith496ddcf2013-05-12 17:32:42 +00004455 // If we're hunting down a 'case' or 'default' label, recurse through
4456 // substatements until we hit the label.
4457 if (Case) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004458 switch (S->getStmtClass()) {
4459 case Stmt::CompoundStmtClass:
4460 // FIXME: Precompute which substatement of a compound statement we
4461 // would jump to, and go straight there rather than performing a
4462 // linear scan each time.
4463 case Stmt::LabelStmtClass:
4464 case Stmt::AttributedStmtClass:
4465 case Stmt::DoStmtClass:
4466 break;
4467
4468 case Stmt::CaseStmtClass:
4469 case Stmt::DefaultStmtClass:
4470 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004471 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004472 break;
4473
4474 case Stmt::IfStmtClass: {
4475 // FIXME: Precompute which side of an 'if' we would jump to, and go
4476 // straight there rather than scanning both sides.
4477 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004478
4479 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4480 // preceded by our switch label.
4481 BlockScopeRAII Scope(Info);
4482
Richard Smith397a6862019-09-20 23:08:59 +00004483 // Step into the init statement in case it brings an (uninitialized)
4484 // variable into scope.
4485 if (const Stmt *Init = IS->getInit()) {
4486 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4487 if (ESR != ESR_CaseNotFound) {
4488 assert(ESR != ESR_Succeeded);
4489 return ESR;
4490 }
4491 }
4492
4493 // Condition variable must be initialized if it exists.
4494 // FIXME: We can skip evaluating the body if there's a condition
4495 // variable, as there can't be any case labels within it.
4496 // (The same is true for 'for' statements.)
4497
Richard Smith496ddcf2013-05-12 17:32:42 +00004498 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
Richard Smith457226e2019-09-23 03:48:44 +00004499 if (ESR == ESR_Failed)
Richard Smith496ddcf2013-05-12 17:32:42 +00004500 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004501 if (ESR != ESR_CaseNotFound)
4502 return Scope.destroy() ? ESR : ESR_Failed;
4503 if (!IS->getElse())
4504 return ESR_CaseNotFound;
4505
4506 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4507 if (ESR == ESR_Failed)
4508 return ESR;
4509 if (ESR != ESR_CaseNotFound)
4510 return Scope.destroy() ? ESR : ESR_Failed;
4511 return ESR_CaseNotFound;
Richard Smith496ddcf2013-05-12 17:32:42 +00004512 }
4513
4514 case Stmt::WhileStmtClass: {
4515 EvalStmtResult ESR =
4516 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4517 if (ESR != ESR_Continue)
4518 return ESR;
4519 break;
4520 }
4521
4522 case Stmt::ForStmtClass: {
4523 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith397a6862019-09-20 23:08:59 +00004524 BlockScopeRAII Scope(Info);
4525
4526 // Step into the init statement in case it brings an (uninitialized)
4527 // variable into scope.
4528 if (const Stmt *Init = FS->getInit()) {
4529 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4530 if (ESR != ESR_CaseNotFound) {
4531 assert(ESR != ESR_Succeeded);
4532 return ESR;
4533 }
4534 }
4535
Richard Smith496ddcf2013-05-12 17:32:42 +00004536 EvalStmtResult ESR =
4537 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4538 if (ESR != ESR_Continue)
4539 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004540 if (FS->getInc()) {
4541 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004542 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004543 return ESR_Failed;
4544 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004545 break;
4546 }
4547
Richard Smithc667cdc2019-09-18 17:37:44 +00004548 case Stmt::DeclStmtClass: {
4549 // Start the lifetime of any uninitialized variables we encounter. They
4550 // might be used by the selected branch of the switch.
4551 const DeclStmt *DS = cast<DeclStmt>(S);
4552 for (const auto *D : DS->decls()) {
4553 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4554 if (VD->hasLocalStorage() && !VD->getInit())
4555 if (!EvaluateVarDecl(Info, VD))
4556 return ESR_Failed;
4557 // FIXME: If the variable has initialization that can't be jumped
4558 // over, bail out of any immediately-surrounding compound-statement
4559 // too. There can't be any case labels here.
4560 }
4561 }
4562 return ESR_CaseNotFound;
4563 }
4564
Richard Smith496ddcf2013-05-12 17:32:42 +00004565 default:
4566 return ESR_CaseNotFound;
4567 }
4568 }
4569
Richard Smith254a73d2011-10-28 22:34:42 +00004570 switch (S->getStmtClass()) {
4571 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004572 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004573 // Don't bother evaluating beyond an expression-statement which couldn't
4574 // be evaluated.
Richard Smith457226e2019-09-23 03:48:44 +00004575 // FIXME: Do we need the FullExpressionRAII object here?
4576 // VisitExprWithCleanups should create one when necessary.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004577 FullExpressionRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004578 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
Richard Smithd9f663b2013-04-22 15:31:51 +00004579 return ESR_Failed;
4580 return ESR_Succeeded;
4581 }
4582
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004583 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004584 return ESR_Failed;
4585
4586 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004587 return ESR_Succeeded;
4588
Richard Smithd9f663b2013-04-22 15:31:51 +00004589 case Stmt::DeclStmtClass: {
4590 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004591 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004592 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004593 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004594 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004595 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004596 if (!Scope.destroy())
4597 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004598 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004599 return ESR_Succeeded;
4600 }
4601
Richard Smith357362d2011-12-13 06:39:58 +00004602 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004603 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004604 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004605 if (RetExpr &&
4606 !(Result.Slot
4607 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4608 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004609 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004610 return Scope.destroy() ? ESR_Returned : ESR_Failed;
Richard Smith357362d2011-12-13 06:39:58 +00004611 }
Richard Smith254a73d2011-10-28 22:34:42 +00004612
4613 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004614 BlockScopeRAII Scope(Info);
4615
Richard Smith254a73d2011-10-28 22:34:42 +00004616 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004617 for (const auto *BI : CS->body()) {
4618 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004619 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004620 Case = nullptr;
Richard Smith457226e2019-09-23 03:48:44 +00004621 else if (ESR != ESR_CaseNotFound) {
4622 if (ESR != ESR_Failed && !Scope.destroy())
4623 return ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004624 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004625 }
Richard Smith254a73d2011-10-28 22:34:42 +00004626 }
Richard Smith457226e2019-09-23 03:48:44 +00004627 if (Case)
4628 return ESR_CaseNotFound;
4629 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004630 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004631
4632 case Stmt::IfStmtClass: {
4633 const IfStmt *IS = cast<IfStmt>(S);
4634
4635 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004636 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004637 if (const Stmt *Init = IS->getInit()) {
4638 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004639 if (ESR != ESR_Succeeded) {
4640 if (ESR != ESR_Failed && !Scope.destroy())
4641 return ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004642 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004643 }
Richard Smitha547eb22016-07-14 00:11:03 +00004644 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004645 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004646 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004647 return ESR_Failed;
4648
4649 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4650 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
Richard Smith457226e2019-09-23 03:48:44 +00004651 if (ESR != ESR_Succeeded) {
4652 if (ESR != ESR_Failed && !Scope.destroy())
4653 return ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004654 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004655 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004656 }
Richard Smith457226e2019-09-23 03:48:44 +00004657 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004658 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004659
4660 case Stmt::WhileStmtClass: {
4661 const WhileStmt *WS = cast<WhileStmt>(S);
4662 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004663 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004664 bool Continue;
4665 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4666 Continue))
4667 return ESR_Failed;
4668 if (!Continue)
4669 break;
4670
4671 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004672 if (ESR != ESR_Continue) {
4673 if (ESR != ESR_Failed && !Scope.destroy())
4674 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004675 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004676 }
4677 if (!Scope.destroy())
4678 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004679 }
4680 return ESR_Succeeded;
4681 }
4682
4683 case Stmt::DoStmtClass: {
4684 const DoStmt *DS = cast<DoStmt>(S);
4685 bool Continue;
4686 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004687 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004688 if (ESR != ESR_Continue)
4689 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004690 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004691
Richard Smith08d6a2c2013-07-24 07:11:57 +00004692 FullExpressionRAII CondScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004693 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4694 !CondScope.destroy())
Richard Smith4e18ca52013-05-06 05:56:11 +00004695 return ESR_Failed;
4696 } while (Continue);
4697 return ESR_Succeeded;
4698 }
4699
4700 case Stmt::ForStmtClass: {
4701 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith457226e2019-09-23 03:48:44 +00004702 BlockScopeRAII ForScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004703 if (FS->getInit()) {
4704 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004705 if (ESR != ESR_Succeeded) {
4706 if (ESR != ESR_Failed && !ForScope.destroy())
4707 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004708 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004709 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004710 }
4711 while (true) {
Richard Smith457226e2019-09-23 03:48:44 +00004712 BlockScopeRAII IterScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004713 bool Continue = true;
4714 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4715 FS->getCond(), Continue))
4716 return ESR_Failed;
4717 if (!Continue)
4718 break;
4719
4720 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004721 if (ESR != ESR_Continue) {
4722 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4723 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004724 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004725 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004726
Richard Smith08d6a2c2013-07-24 07:11:57 +00004727 if (FS->getInc()) {
4728 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004729 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004730 return ESR_Failed;
4731 }
Richard Smith457226e2019-09-23 03:48:44 +00004732
4733 if (!IterScope.destroy())
4734 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004735 }
Richard Smith457226e2019-09-23 03:48:44 +00004736 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004737 }
4738
Richard Smith896e0d72013-05-06 06:51:17 +00004739 case Stmt::CXXForRangeStmtClass: {
4740 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004741 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004742
Richard Smith8baa5002018-09-28 18:44:09 +00004743 // Evaluate the init-statement if present.
4744 if (FS->getInit()) {
4745 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004746 if (ESR != ESR_Succeeded) {
4747 if (ESR != ESR_Failed && !Scope.destroy())
4748 return ESR_Failed;
Richard Smith8baa5002018-09-28 18:44:09 +00004749 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004750 }
Richard Smith8baa5002018-09-28 18:44:09 +00004751 }
4752
Richard Smith896e0d72013-05-06 06:51:17 +00004753 // Initialize the __range variable.
4754 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004755 if (ESR != ESR_Succeeded) {
4756 if (ESR != ESR_Failed && !Scope.destroy())
4757 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004758 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004759 }
Richard Smith896e0d72013-05-06 06:51:17 +00004760
4761 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004762 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004763 if (ESR != ESR_Succeeded) {
4764 if (ESR != ESR_Failed && !Scope.destroy())
4765 return ESR_Failed;
Richard Smith01694c32016-03-20 10:33:40 +00004766 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004767 }
Richard Smith01694c32016-03-20 10:33:40 +00004768 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
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 while (true) {
4776 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004777 {
4778 bool Continue = true;
4779 FullExpressionRAII CondExpr(Info);
4780 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4781 return ESR_Failed;
4782 if (!Continue)
4783 break;
4784 }
Richard Smith896e0d72013-05-06 06:51:17 +00004785
4786 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004787 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004788 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004789 if (ESR != ESR_Succeeded) {
4790 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4791 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004792 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004793 }
Richard Smith896e0d72013-05-06 06:51:17 +00004794
4795 // Loop body.
4796 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004797 if (ESR != ESR_Continue) {
4798 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4799 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004800 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004801 }
Richard Smith896e0d72013-05-06 06:51:17 +00004802
4803 // Increment: ++__begin
4804 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4805 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004806
4807 if (!InnerScope.destroy())
4808 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004809 }
4810
Richard Smith457226e2019-09-23 03:48:44 +00004811 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004812 }
4813
Richard Smith496ddcf2013-05-12 17:32:42 +00004814 case Stmt::SwitchStmtClass:
4815 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4816
Richard Smith4e18ca52013-05-06 05:56:11 +00004817 case Stmt::ContinueStmtClass:
4818 return ESR_Continue;
4819
4820 case Stmt::BreakStmtClass:
4821 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004822
4823 case Stmt::LabelStmtClass:
4824 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4825
4826 case Stmt::AttributedStmtClass:
4827 // As a general principle, C++11 attributes can be ignored without
4828 // any semantic impact.
4829 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4830 Case);
4831
4832 case Stmt::CaseStmtClass:
4833 case Stmt::DefaultStmtClass:
4834 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004835 case Stmt::CXXTryStmtClass:
4836 // Evaluate try blocks by evaluating all sub statements.
4837 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004838 }
4839}
4840
Richard Smithcc36f692011-12-22 02:22:31 +00004841/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4842/// default constructor. If so, we'll fold it whether or not it's marked as
4843/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4844/// so we need special handling.
4845static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004846 const CXXConstructorDecl *CD,
4847 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004848 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4849 return false;
4850
Richard Smith66e05fe2012-01-18 05:21:49 +00004851 // Value-initialization does not call a trivial default constructor, so such a
4852 // call is a core constant expression whether or not the constructor is
4853 // constexpr.
4854 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004855 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004856 // FIXME: If DiagDecl is an implicitly-declared special member function,
4857 // we should be much more explicit about why it's not constexpr.
4858 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4859 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4860 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004861 } else {
4862 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4863 }
4864 }
4865 return true;
4866}
4867
Richard Smith357362d2011-12-13 06:39:58 +00004868/// CheckConstexprFunction - Check that a function can be called in a constant
4869/// expression.
4870static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4871 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004872 const FunctionDecl *Definition,
4873 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004874 // Potential constant expressions can contain calls to declared, but not yet
4875 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004876 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004877 Declaration->isConstexpr())
4878 return false;
4879
James Y Knightc7d3e602018-10-05 17:49:48 +00004880 // Bail out if the function declaration itself is invalid. We will
4881 // have produced a relevant diagnostic while parsing it, so just
4882 // note the problematic sub-expression.
4883 if (Declaration->isInvalidDecl()) {
4884 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004885 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004886 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004887
Richard Smithd9c6b032019-05-09 19:45:49 +00004888 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004889 // constant expression (prior to C++20). We can still constant-fold such a
4890 // call.
4891 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4892 cast<CXXMethodDecl>(Declaration)->isVirtual())
4893 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4894
4895 if (Definition && Definition->isInvalidDecl()) {
4896 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004897 return false;
4898 }
4899
Richard Smith357362d2011-12-13 06:39:58 +00004900 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004901 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004902 return true;
4903
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004904 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004905 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004906
Richard Smith5179eb72016-06-28 19:03:57 +00004907 // If this function is not constexpr because it is an inherited
4908 // non-constexpr constructor, diagnose that directly.
4909 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4910 if (CD && CD->isInheritingConstructor()) {
4911 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004912 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004913 DiagDecl = CD = Inherited;
4914 }
4915
4916 // FIXME: If DiagDecl is an implicitly-declared special member function
4917 // or an inheriting constructor, we should be much more explicit about why
4918 // it's not constexpr.
4919 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004920 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004921 << CD->getInheritedConstructor().getConstructor()->getParent();
4922 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004923 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004924 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004925 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4926 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004927 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004928 }
4929 return false;
4930}
4931
Richard Smithdebad642019-05-12 09:39:08 +00004932namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004933struct CheckDynamicTypeHandler {
4934 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004935 typedef bool result_type;
4936 bool failed() { return false; }
4937 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4938 bool found(APSInt &Value, QualType SubobjType) { return true; }
4939 bool found(APFloat &Value, QualType SubobjType) { return true; }
4940};
4941} // end anonymous namespace
4942
Richard Smith7bd54ab2019-05-15 20:22:21 +00004943/// Check that we can access the notional vptr of an object / determine its
4944/// dynamic type.
4945static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4946 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004947 if (This.Designator.Invalid)
4948 return false;
4949
Richard Smith7bd54ab2019-05-15 20:22:21 +00004950 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004951
4952 if (!Obj)
4953 return false;
4954
4955 if (!Obj.Value) {
4956 // The object is not usable in constant expressions, so we can't inspect
4957 // its value to see if it's in-lifetime or what the active union members
4958 // are. We can still check for a one-past-the-end lvalue.
4959 if (This.Designator.isOnePastTheEnd() ||
4960 This.Designator.isMostDerivedAnUnsizedArray()) {
4961 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4962 ? diag::note_constexpr_access_past_end
4963 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004964 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004965 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004966 } else if (Polymorphic) {
4967 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004968 // not be able to read a notional 'vptr' value.
4969 APValue Val;
4970 This.moveInto(Val);
4971 QualType StarThisType =
4972 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004973 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4974 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004975 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004976 }
4977 return true;
4978 }
4979
Richard Smith7bd54ab2019-05-15 20:22:21 +00004980 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004981 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4982}
4983
Richard Smith7bd54ab2019-05-15 20:22:21 +00004984/// Check that the pointee of the 'this' pointer in a member function call is
4985/// either within its lifetime or in its period of construction or destruction.
Richard Smith61422f92019-09-27 20:24:36 +00004986static bool
4987checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4988 const LValue &This,
4989 const CXXMethodDecl *NamedMember) {
4990 return checkDynamicType(
4991 Info, E, This,
4992 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
Richard Smith7bd54ab2019-05-15 20:22:21 +00004993}
4994
Richard Smith921f1322019-05-13 23:35:21 +00004995struct DynamicType {
4996 /// The dynamic class type of the object.
4997 const CXXRecordDecl *Type;
4998 /// The corresponding path length in the lvalue.
4999 unsigned PathLength;
5000};
5001
5002static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5003 unsigned PathLength) {
5004 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5005 Designator.Entries.size() && "invalid path length");
5006 return (PathLength == Designator.MostDerivedPathLength)
5007 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5008 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5009}
5010
5011/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00005012static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5013 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00005014 // If we don't have an lvalue denoting an object of class type, there is no
5015 // meaningful dynamic type. (We consider objects of non-class type to have no
5016 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00005017 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00005018 return None;
5019
Richard Smith7bd54ab2019-05-15 20:22:21 +00005020 // Refuse to compute a dynamic type in the presence of virtual bases. This
5021 // shouldn't happen other than in constant-folding situations, since literal
5022 // types can't have virtual bases.
5023 //
5024 // Note that consumers of DynamicType assume that the type has no virtual
5025 // bases, and will need modifications if this restriction is relaxed.
5026 const CXXRecordDecl *Class =
5027 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5028 if (!Class || Class->getNumVBases()) {
5029 Info.FFDiag(E);
5030 return None;
5031 }
5032
Richard Smith921f1322019-05-13 23:35:21 +00005033 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5034 // binary search here instead. But the overwhelmingly common case is that
5035 // we're not in the middle of a constructor, so it probably doesn't matter
5036 // in practice.
5037 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5038 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5039 PathLength <= Path.size(); ++PathLength) {
Richard Smith457226e2019-09-23 03:48:44 +00005040 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5041 Path.slice(0, PathLength))) {
Richard Smith921f1322019-05-13 23:35:21 +00005042 case ConstructionPhase::Bases:
Richard Smith457226e2019-09-23 03:48:44 +00005043 case ConstructionPhase::DestroyingBases:
5044 // We're constructing or destroying a base class. This is not the dynamic
5045 // type.
Richard Smith921f1322019-05-13 23:35:21 +00005046 break;
5047
5048 case ConstructionPhase::None:
5049 case ConstructionPhase::AfterBases:
Richard Smith457226e2019-09-23 03:48:44 +00005050 case ConstructionPhase::Destroying:
5051 // We've finished constructing the base classes and not yet started
5052 // destroying them again, so this is the dynamic type.
Richard Smith921f1322019-05-13 23:35:21 +00005053 return DynamicType{getBaseClassType(This.Designator, PathLength),
5054 PathLength};
5055 }
5056 }
5057
5058 // CWG issue 1517: we're constructing a base class of the object described by
5059 // 'This', so that object has not yet begun its period of construction and
5060 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00005061 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00005062 return None;
5063}
5064
5065/// Perform virtual dispatch.
5066static const CXXMethodDecl *HandleVirtualDispatch(
5067 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5068 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith61422f92019-09-27 20:24:36 +00005069 Optional<DynamicType> DynType = ComputeDynamicType(
5070 Info, E, This,
5071 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005072 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00005073 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00005074
5075 // Find the final overrider. It must be declared in one of the classes on the
5076 // path from the dynamic type to the static type.
5077 // FIXME: If we ever allow literal types to have virtual base classes, that
5078 // won't be true.
5079 const CXXMethodDecl *Callee = Found;
5080 unsigned PathLength = DynType->PathLength;
5081 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5082 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00005083 const CXXMethodDecl *Overrider =
5084 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5085 if (Overrider) {
5086 Callee = Overrider;
5087 break;
5088 }
5089 }
5090
5091 // C++2a [class.abstract]p6:
5092 // the effect of making a virtual call to a pure virtual function [...] is
5093 // undefined
5094 if (Callee->isPure()) {
5095 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5096 Info.Note(Callee->getLocation(), diag::note_declared_at);
5097 return nullptr;
5098 }
5099
5100 // If necessary, walk the rest of the path to determine the sequence of
5101 // covariant adjustment steps to apply.
5102 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5103 Found->getReturnType())) {
5104 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5105 for (unsigned CovariantPathLength = PathLength + 1;
5106 CovariantPathLength != This.Designator.Entries.size();
5107 ++CovariantPathLength) {
5108 const CXXRecordDecl *NextClass =
5109 getBaseClassType(This.Designator, CovariantPathLength);
5110 const CXXMethodDecl *Next =
5111 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5112 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5113 Next->getReturnType(), CovariantAdjustmentPath.back()))
5114 CovariantAdjustmentPath.push_back(Next->getReturnType());
5115 }
5116 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5117 CovariantAdjustmentPath.back()))
5118 CovariantAdjustmentPath.push_back(Found->getReturnType());
5119 }
5120
5121 // Perform 'this' adjustment.
5122 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5123 return nullptr;
5124
5125 return Callee;
5126}
5127
5128/// Perform the adjustment from a value returned by a virtual function to
5129/// a value of the statically expected type, which may be a pointer or
5130/// reference to a base class of the returned type.
5131static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5132 APValue &Result,
5133 ArrayRef<QualType> Path) {
5134 assert(Result.isLValue() &&
5135 "unexpected kind of APValue for covariant return");
5136 if (Result.isNullPointer())
5137 return true;
5138
5139 LValue LVal;
5140 LVal.setFrom(Info.Ctx, Result);
5141
5142 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5143 for (unsigned I = 1; I != Path.size(); ++I) {
5144 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5145 assert(OldClass && NewClass && "unexpected kind of covariant return");
5146 if (OldClass != NewClass &&
5147 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5148 return false;
5149 OldClass = NewClass;
5150 }
5151
5152 LVal.moveInto(Result);
5153 return true;
5154}
5155
Richard Smith7bd54ab2019-05-15 20:22:21 +00005156/// Determine whether \p Base, which is known to be a direct base class of
5157/// \p Derived, is a public base class.
5158static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5159 const CXXRecordDecl *Base) {
5160 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5161 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5162 if (BaseClass && declaresSameEntity(BaseClass, Base))
5163 return BaseSpec.getAccessSpecifier() == AS_public;
5164 }
5165 llvm_unreachable("Base is not a direct base of Derived");
5166}
5167
5168/// Apply the given dynamic cast operation on the provided lvalue.
5169///
5170/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5171/// to find a suitable target subobject.
5172static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5173 LValue &Ptr) {
5174 // We can't do anything with a non-symbolic pointer value.
5175 SubobjectDesignator &D = Ptr.Designator;
5176 if (D.Invalid)
5177 return false;
5178
5179 // C++ [expr.dynamic.cast]p6:
5180 // If v is a null pointer value, the result is a null pointer value.
5181 if (Ptr.isNullPointer() && !E->isGLValue())
5182 return true;
5183
5184 // For all the other cases, we need the pointer to point to an object within
5185 // its lifetime / period of construction / destruction, and we need to know
5186 // its dynamic type.
5187 Optional<DynamicType> DynType =
5188 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5189 if (!DynType)
5190 return false;
5191
5192 // C++ [expr.dynamic.cast]p7:
5193 // If T is "pointer to cv void", then the result is a pointer to the most
5194 // derived object
5195 if (E->getType()->isVoidPointerType())
5196 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5197
5198 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5199 assert(C && "dynamic_cast target is not void pointer nor class");
5200 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5201
5202 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5203 // C++ [expr.dynamic.cast]p9:
5204 if (!E->isGLValue()) {
5205 // The value of a failed cast to pointer type is the null pointer value
5206 // of the required result type.
Richard Smith19ad5232019-10-03 00:39:33 +00005207 Ptr.setNull(Info.Ctx, E->getType());
Richard Smith7bd54ab2019-05-15 20:22:21 +00005208 return true;
5209 }
5210
5211 // A failed cast to reference type throws [...] std::bad_cast.
5212 unsigned DiagKind;
5213 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5214 DynType->Type->isDerivedFrom(C)))
5215 DiagKind = 0;
5216 else if (!Paths || Paths->begin() == Paths->end())
5217 DiagKind = 1;
5218 else if (Paths->isAmbiguous(CQT))
5219 DiagKind = 2;
5220 else {
5221 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5222 DiagKind = 3;
5223 }
5224 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5225 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5226 << Info.Ctx.getRecordType(DynType->Type)
5227 << E->getType().getUnqualifiedType();
5228 return false;
5229 };
5230
5231 // Runtime check, phase 1:
5232 // Walk from the base subobject towards the derived object looking for the
5233 // target type.
5234 for (int PathLength = Ptr.Designator.Entries.size();
5235 PathLength >= (int)DynType->PathLength; --PathLength) {
5236 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5237 if (declaresSameEntity(Class, C))
5238 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5239 // We can only walk across public inheritance edges.
5240 if (PathLength > (int)DynType->PathLength &&
5241 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5242 Class))
5243 return RuntimeCheckFailed(nullptr);
5244 }
5245
5246 // Runtime check, phase 2:
5247 // Search the dynamic type for an unambiguous public base of type C.
5248 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5249 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5250 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5251 Paths.front().Access == AS_public) {
5252 // Downcast to the dynamic type...
5253 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5254 return false;
5255 // ... then upcast to the chosen base class subobject.
5256 for (CXXBasePathElement &Elem : Paths.front())
5257 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5258 return false;
5259 return true;
5260 }
5261
5262 // Otherwise, the runtime check fails.
5263 return RuntimeCheckFailed(&Paths);
5264}
5265
Richard Smith31c69a32019-05-21 23:15:20 +00005266namespace {
5267struct StartLifetimeOfUnionMemberHandler {
5268 const FieldDecl *Field;
5269
5270 static const AccessKinds AccessKind = AK_Assign;
5271
Richard Smith31c69a32019-05-21 23:15:20 +00005272 typedef bool result_type;
5273 bool failed() { return false; }
5274 bool found(APValue &Subobj, QualType SubobjType) {
5275 // We are supposed to perform no initialization but begin the lifetime of
5276 // the object. We interpret that as meaning to do what default
5277 // initialization of the object would do if all constructors involved were
5278 // trivial:
5279 // * All base, non-variant member, and array element subobjects' lifetimes
5280 // begin
5281 // * No variant members' lifetimes begin
5282 // * All scalar subobjects whose lifetimes begin have indeterminate values
5283 assert(SubobjType->isUnionType());
Richard Smith61422f92019-09-27 20:24:36 +00005284 if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5285 !Subobj.getUnionValue().hasValue())
Richard Smith31c69a32019-05-21 23:15:20 +00005286 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5287 return true;
5288 }
5289 bool found(APSInt &Value, QualType SubobjType) {
5290 llvm_unreachable("wrong value kind for union object");
5291 }
5292 bool found(APFloat &Value, QualType SubobjType) {
5293 llvm_unreachable("wrong value kind for union object");
5294 }
5295};
5296} // end anonymous namespace
5297
5298const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5299
5300/// Handle a builtin simple-assignment or a call to a trivial assignment
5301/// operator whose left-hand side might involve a union member access. If it
5302/// does, implicitly start the lifetime of any accessed union elements per
5303/// C++20 [class.union]5.
5304static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5305 const LValue &LHS) {
5306 if (LHS.InvalidBase || LHS.Designator.Invalid)
5307 return false;
5308
5309 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5310 // C++ [class.union]p5:
5311 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00005312 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005313 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005314 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5315 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5316 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
Richard Smith9a84dc02019-10-01 00:07:14 +00005317 // Note that we can't implicitly start the lifetime of a reference,
5318 // so we don't need to proceed any further if we reach one.
5319 if (!FD || FD->getType()->isReferenceType())
Richard Smith31c69a32019-05-21 23:15:20 +00005320 break;
5321
5322 // ... and also contains A.B if B names a union member
5323 if (FD->getParent()->isUnion())
5324 UnionPathLengths.push_back({PathLength - 1, FD});
5325
5326 E = ME->getBase();
5327 --PathLength;
5328 assert(declaresSameEntity(FD,
5329 LHS.Designator.Entries[PathLength]
5330 .getAsBaseOrMember().getPointer()));
5331
5332 // -- If E is of the form A[B] and is interpreted as a built-in array
5333 // subscripting operator, S(E) is [S(the array operand, if any)].
5334 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5335 // Step over an ArrayToPointerDecay implicit cast.
5336 auto *Base = ASE->getBase()->IgnoreImplicit();
5337 if (!Base->getType()->isArrayType())
5338 break;
5339
5340 E = Base;
5341 --PathLength;
5342
5343 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5344 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005345 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005346 if (ICE->getCastKind() == CK_NoOp)
5347 continue;
5348 if (ICE->getCastKind() != CK_DerivedToBase &&
5349 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5350 break;
Richard Smitha481b012019-05-30 20:45:12 +00005351 // Walk path backwards as we walk up from the base to the derived class.
5352 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005353 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005354 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005355 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5356 LHS.Designator.Entries[PathLength]
5357 .getAsBaseOrMember().getPointer()));
5358 }
Richard Smith31c69a32019-05-21 23:15:20 +00005359
5360 // -- Otherwise, S(E) is empty.
5361 } else {
5362 break;
5363 }
5364 }
5365
5366 // Common case: no unions' lifetimes are started.
5367 if (UnionPathLengths.empty())
5368 return true;
5369
5370 // if modification of X [would access an inactive union member], an object
5371 // of the type of X is implicitly created
5372 CompleteObject Obj =
5373 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5374 if (!Obj)
5375 return false;
5376 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5377 llvm::reverse(UnionPathLengths)) {
5378 // Form a designator for the union object.
5379 SubobjectDesignator D = LHS.Designator;
5380 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5381
5382 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5383 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5384 return false;
5385 }
5386
5387 return true;
5388}
5389
Richard Smithbe6dd812014-11-19 21:27:17 +00005390/// Determine if a class has any fields that might need to be copied by a
5391/// trivial copy or move operation.
5392static bool hasFields(const CXXRecordDecl *RD) {
5393 if (!RD || RD->isEmpty())
5394 return false;
5395 for (auto *FD : RD->fields()) {
5396 if (FD->isUnnamedBitfield())
5397 continue;
5398 return true;
5399 }
5400 for (auto &Base : RD->bases())
5401 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5402 return true;
5403 return false;
5404}
5405
Richard Smithd62306a2011-11-10 06:34:14 +00005406namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005407typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005408}
5409
5410/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005411static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5412 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005413 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005414 llvm::SmallBitVector ForbiddenNullArgs;
5415 if (Callee->hasAttr<NonNullAttr>()) {
5416 ForbiddenNullArgs.resize(Args.size());
5417 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5418 if (!Attr->args_size()) {
5419 ForbiddenNullArgs.set();
5420 break;
5421 } else
5422 for (auto Idx : Attr->args()) {
5423 unsigned ASTIdx = Idx.getASTIndex();
5424 if (ASTIdx >= Args.size())
5425 continue;
5426 ForbiddenNullArgs[ASTIdx] = 1;
5427 }
5428 }
5429 }
Richard Smithd62306a2011-11-10 06:34:14 +00005430 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005431 I != E; ++I) {
5432 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5433 // If we're checking for a potential constant expression, evaluate all
5434 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005435 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005436 return false;
5437 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005438 } else if (!ForbiddenNullArgs.empty() &&
5439 ForbiddenNullArgs[I - Args.begin()] &&
5440 ArgValues[I - Args.begin()].isNullPointer()) {
5441 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5442 if (!Info.noteFailure())
5443 return false;
5444 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005445 }
5446 }
5447 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005448}
5449
Richard Smith254a73d2011-10-28 22:34:42 +00005450/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005451static bool HandleFunctionCall(SourceLocation CallLoc,
5452 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005453 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005454 EvalInfo &Info, APValue &Result,
5455 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005456 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005457 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005458 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005459
Richard Smith253c2a32012-01-27 01:14:48 +00005460 if (!Info.CheckCallLimit(CallLoc))
5461 return false;
5462
5463 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005464
5465 // For a trivial copy or move assignment, perform an APValue copy. This is
5466 // essential for unions, where the operations performed by the assignment
5467 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005468 //
5469 // Skip this for non-union classes with no fields; in that case, the defaulted
5470 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005471 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005472 if (MD && MD->isDefaulted() &&
5473 (MD->getParent()->isUnion() ||
5474 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005475 assert(This &&
5476 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5477 LValue RHS;
5478 RHS.setFrom(Info.Ctx, ArgValues[0]);
5479 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005480 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5481 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005482 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005483 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5484 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5485 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005486 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005487 RHSValue))
5488 return false;
5489 This->moveInto(Result);
5490 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005491 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005492 // We're in a lambda; determine the lambda capture field maps unless we're
5493 // just constexpr checking a lambda's call operator. constexpr checking is
5494 // done before the captures have been added to the closure object (unless
5495 // we're inferring constexpr-ness), so we don't have access to them in this
5496 // case. But since we don't need the captures to constexpr check, we can
5497 // just ignore them.
5498 if (!Info.checkingPotentialConstantExpression())
5499 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5500 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005501 }
5502
Richard Smith52a980a2015-08-28 02:43:42 +00005503 StmtResult Ret = {Result, ResultSlot};
5504 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005505 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005506 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005507 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005508 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005509 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005510 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005511}
5512
Richard Smithd62306a2011-11-10 06:34:14 +00005513/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005514static bool HandleConstructorCall(const Expr *E, const LValue &This,
5515 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005516 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005517 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005518 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005519 if (!Info.CheckCallLimit(CallLoc))
5520 return false;
5521
Richard Smith3607ffe2012-02-13 03:54:03 +00005522 const CXXRecordDecl *RD = Definition->getParent();
5523 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005524 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005525 return false;
5526 }
5527
Erik Pilkington42925492017-10-04 00:18:55 +00005528 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005529 Info,
5530 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5531 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005532 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005533
Richard Smith52a980a2015-08-28 02:43:42 +00005534 // FIXME: Creating an APValue just to hold a nonexistent return value is
5535 // wasteful.
5536 APValue RetVal;
5537 StmtResult Ret = {RetVal, nullptr};
5538
Richard Smith5179eb72016-06-28 19:03:57 +00005539 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005540 if (Definition->isDelegatingConstructor()) {
5541 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005542 {
5543 FullExpressionRAII InitScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00005544 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5545 !InitScope.destroy())
Richard Smith9ff62af2013-11-07 18:45:03 +00005546 return false;
5547 }
Richard Smith52a980a2015-08-28 02:43:42 +00005548 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005549 }
5550
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005551 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005552 // essential for unions (or classes with anonymous union members), where the
5553 // operations performed by the constructor cannot be represented by
5554 // ctor-initializers.
5555 //
5556 // Skip this for empty non-union classes; we should not perform an
5557 // lvalue-to-rvalue conversion on them because their copy constructor does not
5558 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005559 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005560 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005561 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005562 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005563 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005564 return handleLValueToRValueConversion(
5565 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005566 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005567 }
5568
5569 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005570 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005571 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005572 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005573
John McCalld7bca762012-05-01 00:38:49 +00005574 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005575 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5576
Richard Smith08d6a2c2013-07-24 07:11:57 +00005577 // A scope for temporaries lifetime-extended by reference members.
5578 BlockScopeRAII LifetimeExtendedScope(Info);
5579
Richard Smith253c2a32012-01-27 01:14:48 +00005580 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005581 unsigned BasesSeen = 0;
5582#ifndef NDEBUG
5583 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5584#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005585 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5586 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5587 // We might be initializing the same field again if this is an indirect
5588 // field initialization.
5589 if (FieldIt == RD->field_end() ||
5590 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5591 assert(Indirect && "fields out of order?");
5592 return;
5593 }
5594
5595 // Default-initialize any fields with no explicit initializer.
5596 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5597 assert(FieldIt != RD->field_end() && "missing field?");
5598 if (!FieldIt->isUnnamedBitfield())
5599 Result.getStructField(FieldIt->getFieldIndex()) =
5600 getDefaultInitValue(FieldIt->getType());
5601 }
5602 ++FieldIt;
5603 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005604 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005605 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005606 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005607 APValue *Value = &Result;
5608
5609 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005610 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005611 if (I->isBaseInitializer()) {
5612 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005613#ifndef NDEBUG
5614 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005615 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005616 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5617 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5618 "base class initializers not in expected order");
5619 ++BaseIt;
5620#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005621 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005622 BaseType->getAsCXXRecordDecl(), &Layout))
5623 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005624 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005625 } else if ((FD = I->getMember())) {
5626 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005627 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005628 if (RD->isUnion()) {
5629 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005630 Value = &Result.getUnionValue();
5631 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005632 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005633 Value = &Result.getStructField(FD->getFieldIndex());
5634 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005635 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005636 // Walk the indirect field decl's chain to find the object to initialize,
5637 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005638 auto IndirectFieldChain = IFD->chain();
5639 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005640 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005641 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5642 // Switch the union field if it differs. This happens if we had
5643 // preceding zero-initialization, and we're now initializing a union
5644 // subobject other than the first.
5645 // FIXME: In this case, the values of the other subobjects are
5646 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005647 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005648 (Value->isUnion() && Value->getUnionField() != FD)) {
5649 if (CD->isUnion())
5650 *Value = APValue(FD);
5651 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005652 // FIXME: This immediately starts the lifetime of all members of an
5653 // anonymous struct. It would be preferable to strictly start member
5654 // lifetime in initialization order.
5655 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005656 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005657 // Store Subobject as its parent before updating it for the last element
5658 // in the chain.
5659 if (C == IndirectFieldChain.back())
5660 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005661 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005662 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005663 if (CD->isUnion())
5664 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005665 else {
5666 if (C == IndirectFieldChain.front() && !RD->isUnion())
5667 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005668 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005669 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005670 }
Richard Smithd62306a2011-11-10 06:34:14 +00005671 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005672 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005673 }
Richard Smith253c2a32012-01-27 01:14:48 +00005674
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005675 // Need to override This for implicit field initializers as in this case
5676 // This refers to innermost anonymous struct/union containing initializer,
5677 // not to currently constructed class.
5678 const Expr *Init = I->getInit();
5679 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5680 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005681 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005682 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5683 (FD && FD->isBitField() &&
5684 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005685 // If we're checking for a potential constant expression, evaluate all
5686 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005687 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005688 return false;
5689 Success = false;
5690 }
Richard Smith921f1322019-05-13 23:35:21 +00005691
5692 // This is the point at which the dynamic type of the object becomes this
5693 // class type.
5694 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5695 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005696 }
5697
Richard Smithc667cdc2019-09-18 17:37:44 +00005698 // Default-initialize any remaining fields.
5699 if (!RD->isUnion()) {
5700 for (; FieldIt != RD->field_end(); ++FieldIt) {
5701 if (!FieldIt->isUnnamedBitfield())
5702 Result.getStructField(FieldIt->getFieldIndex()) =
5703 getDefaultInitValue(FieldIt->getType());
5704 }
5705 }
5706
Richard Smithd9f663b2013-04-22 15:31:51 +00005707 return Success &&
Richard Smith457226e2019-09-23 03:48:44 +00005708 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5709 LifetimeExtendedScope.destroy();
Richard Smithd62306a2011-11-10 06:34:14 +00005710}
5711
Richard Smith5179eb72016-06-28 19:03:57 +00005712static bool HandleConstructorCall(const Expr *E, const LValue &This,
5713 ArrayRef<const Expr*> Args,
5714 const CXXConstructorDecl *Definition,
5715 EvalInfo &Info, APValue &Result) {
5716 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005717 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005718 return false;
5719
5720 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5721 Info, Result);
5722}
5723
Richard Smith61422f92019-09-27 20:24:36 +00005724static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5725 const LValue &This, APValue &Value,
5726 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005727 // Objects can only be destroyed while they're within their lifetimes.
5728 // FIXME: We have no representation for whether an object of type nullptr_t
5729 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5730 // as indeterminate instead?
5731 if (Value.isAbsent() && !T->isNullPtrType()) {
5732 APValue Printable;
5733 This.moveInto(Printable);
5734 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5735 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5736 return false;
5737 }
5738
Richard Smith457226e2019-09-23 03:48:44 +00005739 // Invent an expression for location purposes.
5740 // FIXME: We shouldn't need to do this.
5741 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5742
5743 // For arrays, destroy elements right-to-left.
5744 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5745 uint64_t Size = CAT->getSize().getZExtValue();
5746 QualType ElemT = CAT->getElementType();
5747
5748 LValue ElemLV = This;
5749 ElemLV.addArray(Info, &LocE, CAT);
5750 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5751 return false;
5752
Richard Smithda1b4342019-09-27 01:26:47 +00005753 // Ensure that we have actual array elements available to destroy; the
5754 // destructors might mutate the value, so we can't run them on the array
5755 // filler.
5756 if (Size && Size > Value.getArrayInitializedElts())
5757 expandArray(Value, Value.getArraySize() - 1);
5758
Richard Smith457226e2019-09-23 03:48:44 +00005759 for (; Size != 0; --Size) {
5760 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
Richard Smithda1b4342019-09-27 01:26:47 +00005761 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
Richard Smith61422f92019-09-27 20:24:36 +00005762 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
Richard Smith457226e2019-09-23 03:48:44 +00005763 return false;
5764 }
5765
5766 // End the lifetime of this array now.
5767 Value = APValue();
5768 return true;
5769 }
5770
5771 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5772 if (!RD) {
5773 if (T.isDestructedType()) {
5774 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5775 return false;
5776 }
5777
5778 Value = APValue();
5779 return true;
5780 }
5781
5782 if (RD->getNumVBases()) {
5783 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5784 return false;
5785 }
5786
5787 const CXXDestructorDecl *DD = RD->getDestructor();
Richard Smithda1b4342019-09-27 01:26:47 +00005788 if (!DD && !RD->hasTrivialDestructor()) {
Richard Smith457226e2019-09-23 03:48:44 +00005789 Info.FFDiag(CallLoc);
5790 return false;
5791 }
5792
Richard Smithda1b4342019-09-27 01:26:47 +00005793 if (!DD || DD->isTrivial() ||
Richard Smith457226e2019-09-23 03:48:44 +00005794 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5795 // A trivial destructor just ends the lifetime of the object. Check for
5796 // this case before checking for a body, because we might not bother
5797 // building a body for a trivial destructor. Note that it doesn't matter
5798 // whether the destructor is constexpr in this case; all trivial
5799 // destructors are constexpr.
5800 //
5801 // If an anonymous union would be destroyed, some enclosing destructor must
5802 // have been explicitly defined, and the anonymous union destruction should
5803 // have no effect.
5804 Value = APValue();
5805 return true;
5806 }
5807
5808 if (!Info.CheckCallLimit(CallLoc))
5809 return false;
5810
Richard Smithda1b4342019-09-27 01:26:47 +00005811 const FunctionDecl *Definition = nullptr;
5812 const Stmt *Body = DD->getBody(Definition);
5813
Richard Smith457226e2019-09-23 03:48:44 +00005814 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5815 return false;
5816
5817 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5818
5819 // We're now in the period of destruction of this object.
5820 unsigned BasesLeft = RD->getNumBases();
5821 EvalInfo::EvaluatingDestructorRAII EvalObj(
5822 Info,
5823 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
Richard Smithda1b4342019-09-27 01:26:47 +00005824 if (!EvalObj.DidInsert) {
5825 // C++2a [class.dtor]p19:
5826 // the behavior is undefined if the destructor is invoked for an object
5827 // whose lifetime has ended
5828 // (Note that formally the lifetime ends when the period of destruction
5829 // begins, even though certain uses of the object remain valid until the
5830 // period of destruction ends.)
5831 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5832 return false;
5833 }
Richard Smith457226e2019-09-23 03:48:44 +00005834
5835 // FIXME: Creating an APValue just to hold a nonexistent return value is
5836 // wasteful.
5837 APValue RetVal;
5838 StmtResult Ret = {RetVal, nullptr};
5839 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5840 return false;
5841
5842 // A union destructor does not implicitly destroy its members.
5843 if (RD->isUnion())
5844 return true;
5845
5846 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5847
5848 // We don't have a good way to iterate fields in reverse, so collect all the
5849 // fields first and then walk them backwards.
5850 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5851 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5852 if (FD->isUnnamedBitfield())
5853 continue;
5854
5855 LValue Subobject = This;
5856 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5857 return false;
5858
5859 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
Richard Smith61422f92019-09-27 20:24:36 +00005860 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5861 FD->getType()))
Richard Smith457226e2019-09-23 03:48:44 +00005862 return false;
5863 }
5864
5865 if (BasesLeft != 0)
5866 EvalObj.startedDestroyingBases();
5867
5868 // Destroy base classes in reverse order.
5869 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5870 --BasesLeft;
5871
5872 QualType BaseType = Base.getType();
5873 LValue Subobject = This;
5874 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5875 BaseType->getAsCXXRecordDecl(), &Layout))
5876 return false;
5877
5878 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
Richard Smith61422f92019-09-27 20:24:36 +00005879 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5880 BaseType))
Richard Smith457226e2019-09-23 03:48:44 +00005881 return false;
5882 }
5883 assert(BasesLeft == 0 && "NumBases was wrong?");
5884
5885 // The period of destruction ends now. The object is gone.
5886 Value = APValue();
5887 return true;
5888}
5889
Richard Smith61422f92019-09-27 20:24:36 +00005890namespace {
5891struct DestroyObjectHandler {
5892 EvalInfo &Info;
5893 const Expr *E;
5894 const LValue &This;
5895 const AccessKinds AccessKind;
5896
5897 typedef bool result_type;
5898 bool failed() { return false; }
5899 bool found(APValue &Subobj, QualType SubobjType) {
5900 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5901 SubobjType);
5902 }
5903 bool found(APSInt &Value, QualType SubobjType) {
5904 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5905 return false;
5906 }
5907 bool found(APFloat &Value, QualType SubobjType) {
5908 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5909 return false;
5910 }
5911};
5912}
5913
5914/// Perform a destructor or pseudo-destructor call on the given object, which
5915/// might in general not be a complete object.
5916static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5917 const LValue &This, QualType ThisType) {
5918 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5919 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5920 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5921}
5922
5923/// Destroy and end the lifetime of the given complete object.
5924static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5925 APValue::LValueBase LVBase, APValue &Value,
5926 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005927 // If we've had an unmodeled side-effect, we can't rely on mutable state
5928 // (such as the object we're about to destroy) being correct.
5929 if (Info.EvalStatus.HasSideEffects)
5930 return false;
Richard Smith457226e2019-09-23 03:48:44 +00005931
5932 LValue LV;
5933 LV.set({LVBase});
Richard Smith61422f92019-09-27 20:24:36 +00005934 return HandleDestructionImpl(Info, Loc, LV, Value, T);
Richard Smith457226e2019-09-23 03:48:44 +00005935}
5936
Richard Smith19ad5232019-10-03 00:39:33 +00005937/// Perform a call to 'perator new' or to `__builtin_operator_new'.
5938static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
5939 LValue &Result) {
5940 if (Info.checkingPotentialConstantExpression() ||
5941 Info.SpeculativeEvaluationDepth)
5942 return false;
5943
5944 // This is permitted only within a call to std::allocator<T>::allocate.
5945 auto Caller = Info.getStdAllocatorCaller("allocate");
5946 if (!Caller) {
5947 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
5948 ? diag::note_constexpr_new_untyped
5949 : diag::note_constexpr_new);
5950 return false;
5951 }
5952
5953 QualType ElemType = Caller.ElemType;
5954 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
5955 Info.FFDiag(E->getExprLoc(),
5956 diag::note_constexpr_new_not_complete_object_type)
5957 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
5958 return false;
5959 }
5960
5961 APSInt ByteSize;
5962 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
5963 return false;
5964 bool IsNothrow = false;
5965 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
5966 EvaluateIgnoredValue(Info, E->getArg(I));
5967 IsNothrow |= E->getType()->isNothrowT();
5968 }
5969
5970 CharUnits ElemSize;
5971 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
5972 return false;
5973 APInt Size, Remainder;
5974 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
5975 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
5976 if (Remainder != 0) {
5977 // This likely indicates a bug in the implementation of 'std::allocator'.
5978 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
5979 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
5980 return false;
5981 }
5982
5983 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
5984 if (IsNothrow) {
5985 Result.setNull(Info.Ctx, E->getType());
5986 return true;
5987 }
5988
5989 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
5990 return false;
5991 }
5992
5993 QualType AllocType =
5994 Info.Ctx.getConstantArrayType(ElemType, Size, ArrayType::Normal, 0);
5995 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
5996 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
5997 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
5998 return true;
5999}
6000
6001static bool hasVirtualDestructor(QualType T) {
6002 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6003 if (CXXDestructorDecl *DD = RD->getDestructor())
6004 return DD->isVirtual();
6005 return false;
6006}
6007
6008/// Check that the given object is a suitable pointer to a heap allocation that
6009/// still exists and is of the right kind for the purpose of a deletion.
6010///
6011/// On success, returns the heap allocation to deallocate. On failure, produces
6012/// a diagnostic and returns None.
6013static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6014 const LValue &Pointer,
6015 DynAlloc::Kind DeallocKind) {
6016 auto PointerAsString = [&] {
6017 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6018 };
6019
6020 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6021 if (!DA) {
6022 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6023 << PointerAsString();
6024 if (Pointer.Base)
6025 NoteLValueLocation(Info, Pointer.Base);
6026 return None;
6027 }
6028
6029 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6030 if (!Alloc) {
6031 Info.FFDiag(E, diag::note_constexpr_double_delete);
6032 return None;
6033 }
6034
6035 QualType AllocType = Pointer.Base.getDynamicAllocType();
6036 if (DeallocKind != (*Alloc)->getKind()) {
6037 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6038 << DeallocKind << (*Alloc)->getKind() << AllocType;
6039 NoteLValueLocation(Info, Pointer.Base);
6040 return None;
6041 }
6042
6043 bool Subobject = false;
6044 if (DeallocKind == DynAlloc::New) {
6045 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6046 Pointer.Designator.isOnePastTheEnd();
6047 } else {
6048 Subobject = Pointer.Designator.Entries.size() != 1 ||
6049 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6050 }
6051 if (Subobject) {
6052 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6053 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6054 return None;
6055 }
6056
6057 return Alloc;
6058}
6059
6060// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6061bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6062 if (Info.checkingPotentialConstantExpression() ||
6063 Info.SpeculativeEvaluationDepth)
6064 return false;
6065
6066 // This is permitted only within a call to std::allocator<T>::deallocate.
6067 if (!Info.getStdAllocatorCaller("deallocate")) {
6068 Info.FFDiag(E->getExprLoc());
6069 return true;
6070 }
6071
6072 LValue Pointer;
6073 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6074 return false;
6075 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6076 EvaluateIgnoredValue(Info, E->getArg(I));
6077
6078 if (Pointer.Designator.Invalid)
6079 return false;
6080
6081 // Deleting a null pointer has no effect.
6082 if (Pointer.isNullPointer())
6083 return true;
6084
6085 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6086 return false;
6087
6088 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6089 return true;
6090}
6091
Eli Friedman9a156e52008-11-12 09:44:48 +00006092//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00006093// Generic Evaluation
6094//===----------------------------------------------------------------------===//
6095namespace {
6096
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006097class BitCastBuffer {
6098 // FIXME: We're going to need bit-level granularity when we support
6099 // bit-fields.
6100 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6101 // we don't support a host or target where that is the case. Still, we should
6102 // use a more generic type in case we ever do.
6103 SmallVector<Optional<unsigned char>, 32> Bytes;
6104
6105 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6106 "Need at least 8 bit unsigned char");
6107
6108 bool TargetIsLittleEndian;
6109
6110public:
6111 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6112 : Bytes(Width.getQuantity()),
6113 TargetIsLittleEndian(TargetIsLittleEndian) {}
6114
6115 LLVM_NODISCARD
6116 bool readObject(CharUnits Offset, CharUnits Width,
6117 SmallVectorImpl<unsigned char> &Output) const {
6118 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6119 // If a byte of an integer is uninitialized, then the whole integer is
6120 // uninitalized.
6121 if (!Bytes[I.getQuantity()])
6122 return false;
6123 Output.push_back(*Bytes[I.getQuantity()]);
6124 }
6125 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6126 std::reverse(Output.begin(), Output.end());
6127 return true;
6128 }
6129
6130 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6131 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6132 std::reverse(Input.begin(), Input.end());
6133
6134 size_t Index = 0;
6135 for (unsigned char Byte : Input) {
6136 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6137 Bytes[Offset.getQuantity() + Index] = Byte;
6138 ++Index;
6139 }
6140 }
6141
6142 size_t size() { return Bytes.size(); }
6143};
6144
6145/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6146/// target would represent the value at runtime.
6147class APValueToBufferConverter {
6148 EvalInfo &Info;
6149 BitCastBuffer Buffer;
6150 const CastExpr *BCE;
6151
6152 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6153 const CastExpr *BCE)
6154 : Info(Info),
6155 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6156 BCE(BCE) {}
6157
6158 bool visit(const APValue &Val, QualType Ty) {
6159 return visit(Val, Ty, CharUnits::fromQuantity(0));
6160 }
6161
6162 // Write out Val with type Ty into Buffer starting at Offset.
6163 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6164 assert((size_t)Offset.getQuantity() <= Buffer.size());
6165
6166 // As a special case, nullptr_t has an indeterminate value.
6167 if (Ty->isNullPtrType())
6168 return true;
6169
6170 // Dig through Src to find the byte at SrcOffset.
6171 switch (Val.getKind()) {
6172 case APValue::Indeterminate:
6173 case APValue::None:
6174 return true;
6175
6176 case APValue::Int:
6177 return visitInt(Val.getInt(), Ty, Offset);
6178 case APValue::Float:
6179 return visitFloat(Val.getFloat(), Ty, Offset);
6180 case APValue::Array:
6181 return visitArray(Val, Ty, Offset);
6182 case APValue::Struct:
6183 return visitRecord(Val, Ty, Offset);
6184
6185 case APValue::ComplexInt:
6186 case APValue::ComplexFloat:
6187 case APValue::Vector:
6188 case APValue::FixedPoint:
6189 // FIXME: We should support these.
6190
6191 case APValue::Union:
6192 case APValue::MemberPointer:
6193 case APValue::AddrLabelDiff: {
6194 Info.FFDiag(BCE->getBeginLoc(),
6195 diag::note_constexpr_bit_cast_unsupported_type)
6196 << Ty;
6197 return false;
6198 }
6199
6200 case APValue::LValue:
6201 llvm_unreachable("LValue subobject in bit_cast?");
6202 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006203 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006204 }
6205
6206 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6207 const RecordDecl *RD = Ty->getAsRecordDecl();
6208 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6209
6210 // Visit the base classes.
6211 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6212 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6213 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6214 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6215
6216 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6217 Layout.getBaseClassOffset(BaseDecl) + Offset))
6218 return false;
6219 }
6220 }
6221
6222 // Visit the fields.
6223 unsigned FieldIdx = 0;
6224 for (FieldDecl *FD : RD->fields()) {
6225 if (FD->isBitField()) {
6226 Info.FFDiag(BCE->getBeginLoc(),
6227 diag::note_constexpr_bit_cast_unsupported_bitfield);
6228 return false;
6229 }
6230
6231 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6232
6233 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6234 "only bit-fields can have sub-char alignment");
6235 CharUnits FieldOffset =
6236 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6237 QualType FieldTy = FD->getType();
6238 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6239 return false;
6240 ++FieldIdx;
6241 }
6242
6243 return true;
6244 }
6245
6246 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6247 const auto *CAT =
6248 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6249 if (!CAT)
6250 return false;
6251
6252 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6253 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6254 unsigned ArraySize = Val.getArraySize();
6255 // First, initialize the initialized elements.
6256 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6257 const APValue &SubObj = Val.getArrayInitializedElt(I);
6258 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6259 return false;
6260 }
6261
6262 // Next, initialize the rest of the array using the filler.
6263 if (Val.hasArrayFiller()) {
6264 const APValue &Filler = Val.getArrayFiller();
6265 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6266 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6267 return false;
6268 }
6269 }
6270
6271 return true;
6272 }
6273
6274 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6275 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6276 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6277 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6278 Buffer.writeObject(Offset, Bytes);
6279 return true;
6280 }
6281
6282 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6283 APSInt AsInt(Val.bitcastToAPInt());
6284 return visitInt(AsInt, Ty, Offset);
6285 }
6286
6287public:
6288 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6289 const CastExpr *BCE) {
6290 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6291 APValueToBufferConverter Converter(Info, DstSize, BCE);
6292 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6293 return None;
6294 return Converter.Buffer;
6295 }
6296};
6297
6298/// Write an BitCastBuffer into an APValue.
6299class BufferToAPValueConverter {
6300 EvalInfo &Info;
6301 const BitCastBuffer &Buffer;
6302 const CastExpr *BCE;
6303
6304 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6305 const CastExpr *BCE)
6306 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6307
6308 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6309 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6310 // Ideally this will be unreachable.
6311 llvm::NoneType unsupportedType(QualType Ty) {
6312 Info.FFDiag(BCE->getBeginLoc(),
6313 diag::note_constexpr_bit_cast_unsupported_type)
6314 << Ty;
6315 return None;
6316 }
6317
6318 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6319 const EnumType *EnumSugar = nullptr) {
6320 if (T->isNullPtrType()) {
6321 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6322 return APValue((Expr *)nullptr,
6323 /*Offset=*/CharUnits::fromQuantity(NullValue),
6324 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6325 }
6326
6327 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6328 SmallVector<uint8_t, 8> Bytes;
6329 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6330 // If this is std::byte or unsigned char, then its okay to store an
6331 // indeterminate value.
6332 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6333 bool IsUChar =
6334 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6335 T->isSpecificBuiltinType(BuiltinType::Char_U));
6336 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00006337 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006338 Info.FFDiag(BCE->getExprLoc(),
6339 diag::note_constexpr_bit_cast_indet_dest)
6340 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6341 return None;
6342 }
6343
6344 return APValue::IndeterminateValue();
6345 }
6346
6347 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6348 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6349
6350 if (T->isIntegralOrEnumerationType()) {
6351 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6352 return APValue(Val);
6353 }
6354
6355 if (T->isRealFloatingType()) {
6356 const llvm::fltSemantics &Semantics =
6357 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6358 return APValue(APFloat(Semantics, Val));
6359 }
6360
6361 return unsupportedType(QualType(T, 0));
6362 }
6363
6364 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6365 const RecordDecl *RD = RTy->getAsRecordDecl();
6366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6367
6368 unsigned NumBases = 0;
6369 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6370 NumBases = CXXRD->getNumBases();
6371
6372 APValue ResultVal(APValue::UninitStruct(), NumBases,
6373 std::distance(RD->field_begin(), RD->field_end()));
6374
6375 // Visit the base classes.
6376 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6377 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6378 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6379 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6380 if (BaseDecl->isEmpty() ||
6381 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6382 continue;
6383
6384 Optional<APValue> SubObj = visitType(
6385 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6386 if (!SubObj)
6387 return None;
6388 ResultVal.getStructBase(I) = *SubObj;
6389 }
6390 }
6391
6392 // Visit the fields.
6393 unsigned FieldIdx = 0;
6394 for (FieldDecl *FD : RD->fields()) {
6395 // FIXME: We don't currently support bit-fields. A lot of the logic for
6396 // this is in CodeGen, so we need to factor it around.
6397 if (FD->isBitField()) {
6398 Info.FFDiag(BCE->getBeginLoc(),
6399 diag::note_constexpr_bit_cast_unsupported_bitfield);
6400 return None;
6401 }
6402
6403 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6404 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6405
6406 CharUnits FieldOffset =
6407 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6408 Offset;
6409 QualType FieldTy = FD->getType();
6410 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6411 if (!SubObj)
6412 return None;
6413 ResultVal.getStructField(FieldIdx) = *SubObj;
6414 ++FieldIdx;
6415 }
6416
6417 return ResultVal;
6418 }
6419
6420 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6421 QualType RepresentationType = Ty->getDecl()->getIntegerType();
6422 assert(!RepresentationType.isNull() &&
6423 "enum forward decl should be caught by Sema");
6424 const BuiltinType *AsBuiltin =
6425 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
6426 assert(AsBuiltin && "non-integral enum underlying type?");
6427 // Recurse into the underlying type. Treat std::byte transparently as
6428 // unsigned char.
6429 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6430 }
6431
6432 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6433 size_t Size = Ty->getSize().getLimitedValue();
6434 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6435
6436 APValue ArrayValue(APValue::UninitArray(), Size, Size);
6437 for (size_t I = 0; I != Size; ++I) {
6438 Optional<APValue> ElementValue =
6439 visitType(Ty->getElementType(), Offset + I * ElementWidth);
6440 if (!ElementValue)
6441 return None;
6442 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6443 }
6444
6445 return ArrayValue;
6446 }
6447
6448 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6449 return unsupportedType(QualType(Ty, 0));
6450 }
6451
6452 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6453 QualType Can = Ty.getCanonicalType();
6454
6455 switch (Can->getTypeClass()) {
6456#define TYPE(Class, Base) \
6457 case Type::Class: \
6458 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6459#define ABSTRACT_TYPE(Class, Base)
6460#define NON_CANONICAL_TYPE(Class, Base) \
6461 case Type::Class: \
6462 llvm_unreachable("non-canonical type should be impossible!");
6463#define DEPENDENT_TYPE(Class, Base) \
6464 case Type::Class: \
6465 llvm_unreachable( \
6466 "dependent types aren't supported in the constant evaluator!");
6467#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
6468 case Type::Class: \
6469 llvm_unreachable("either dependent or not canonical!");
John McCall36b12a82019-10-02 06:35:23 +00006470#include "clang/AST/TypeNodes.inc"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006471 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006472 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006473 }
6474
6475public:
6476 // Pull out a full value of type DstType.
6477 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6478 const CastExpr *BCE) {
6479 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6480 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6481 }
6482};
6483
6484static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6485 QualType Ty, EvalInfo *Info,
6486 const ASTContext &Ctx,
6487 bool CheckingDest) {
6488 Ty = Ty.getCanonicalType();
6489
6490 auto diag = [&](int Reason) {
6491 if (Info)
6492 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6493 << CheckingDest << (Reason == 4) << Reason;
6494 return false;
6495 };
6496 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6497 if (Info)
6498 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6499 << NoteTy << Construct << Ty;
6500 return false;
6501 };
6502
6503 if (Ty->isUnionType())
6504 return diag(0);
6505 if (Ty->isPointerType())
6506 return diag(1);
6507 if (Ty->isMemberPointerType())
6508 return diag(2);
6509 if (Ty.isVolatileQualified())
6510 return diag(3);
6511
6512 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6513 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6514 for (CXXBaseSpecifier &BS : CXXRD->bases())
6515 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6516 CheckingDest))
6517 return note(1, BS.getType(), BS.getBeginLoc());
6518 }
6519 for (FieldDecl *FD : Record->fields()) {
6520 if (FD->getType()->isReferenceType())
6521 return diag(4);
6522 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6523 CheckingDest))
6524 return note(0, FD->getType(), FD->getBeginLoc());
6525 }
6526 }
6527
6528 if (Ty->isArrayType() &&
6529 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6530 Info, Ctx, CheckingDest))
6531 return false;
6532
6533 return true;
6534}
6535
6536static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6537 const ASTContext &Ctx,
6538 const CastExpr *BCE) {
6539 bool DestOK = checkBitCastConstexprEligibilityType(
6540 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6541 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6542 BCE->getBeginLoc(),
6543 BCE->getSubExpr()->getType(), Info, Ctx, false);
6544 return SourceOK;
6545}
6546
6547static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6548 APValue &SourceValue,
6549 const CastExpr *BCE) {
6550 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6551 "no host or target supports non 8-bit chars");
6552 assert(SourceValue.isLValue() &&
6553 "LValueToRValueBitcast requires an lvalue operand!");
6554
6555 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6556 return false;
6557
6558 LValue SourceLValue;
6559 APValue SourceRValue;
6560 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00006561 if (!handleLValueToRValueConversion(
6562 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6563 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006564 return false;
6565
6566 // Read out SourceValue into a char buffer.
6567 Optional<BitCastBuffer> Buffer =
6568 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6569 if (!Buffer)
6570 return false;
6571
6572 // Write out the buffer into a new APValue.
6573 Optional<APValue> MaybeDestValue =
6574 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6575 if (!MaybeDestValue)
6576 return false;
6577
6578 DestValue = std::move(*MaybeDestValue);
6579 return true;
6580}
6581
Aaron Ballman68af21c2014-01-03 19:26:43 +00006582template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00006583class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006584 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00006585private:
Richard Smith52a980a2015-08-28 02:43:42 +00006586 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006587 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006588 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006589 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006590 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006591 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006592 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006593
Richard Smith17100ba2012-02-16 02:46:34 +00006594 // Check whether a conditional operator with a non-constant condition is a
6595 // potential constant expression. If neither arm is a potential constant
6596 // expression, then the conditional operator is not either.
6597 template<typename ConditionalOperator>
6598 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00006599 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00006600
6601 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00006602 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00006603 {
Richard Smith17100ba2012-02-16 02:46:34 +00006604 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006605 StmtVisitorTy::Visit(E->getFalseExpr());
6606 if (Diag.empty())
6607 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00006608 }
Richard Smith17100ba2012-02-16 02:46:34 +00006609
George Burgess IV8c892b52016-05-25 22:31:54 +00006610 {
6611 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006612 Diag.clear();
6613 StmtVisitorTy::Visit(E->getTrueExpr());
6614 if (Diag.empty())
6615 return;
6616 }
6617
6618 Error(E, diag::note_constexpr_conditional_never_const);
6619 }
6620
6621
6622 template<typename ConditionalOperator>
6623 bool HandleConditionalOperator(const ConditionalOperator *E) {
6624 bool BoolResult;
6625 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00006626 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00006627 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00006628 return false;
6629 }
6630 if (Info.noteFailure()) {
6631 StmtVisitorTy::Visit(E->getTrueExpr());
6632 StmtVisitorTy::Visit(E->getFalseExpr());
6633 }
Richard Smith17100ba2012-02-16 02:46:34 +00006634 return false;
6635 }
6636
6637 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6638 return StmtVisitorTy::Visit(EvalExpr);
6639 }
6640
Peter Collingbournee9200682011-05-13 03:29:01 +00006641protected:
6642 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006643 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00006644 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6645
Richard Smith92b1ce02011-12-12 09:28:41 +00006646 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006647 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006648 }
6649
Aaron Ballman68af21c2014-01-03 19:26:43 +00006650 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006651
6652public:
6653 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6654
6655 EvalInfo &getEvalInfo() { return Info; }
6656
Richard Smithf57d8cb2011-12-09 22:58:01 +00006657 /// Report an evaluation error. This should only be called when an error is
6658 /// first discovered. When propagating an error, just return false.
6659 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006660 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006661 return false;
6662 }
6663 bool Error(const Expr *E) {
6664 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6665 }
6666
Aaron Ballman68af21c2014-01-03 19:26:43 +00006667 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00006668 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00006669 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006670 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006671 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006672 }
6673
Bill Wendling8003edc2018-11-09 00:41:36 +00006674 bool VisitConstantExpr(const ConstantExpr *E)
6675 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006676 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006677 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006678 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006679 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006680 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006681 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006682 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00006683 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006684 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006685 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006686 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00006687 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006688 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6689 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00006690 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006691 return StmtVisitorTy::Visit(E->getExpr());
6692 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006693 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006694 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00006695 // The initializer may not have been parsed yet, or might be erroneous.
6696 if (!E->getExpr())
6697 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00006698 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00006699 return StmtVisitorTy::Visit(E->getExpr());
6700 }
Eric Fiselier708afb52019-05-16 21:04:15 +00006701
Richard Smith457226e2019-09-23 03:48:44 +00006702 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6703 FullExpressionRAII Scope(Info);
6704 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6705 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006706
Richard Smith3b69bcc2019-10-01 00:41:16 +00006707 // Temporaries are registered when created, so we don't care about
6708 // CXXBindTemporaryExpr.
6709 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6710 return StmtVisitorTy::Visit(E->getSubExpr());
6711 }
6712
Aaron Ballman68af21c2014-01-03 19:26:43 +00006713 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006714 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6715 return static_cast<Derived*>(this)->VisitCastExpr(E);
6716 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006717 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00006718 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006720 return static_cast<Derived*>(this)->VisitCastExpr(E);
6721 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006722 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6723 return static_cast<Derived*>(this)->VisitCastExpr(E);
6724 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006725
Aaron Ballman68af21c2014-01-03 19:26:43 +00006726 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006727 switch (E->getOpcode()) {
6728 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006729 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006730
6731 case BO_Comma:
6732 VisitIgnoredValue(E->getLHS());
6733 return StmtVisitorTy::Visit(E->getRHS());
6734
6735 case BO_PtrMemD:
6736 case BO_PtrMemI: {
6737 LValue Obj;
6738 if (!HandleMemberPointerAccess(Info, E, Obj))
6739 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006740 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006741 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006742 return false;
6743 return DerivedSuccess(Result, E);
6744 }
6745 }
6746 }
6747
Aaron Ballman68af21c2014-01-03 19:26:43 +00006748 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006749 // Evaluate and cache the common expression. We treat it as a temporary,
6750 // even though it's not quite the same thing.
Richard Smith457226e2019-09-23 03:48:44 +00006751 LValue CommonLV;
6752 if (!Evaluate(Info.CurrentCall->createTemporary(
Richard Smith61422f92019-09-27 20:24:36 +00006753 E->getOpaqueValue(),
6754 getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6755 CommonLV),
Richard Smith26d4cc12012-06-26 08:12:11 +00006756 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006757 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006758
Richard Smith17100ba2012-02-16 02:46:34 +00006759 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006760 }
6761
Aaron Ballman68af21c2014-01-03 19:26:43 +00006762 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006763 bool IsBcpCall = false;
6764 // If the condition (ignoring parens) is a __builtin_constant_p call,
6765 // the result is a constant expression if it can be folded without
6766 // side-effects. This is an important GNU extension. See GCC PR38377
6767 // for discussion.
6768 if (const CallExpr *CallCE =
6769 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006770 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006771 IsBcpCall = true;
6772
6773 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6774 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00006775 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6776 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00006777 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006778 return false;
6779
Richard Smith6d4c6582013-11-05 22:18:15 +00006780 FoldConstant Fold(Info, IsBcpCall);
6781 if (!HandleConditionalOperator(E)) {
6782 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006783 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006784 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006785
6786 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006787 }
6788
Aaron Ballman68af21c2014-01-03 19:26:43 +00006789 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006790 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006791 return DerivedSuccess(*Value, E);
6792
6793 const Expr *Source = E->getSourceExpr();
6794 if (!Source)
6795 return Error(E);
6796 if (Source == E) { // sanity checking.
6797 assert(0 && "OpaqueValueExpr recursively refers to itself");
6798 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006799 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006800 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006801 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006802
Aaron Ballman68af21c2014-01-03 19:26:43 +00006803 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006804 APValue Result;
6805 if (!handleCallExpr(E, Result, nullptr))
6806 return false;
6807 return DerivedSuccess(Result, E);
6808 }
6809
6810 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006811 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006812 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006813 QualType CalleeType = Callee->getType();
6814
Craig Topper36250ad2014-05-12 05:36:57 +00006815 const FunctionDecl *FD = nullptr;
6816 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006817 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006818 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006819
Richard Smithe97cbd72011-11-11 04:05:33 +00006820 // Extract function decl and 'this' pointer from the callee.
6821 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006822 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006823 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6824 // Explicit bound member calls, such as x.f() or p->g();
6825 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006826 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006827 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6828 if (!Member)
6829 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006830 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006831 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006832 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6833 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006834 Member = dyn_cast_or_null<CXXMethodDecl>(
6835 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6836 if (!Member)
6837 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006838 This = &ThisVal;
Richard Smith61422f92019-09-27 20:24:36 +00006839 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6840 if (!Info.getLangOpts().CPlusPlus2a)
6841 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6842 // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6843 // their callee, we should start calling HandleDestruction here.
6844 // For now, we just evaluate the object argument and discard it.
6845 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
Richard Smith027bf112011-11-17 22:56:20 +00006846 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006847 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006848 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006849 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006850 LValue Call;
6851 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006852 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006853
Richard Smitha8105bc2012-01-06 16:39:00 +00006854 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006855 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006856 FD = dyn_cast_or_null<FunctionDecl>(
6857 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006858 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006859 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006860 // Don't call function pointers which have been cast to some other type.
6861 // Per DR (no number yet), the caller and callee can differ in noexcept.
6862 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6863 CalleeType->getPointeeType(), FD->getType())) {
6864 return Error(E);
6865 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006866
6867 // Overloaded operator calls to member functions are represented as normal
6868 // calls with '*this' as the first argument.
6869 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6870 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006871 // FIXME: When selecting an implicit conversion for an overloaded
6872 // operator delete, we sometimes try to evaluate calls to conversion
6873 // operators without a 'this' parameter!
6874 if (Args.empty())
6875 return Error(E);
6876
Nick Lewycky13073a62017-06-12 21:15:44 +00006877 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006878 return false;
6879 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006880 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006881 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006882 // Map the static invoker for the lambda back to the call operator.
6883 // Conveniently, we don't have to slice out the 'this' argument (as is
6884 // being done for the non-static case), since a static member function
6885 // doesn't have an implicit argument passed in.
6886 const CXXRecordDecl *ClosureClass = MD->getParent();
6887 assert(
6888 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6889 "Number of captures must be zero for conversion to function-ptr");
6890
6891 const CXXMethodDecl *LambdaCallOp =
6892 ClosureClass->getLambdaCallOperator();
6893
6894 // Set 'FD', the function that will be called below, to the call
6895 // operator. If the closure object represents a generic lambda, find
6896 // the corresponding specialization of the call operator.
6897
6898 if (ClosureClass->isGenericLambda()) {
6899 assert(MD->isFunctionTemplateSpecialization() &&
6900 "A generic lambda's static-invoker function must be a "
6901 "template specialization");
6902 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6903 FunctionTemplateDecl *CallOpTemplate =
6904 LambdaCallOp->getDescribedFunctionTemplate();
6905 void *InsertPos = nullptr;
6906 FunctionDecl *CorrespondingCallOpSpecialization =
6907 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6908 assert(CorrespondingCallOpSpecialization &&
6909 "We must always have a function call operator specialization "
6910 "that corresponds to our static invoker specialization");
6911 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6912 } else
6913 FD = LambdaCallOp;
Richard Smith19ad5232019-10-03 00:39:33 +00006914 } else if (FD->isReplaceableGlobalAllocationFunction()) {
6915 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
6916 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
6917 LValue Ptr;
6918 if (!HandleOperatorNewCall(Info, E, Ptr))
6919 return false;
6920 Ptr.moveInto(Result);
6921 return true;
6922 } else {
6923 return HandleOperatorDeleteCall(Info, E);
6924 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006925 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006926 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006927 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006928
Richard Smith921f1322019-05-13 23:35:21 +00006929 SmallVector<QualType, 4> CovariantAdjustmentPath;
6930 if (This) {
6931 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006932 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6933 // Perform virtual dispatch, if necessary.
6934 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6935 CovariantAdjustmentPath);
6936 if (!FD)
6937 return false;
6938 } else {
6939 // Check that the 'this' pointer points to an object of the right type.
Richard Smith61422f92019-09-27 20:24:36 +00006940 // FIXME: If this is an assignment operator call, we may need to change
6941 // the active union member before we check this.
6942 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
Richard Smith7bd54ab2019-05-15 20:22:21 +00006943 return false;
6944 }
Richard Smith921f1322019-05-13 23:35:21 +00006945 }
Richard Smith47b34932012-02-01 02:39:43 +00006946
Richard Smith61422f92019-09-27 20:24:36 +00006947 // Destructor calls are different enough that they have their own codepath.
6948 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
6949 assert(This && "no 'this' pointer for destructor call");
6950 return HandleDestruction(Info, E, *This,
6951 Info.Ctx.getRecordType(DD->getParent()));
6952 }
6953
Craig Topper36250ad2014-05-12 05:36:57 +00006954 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006955 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006956
Nick Lewycky13073a62017-06-12 21:15:44 +00006957 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6958 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006959 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006960 return false;
6961
Richard Smith921f1322019-05-13 23:35:21 +00006962 if (!CovariantAdjustmentPath.empty() &&
6963 !HandleCovariantReturnAdjustment(Info, E, Result,
6964 CovariantAdjustmentPath))
6965 return false;
6966
Richard Smith52a980a2015-08-28 02:43:42 +00006967 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006968 }
6969
Aaron Ballman68af21c2014-01-03 19:26:43 +00006970 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006971 return StmtVisitorTy::Visit(E->getInitializer());
6972 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006973 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006974 if (E->getNumInits() == 0)
6975 return DerivedZeroInitialization(E);
6976 if (E->getNumInits() == 1)
6977 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006978 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006979 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006980 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006981 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006982 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006983 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006984 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006985 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006986 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006987 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006988 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006989
Richard Smithd62306a2011-11-10 06:34:14 +00006990 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006991 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006992 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6993 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006994 assert(!E->isArrow() && "missing call to bound member function?");
6995
Richard Smith2e312c82012-03-03 22:46:17 +00006996 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006997 if (!Evaluate(Val, Info, E->getBase()))
6998 return false;
6999
7000 QualType BaseTy = E->getBase()->getType();
7001
7002 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00007003 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007004 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00007005 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00007006 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7007
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007008 // Note: there is no lvalue base here. But this case should only ever
7009 // happen in C or in C++98, where we cannot be evaluating a constexpr
7010 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00007011 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00007012 SubobjectDesignator Designator(BaseTy);
7013 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00007014
Richard Smith3229b742013-05-05 21:17:10 +00007015 APValue Result;
7016 return extractSubobject(Info, E, Obj, Designator, Result) &&
7017 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00007018 }
7019
Aaron Ballman68af21c2014-01-03 19:26:43 +00007020 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007021 switch (E->getCastKind()) {
7022 default:
7023 break;
7024
Richard Smitha23ab512013-05-23 00:30:41 +00007025 case CK_AtomicToNonAtomic: {
7026 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00007027 // This does not need to be done in place even for class/array types:
7028 // atomic-to-non-atomic conversion implies copying the object
7029 // representation.
7030 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00007031 return false;
7032 return DerivedSuccess(AtomicVal, E);
7033 }
7034
Richard Smith11562c52011-10-28 17:51:58 +00007035 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00007036 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00007037 return StmtVisitorTy::Visit(E->getSubExpr());
7038
7039 case CK_LValueToRValue: {
7040 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007041 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7042 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007043 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00007044 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00007045 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00007046 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007047 return false;
7048 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00007049 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00007050 case CK_LValueToRValueBitCast: {
7051 APValue DestValue, SourceValue;
7052 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7053 return false;
7054 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7055 return false;
7056 return DerivedSuccess(DestValue, E);
7057 }
Richard Smith11562c52011-10-28 17:51:58 +00007058 }
7059
Richard Smithf57d8cb2011-12-09 22:58:01 +00007060 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007061 }
7062
Aaron Ballman68af21c2014-01-03 19:26:43 +00007063 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00007064 return VisitUnaryPostIncDec(UO);
7065 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007066 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00007067 return VisitUnaryPostIncDec(UO);
7068 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007069 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007070 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007071 return Error(UO);
7072
7073 LValue LVal;
7074 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7075 return false;
7076 APValue RVal;
7077 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7078 UO->isIncrementOp(), &RVal))
7079 return false;
7080 return DerivedSuccess(RVal, UO);
7081 }
7082
Aaron Ballman68af21c2014-01-03 19:26:43 +00007083 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00007084 // We will have checked the full-expressions inside the statement expression
7085 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00007086 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00007087 return Error(E);
7088
7089 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00007090 if (CS->body_empty())
7091 return true;
7092
Richard Smith457226e2019-09-23 03:48:44 +00007093 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00007094 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7095 BE = CS->body_end();
7096 /**/; ++BI) {
7097 if (BI + 1 == BE) {
7098 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7099 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007100 Info.FFDiag((*BI)->getBeginLoc(),
7101 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00007102 return false;
7103 }
Richard Smith457226e2019-09-23 03:48:44 +00007104 return this->Visit(FinalExpr) && Scope.destroy();
Richard Smith51f03172013-06-20 03:00:05 +00007105 }
7106
7107 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00007108 StmtResult Result = { ReturnValue, nullptr };
7109 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00007110 if (ESR != ESR_Succeeded) {
7111 // FIXME: If the statement-expression terminated due to 'return',
7112 // 'break', or 'continue', it would be nice to propagate that to
7113 // the outer statement evaluation rather than bailing out.
7114 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007115 Info.FFDiag((*BI)->getBeginLoc(),
7116 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00007117 return false;
7118 }
7119 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00007120
7121 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00007122 }
7123
Richard Smith4a678122011-10-24 18:44:57 +00007124 /// Visit a value which is evaluated, but whose value is ignored.
7125 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00007126 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00007127 }
David Majnemere9807b22016-02-26 04:23:19 +00007128
7129 /// Potentially visit a MemberExpr's base expression.
7130 void VisitIgnoredBaseExpression(const Expr *E) {
7131 // While MSVC doesn't evaluate the base expression, it does diagnose the
7132 // presence of side-effecting behavior.
7133 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7134 return;
7135 VisitIgnoredValue(E);
7136 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007137};
7138
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007139} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00007140
7141//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007142// Common base class for lvalue and temporary evaluation.
7143//===----------------------------------------------------------------------===//
7144namespace {
7145template<class Derived>
7146class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00007147 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00007148protected:
7149 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007150 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00007151 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00007152 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00007153
7154 bool Success(APValue::LValueBase B) {
7155 Result.set(B);
7156 return true;
7157 }
7158
George Burgess IVf9013bf2017-02-10 22:52:29 +00007159 bool evaluatePointer(const Expr *E, LValue &Result) {
7160 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7161 }
7162
Richard Smith027bf112011-11-17 22:56:20 +00007163public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007164 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7165 : ExprEvaluatorBaseTy(Info), Result(Result),
7166 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00007167
Richard Smith2e312c82012-03-03 22:46:17 +00007168 bool Success(const APValue &V, const Expr *E) {
7169 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00007170 return true;
7171 }
Richard Smith027bf112011-11-17 22:56:20 +00007172
Richard Smith027bf112011-11-17 22:56:20 +00007173 bool VisitMemberExpr(const MemberExpr *E) {
7174 // Handle non-static data members.
7175 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007176 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00007177 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007178 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00007179 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00007180 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007181 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00007182 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00007183 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00007184 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00007185 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00007186 BaseTy = E->getBase()->getType();
7187 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00007188 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007189 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007190 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00007191 Result.setInvalid(E);
7192 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007193 }
Richard Smith027bf112011-11-17 22:56:20 +00007194
Richard Smith1b78b3d2012-01-25 22:15:11 +00007195 const ValueDecl *MD = E->getMemberDecl();
7196 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7197 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7198 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7199 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00007200 if (!HandleLValueMember(this->Info, E, Result, FD))
7201 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00007202 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00007203 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7204 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00007205 } else
7206 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007207
Richard Smith1b78b3d2012-01-25 22:15:11 +00007208 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00007209 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00007210 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00007211 RefValue))
7212 return false;
7213 return Success(RefValue, E);
7214 }
7215 return true;
7216 }
7217
7218 bool VisitBinaryOperator(const BinaryOperator *E) {
7219 switch (E->getOpcode()) {
7220 default:
7221 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7222
7223 case BO_PtrMemD:
7224 case BO_PtrMemI:
7225 return HandleMemberPointerAccess(this->Info, E, Result);
7226 }
7227 }
7228
7229 bool VisitCastExpr(const CastExpr *E) {
7230 switch (E->getCastKind()) {
7231 default:
7232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7233
7234 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007235 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00007236 if (!this->Visit(E->getSubExpr()))
7237 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007238
7239 // Now figure out the necessary offset to add to the base LV to get from
7240 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007241 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7242 Result);
Richard Smith027bf112011-11-17 22:56:20 +00007243 }
7244 }
7245};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007246}
Richard Smith027bf112011-11-17 22:56:20 +00007247
7248//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00007249// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007250//
7251// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7252// function designators (in C), decl references to void objects (in C), and
7253// temporaries (if building with -Wno-address-of-temporary).
7254//
7255// LValue evaluation produces values comprising a base expression of one of the
7256// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00007257// - Declarations
7258// * VarDecl
7259// * FunctionDecl
7260// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00007261// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00007262// * StringLiteral
7263// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00007264// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00007265// * ObjCEncodeExpr
7266// * AddrLabelExpr
7267// * BlockExpr
7268// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00007269// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00007270// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00007271// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00007272// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00007273// was evaluated, for cases where the MaterializeTemporaryExpr is missing
7274// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00007275// * A MaterializeTemporaryExpr that has static storage duration, with no
7276// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00007277// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00007278//===----------------------------------------------------------------------===//
7279namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007280class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00007281 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00007282public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007283 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7284 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00007285
Richard Smith11562c52011-10-28 17:51:58 +00007286 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00007287 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00007288
Peter Collingbournee9200682011-05-13 03:29:01 +00007289 bool VisitDeclRefExpr(const DeclRefExpr *E);
7290 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007291 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007292 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7293 bool VisitMemberExpr(const MemberExpr *E);
7294 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7295 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00007296 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00007297 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007298 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7299 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00007300 bool VisitUnaryReal(const UnaryOperator *E);
7301 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00007302 bool VisitUnaryPreInc(const UnaryOperator *UO) {
7303 return VisitUnaryPreIncDec(UO);
7304 }
7305 bool VisitUnaryPreDec(const UnaryOperator *UO) {
7306 return VisitUnaryPreIncDec(UO);
7307 }
Richard Smith3229b742013-05-05 21:17:10 +00007308 bool VisitBinAssign(const BinaryOperator *BO);
7309 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00007310
Peter Collingbournee9200682011-05-13 03:29:01 +00007311 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00007312 switch (E->getCastKind()) {
7313 default:
Richard Smith027bf112011-11-17 22:56:20 +00007314 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00007315
Eli Friedmance3e02a2011-10-11 00:13:24 +00007316 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00007317 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00007318 if (!Visit(E->getSubExpr()))
7319 return false;
7320 Result.Designator.setInvalid();
7321 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00007322
Richard Smith027bf112011-11-17 22:56:20 +00007323 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00007324 if (!Visit(E->getSubExpr()))
7325 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007326 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00007327
7328 case CK_Dynamic:
7329 if (!Visit(E->getSubExpr()))
7330 return false;
7331 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00007332 }
7333 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007334};
7335} // end anonymous namespace
7336
Richard Smith11562c52011-10-28 17:51:58 +00007337/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00007338/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00007339/// * function designators in C, and
7340/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00007341/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00007342static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7343 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00007344 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00007345 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00007346 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007347}
7348
Peter Collingbournee9200682011-05-13 03:29:01 +00007349bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00007350 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00007351 return Success(FD);
7352 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00007353 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00007354 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00007355 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00007356 return Error(E);
7357}
Richard Smith733237d2011-10-24 23:14:33 +00007358
Faisal Vali0528a312016-11-13 06:09:16 +00007359
Richard Smith11562c52011-10-28 17:51:58 +00007360bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007361
7362 // If we are within a lambda's call operator, check whether the 'VD' referred
7363 // to within 'E' actually represents a lambda-capture that maps to a
7364 // data-member/field within the closure object, and if so, evaluate to the
7365 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00007366 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7367 isa<DeclRefExpr>(E) &&
7368 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7369 // We don't always have a complete capture-map when checking or inferring if
7370 // the function call operator meets the requirements of a constexpr function
7371 // - but we don't need to evaluate the captures to determine constexprness
7372 // (dcl.constexpr C++17).
7373 if (Info.checkingPotentialConstantExpression())
7374 return false;
7375
Faisal Vali051e3a22017-02-16 04:12:21 +00007376 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007377 // Start with 'Result' referring to the complete closure object...
7378 Result = *Info.CurrentCall->This;
7379 // ... then update it to refer to the field of the closure object
7380 // that represents the capture.
7381 if (!HandleLValueMember(Info, E, Result, FD))
7382 return false;
7383 // And if the field is of reference type, update 'Result' to refer to what
7384 // the field refers to.
7385 if (FD->getType()->isReferenceType()) {
7386 APValue RVal;
7387 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7388 RVal))
7389 return false;
7390 Result.setFrom(Info.Ctx, RVal);
7391 }
7392 return true;
7393 }
7394 }
Craig Topper36250ad2014-05-12 05:36:57 +00007395 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00007396 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7397 // Only if a local variable was declared in the function currently being
7398 // evaluated, do we expect to be able to find its value in the current
7399 // frame. (Otherwise it was likely declared in an enclosing context and
7400 // could either have a valid evaluatable value (for e.g. a constexpr
7401 // variable) or be ill-formed (and trigger an appropriate evaluation
7402 // diagnostic)).
7403 if (Info.CurrentCall->Callee &&
7404 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7405 Frame = Info.CurrentCall;
7406 }
7407 }
Richard Smith3229b742013-05-05 21:17:10 +00007408
Richard Smithfec09922011-11-01 16:57:24 +00007409 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00007410 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007411 Result.set({VD, Frame->Index,
7412 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00007413 return true;
7414 }
Richard Smithce40ad62011-11-12 22:28:03 +00007415 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00007416 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00007417
Richard Smith3229b742013-05-05 21:17:10 +00007418 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007419 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007420 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00007421 if (!V->hasValue()) {
7422 // FIXME: Is it possible for V to be indeterminate here? If so, we should
7423 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00007424 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00007425 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007426 return false;
7427 }
Richard Smith3229b742013-05-05 21:17:10 +00007428 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00007429}
7430
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007431bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7432 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007433 // Walk through the expression to find the materialized temporary itself.
7434 SmallVector<const Expr *, 2> CommaLHSs;
7435 SmallVector<SubobjectAdjustment, 2> Adjustments;
7436 const Expr *Inner = E->GetTemporaryExpr()->
7437 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00007438
Richard Smith84401042013-06-03 05:03:02 +00007439 // If we passed any comma operators, evaluate their LHSs.
7440 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7441 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7442 return false;
7443
Richard Smithe6c01442013-06-05 00:46:14 +00007444 // A materialized temporary with static storage duration can appear within the
7445 // result of a constant expression evaluation, so we need to preserve its
7446 // value for use outside this evaluation.
7447 APValue *Value;
7448 if (E->getStorageDuration() == SD_Static) {
7449 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00007450 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00007451 Result.set(E);
7452 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007453 Value = &Info.CurrentCall->createTemporary(
7454 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
Richard Smithe6c01442013-06-05 00:46:14 +00007455 }
7456
Richard Smithea4ad5d2013-06-06 08:19:16 +00007457 QualType Type = Inner->getType();
7458
Richard Smith84401042013-06-03 05:03:02 +00007459 // Materialize the temporary itself.
Richard Smith4566f872019-09-29 05:58:31 +00007460 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
Richard Smithea4ad5d2013-06-06 08:19:16 +00007461 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00007462 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00007463 }
Richard Smith84401042013-06-03 05:03:02 +00007464
7465 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00007466 for (unsigned I = Adjustments.size(); I != 0; /**/) {
7467 --I;
7468 switch (Adjustments[I].Kind) {
7469 case SubobjectAdjustment::DerivedToBaseAdjustment:
7470 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7471 Type, Result))
7472 return false;
7473 Type = Adjustments[I].DerivedToBase.BasePath->getType();
7474 break;
7475
7476 case SubobjectAdjustment::FieldAdjustment:
7477 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7478 return false;
7479 Type = Adjustments[I].Field->getType();
7480 break;
7481
7482 case SubobjectAdjustment::MemberPointerAdjustment:
7483 if (!HandleMemberPointerAccess(this->Info, Type, Result,
7484 Adjustments[I].Ptr.RHS))
7485 return false;
7486 Type = Adjustments[I].Ptr.MPT->getPointeeType();
7487 break;
7488 }
7489 }
7490
7491 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007492}
7493
Peter Collingbournee9200682011-05-13 03:29:01 +00007494bool
7495LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00007496 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7497 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00007498 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7499 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00007500 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007501}
7502
Richard Smith6e525142011-12-27 12:18:28 +00007503bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00007504 TypeInfoLValue TypeInfo;
7505
Richard Smithee0ce3022019-05-17 07:06:46 +00007506 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00007507 if (E->isTypeOperand())
7508 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7509 else
7510 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00007511 } else {
7512 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7513 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7514 << E->getExprOperand()->getType()
7515 << E->getExprOperand()->getSourceRange();
7516 }
7517
7518 if (!Visit(E->getExprOperand()))
7519 return false;
7520
7521 Optional<DynamicType> DynType =
7522 ComputeDynamicType(Info, E, Result, AK_TypeId);
7523 if (!DynType)
7524 return false;
7525
7526 TypeInfo =
7527 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00007528 }
Richard Smith6f3d4352012-10-17 23:52:07 +00007529
Richard Smitha9330302019-05-17 19:19:28 +00007530 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00007531}
7532
Francois Pichet0066db92012-04-16 04:08:35 +00007533bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7534 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00007535}
Francois Pichet0066db92012-04-16 04:08:35 +00007536
Peter Collingbournee9200682011-05-13 03:29:01 +00007537bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007538 // Handle static data members.
7539 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007540 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00007541 return VisitVarDecl(E, VD);
7542 }
7543
Richard Smith254a73d2011-10-28 22:34:42 +00007544 // Handle static member functions.
7545 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7546 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00007547 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00007548 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00007549 }
7550 }
7551
Richard Smithd62306a2011-11-10 06:34:14 +00007552 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00007553 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007554}
7555
Peter Collingbournee9200682011-05-13 03:29:01 +00007556bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007557 // FIXME: Deal with vectors as array subscript bases.
7558 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007559 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007560
Nick Lewyckyad888682017-04-27 07:27:36 +00007561 bool Success = true;
7562 if (!evaluatePointer(E->getBase(), Result)) {
7563 if (!Info.noteFailure())
7564 return false;
7565 Success = false;
7566 }
Mike Stump11289f42009-09-09 15:08:12 +00007567
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007568 APSInt Index;
7569 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00007570 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007571
Nick Lewyckyad888682017-04-27 07:27:36 +00007572 return Success &&
7573 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007574}
Eli Friedman9a156e52008-11-12 09:44:48 +00007575
Peter Collingbournee9200682011-05-13 03:29:01 +00007576bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007577 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00007578}
7579
Richard Smith66c96992012-02-18 22:04:06 +00007580bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7581 if (!Visit(E->getSubExpr()))
7582 return false;
7583 // __real is a no-op on scalar lvalues.
7584 if (E->getSubExpr()->getType()->isAnyComplexType())
7585 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7586 return true;
7587}
7588
7589bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7590 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7591 "lvalue __imag__ on scalar?");
7592 if (!Visit(E->getSubExpr()))
7593 return false;
7594 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7595 return true;
7596}
7597
Richard Smith243ef902013-05-05 23:31:59 +00007598bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007599 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007600 return Error(UO);
7601
7602 if (!this->Visit(UO->getSubExpr()))
7603 return false;
7604
Richard Smith243ef902013-05-05 23:31:59 +00007605 return handleIncDec(
7606 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00007607 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00007608}
7609
7610bool LValueExprEvaluator::VisitCompoundAssignOperator(
7611 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007612 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007613 return Error(CAO);
7614
Richard Smith3229b742013-05-05 21:17:10 +00007615 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00007616
7617 // The overall lvalue result is the result of evaluating the LHS.
7618 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007619 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007620 Evaluate(RHS, this->Info, CAO->getRHS());
7621 return false;
7622 }
7623
Richard Smith3229b742013-05-05 21:17:10 +00007624 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7625 return false;
7626
Richard Smith43e77732013-05-07 04:50:00 +00007627 return handleCompoundAssignment(
7628 this->Info, CAO,
7629 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7630 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00007631}
7632
7633bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007634 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007635 return Error(E);
7636
Richard Smith3229b742013-05-05 21:17:10 +00007637 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00007638
7639 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007640 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007641 Evaluate(NewVal, this->Info, E->getRHS());
7642 return false;
7643 }
7644
Richard Smith3229b742013-05-05 21:17:10 +00007645 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7646 return false;
Richard Smith243ef902013-05-05 23:31:59 +00007647
Richard Smith31c69a32019-05-21 23:15:20 +00007648 if (Info.getLangOpts().CPlusPlus2a &&
7649 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7650 return false;
7651
Richard Smith243ef902013-05-05 23:31:59 +00007652 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00007653 NewVal);
7654}
7655
Eli Friedman9a156e52008-11-12 09:44:48 +00007656//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007657// Pointer Evaluation
7658//===----------------------------------------------------------------------===//
7659
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007660/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00007661/// returned by a function with the alloc_size attribute. Returns true if we
7662/// were successful. Places an unsigned number into `Result`.
7663///
7664/// This expects the given CallExpr to be a call to a function with an
7665/// alloc_size attribute.
7666static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7667 const CallExpr *Call,
7668 llvm::APInt &Result) {
7669 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7670
Joel E. Denny81508102018-03-13 14:51:22 +00007671 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7672 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007673 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7674 if (Call->getNumArgs() <= SizeArgNo)
7675 return false;
7676
7677 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00007678 Expr::EvalResult ExprResult;
7679 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00007680 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007681 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00007682 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7683 return false;
7684 Into = Into.zextOrSelf(BitsInSizeT);
7685 return true;
7686 };
7687
7688 APSInt SizeOfElem;
7689 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7690 return false;
7691
Joel E. Denny81508102018-03-13 14:51:22 +00007692 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007693 Result = std::move(SizeOfElem);
7694 return true;
7695 }
7696
7697 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00007698 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007699 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7700 return false;
7701
7702 bool Overflow;
7703 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7704 if (Overflow)
7705 return false;
7706
7707 Result = std::move(BytesAvailable);
7708 return true;
7709}
7710
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007711/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00007712/// function.
7713static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7714 const LValue &LVal,
7715 llvm::APInt &Result) {
7716 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7717 "Can't get the size of a non alloc_size function");
7718 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7719 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7720 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7721}
7722
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007723/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00007724/// a function with the alloc_size attribute. If it was possible to do so, this
7725/// function will return true, make Result's Base point to said function call,
7726/// and mark Result's Base as invalid.
7727static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7728 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007729 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00007730 return false;
7731
7732 // Because we do no form of static analysis, we only support const variables.
7733 //
7734 // Additionally, we can't support parameters, nor can we support static
7735 // variables (in the latter case, use-before-assign isn't UB; in the former,
7736 // we have no clue what they'll be assigned to).
7737 const auto *VD =
7738 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7739 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7740 return false;
7741
7742 const Expr *Init = VD->getAnyInitializer();
7743 if (!Init)
7744 return false;
7745
7746 const Expr *E = Init->IgnoreParens();
7747 if (!tryUnwrapAllocSizeCall(E))
7748 return false;
7749
7750 // Store E instead of E unwrapped so that the type of the LValue's base is
7751 // what the user wanted.
7752 Result.setInvalid(E);
7753
7754 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007755 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007756 return true;
7757}
7758
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007759namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007760class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007761 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007762 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007763 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007764
Peter Collingbournee9200682011-05-13 03:29:01 +00007765 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007766 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007767 return true;
7768 }
George Burgess IVe3763372016-12-22 02:50:20 +00007769
George Burgess IVf9013bf2017-02-10 22:52:29 +00007770 bool evaluateLValue(const Expr *E, LValue &Result) {
7771 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7772 }
7773
7774 bool evaluatePointer(const Expr *E, LValue &Result) {
7775 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7776 }
7777
George Burgess IVe3763372016-12-22 02:50:20 +00007778 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007779public:
Mike Stump11289f42009-09-09 15:08:12 +00007780
George Burgess IVf9013bf2017-02-10 22:52:29 +00007781 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7782 : ExprEvaluatorBaseTy(info), Result(Result),
7783 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007784
Richard Smith2e312c82012-03-03 22:46:17 +00007785 bool Success(const APValue &V, const Expr *E) {
7786 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007787 return true;
7788 }
Richard Smithfddd3842011-12-30 21:15:51 +00007789 bool ZeroInitialization(const Expr *E) {
Richard Smith19ad5232019-10-03 00:39:33 +00007790 Result.setNull(Info.Ctx, E->getType());
Yaxun Liu402804b2016-12-15 08:09:08 +00007791 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007792 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007793
John McCall45d55e42010-05-07 21:00:08 +00007794 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007795 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007796 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007797 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007798 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007799 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007800 if (E->isExpressibleAsConstantInitializer())
7801 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007802 if (Info.noteFailure())
7803 EvaluateIgnoredValue(Info, E->getSubExpr());
7804 return Error(E);
7805 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007806 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007807 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007808 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007809 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007810 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007811 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007812 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007813 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007814 }
Richard Smithd62306a2011-11-10 06:34:14 +00007815 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007816 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007817 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007818 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007819 if (!Info.CurrentCall->This) {
7820 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007821 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007822 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007823 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007824 return false;
7825 }
Richard Smithd62306a2011-11-10 06:34:14 +00007826 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007827 // If we are inside a lambda's call operator, the 'this' expression refers
7828 // to the enclosing '*this' object (either by value or reference) which is
7829 // either copied into the closure object's field that represents the '*this'
7830 // or refers to '*this'.
7831 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7832 // Update 'Result' to refer to the data member/field of the closure object
7833 // that represents the '*this' capture.
7834 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007835 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007836 return false;
7837 // If we captured '*this' by reference, replace the field with its referent.
7838 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7839 ->isPointerType()) {
7840 APValue RVal;
7841 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7842 RVal))
7843 return false;
7844
7845 Result.setFrom(Info.Ctx, RVal);
7846 }
7847 }
Richard Smithd62306a2011-11-10 06:34:14 +00007848 return true;
7849 }
John McCallc07a0c72011-02-17 10:25:35 +00007850
Richard Smithda1b4342019-09-27 01:26:47 +00007851 bool VisitCXXNewExpr(const CXXNewExpr *E);
7852
Eric Fiselier708afb52019-05-16 21:04:15 +00007853 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7854 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7855 APValue LValResult = E->EvaluateInContext(
7856 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7857 Result.setFrom(Info.Ctx, LValResult);
7858 return true;
7859 }
7860
Eli Friedman449fe542009-03-23 04:56:01 +00007861 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007862};
Chris Lattner05706e882008-07-11 18:11:29 +00007863} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007864
George Burgess IVf9013bf2017-02-10 22:52:29 +00007865static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7866 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007867 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007868 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007869}
7870
John McCall45d55e42010-05-07 21:00:08 +00007871bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007872 if (E->getOpcode() != BO_Add &&
7873 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007874 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007875
Chris Lattner05706e882008-07-11 18:11:29 +00007876 const Expr *PExp = E->getLHS();
7877 const Expr *IExp = E->getRHS();
7878 if (IExp->getType()->isPointerType())
7879 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007880
George Burgess IVf9013bf2017-02-10 22:52:29 +00007881 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007882 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007883 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007884
John McCall45d55e42010-05-07 21:00:08 +00007885 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007886 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007887 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007888
Richard Smith96e0c102011-11-04 02:25:55 +00007889 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007890 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007891
Ted Kremenek28831752012-08-23 20:46:57 +00007892 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007893 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007894}
Eli Friedman9a156e52008-11-12 09:44:48 +00007895
John McCall45d55e42010-05-07 21:00:08 +00007896bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007897 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007898}
Mike Stump11289f42009-09-09 15:08:12 +00007899
Richard Smith81dfef92018-07-11 00:29:05 +00007900bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7901 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007902
Eli Friedman847a2bc2009-12-27 05:43:15 +00007903 switch (E->getCastKind()) {
7904 default:
7905 break;
John McCalle3027922010-08-25 11:45:40 +00007906 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007907 case CK_CPointerToObjCPointerCast:
7908 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007909 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007910 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007911 if (!Visit(SubExpr))
7912 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007913 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7914 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7915 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007916 if (!E->getType()->isVoidPointerType()) {
Richard Smith19ad5232019-10-03 00:39:33 +00007917 if (!Result.InvalidBase && !Result.Designator.Invalid &&
7918 !Result.IsNullPtr &&
7919 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
7920 E->getType()->getPointeeType()) &&
7921 Info.getStdAllocatorCaller("allocate")) {
7922 // Inside a call to std::allocator::allocate and friends, we permit
7923 // casting from void* back to cv1 T* for a pointer that points to a
7924 // cv2 T.
7925 } else {
7926 Result.Designator.setInvalid();
7927 if (SubExpr->getType()->isVoidPointerType())
7928 CCEDiag(E, diag::note_constexpr_invalid_cast)
7929 << 3 << SubExpr->getType();
7930 else
7931 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7932 }
Richard Smithff07af12011-12-12 19:10:03 +00007933 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007934 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7935 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007936 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007937
Anders Carlsson18275092010-10-31 20:41:46 +00007938 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007939 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007940 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007941 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007942 if (!Result.Base && Result.Offset.isZero())
7943 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007944
Richard Smithd62306a2011-11-10 06:34:14 +00007945 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007946 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007947 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7948 castAs<PointerType>()->getPointeeType(),
7949 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007950
Richard Smith027bf112011-11-17 22:56:20 +00007951 case CK_BaseToDerived:
7952 if (!Visit(E->getSubExpr()))
7953 return false;
7954 if (!Result.Base && Result.Offset.isZero())
7955 return true;
7956 return HandleBaseToDerivedCast(Info, E, Result);
7957
Richard Smith7bd54ab2019-05-15 20:22:21 +00007958 case CK_Dynamic:
7959 if (!Visit(E->getSubExpr()))
7960 return false;
7961 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7962
Richard Smith0b0a0b62011-10-29 20:57:55 +00007963 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007964 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007965 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007966
John McCalle3027922010-08-25 11:45:40 +00007967 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007968 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7969
Richard Smith2e312c82012-03-03 22:46:17 +00007970 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007971 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007972 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007973
John McCall45d55e42010-05-07 21:00:08 +00007974 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007975 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7976 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007977 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007978 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007979 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007980 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007981 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007982 return true;
7983 } else {
7984 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007985 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007986 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007987 }
7988 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007989
7990 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007991 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007992 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007993 return false;
7994 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007995 APValue &Value = Info.CurrentCall->createTemporary(
7996 SubExpr, SubExpr->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007997 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007998 return false;
7999 }
Richard Smith96e0c102011-11-04 02:25:55 +00008000 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00008001 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8002 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00008003 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00008004 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00008005 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00008006 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00008007 }
Richard Smithdd785442011-10-31 20:57:44 +00008008
John McCalle3027922010-08-25 11:45:40 +00008009 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00008010 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00008011
8012 case CK_LValueToRValue: {
8013 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00008014 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00008015 return false;
8016
8017 APValue RVal;
8018 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8019 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8020 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00008021 return InvalidBaseOK &&
8022 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00008023 return Success(RVal, E);
8024 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008025 }
8026
Richard Smith11562c52011-10-28 17:51:58 +00008027 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00008028}
Chris Lattner05706e882008-07-11 18:11:29 +00008029
Richard Smith6822bd72018-10-26 19:26:45 +00008030static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8031 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008032 // C++ [expr.alignof]p3:
8033 // When alignof is applied to a reference type, the result is the
8034 // alignment of the referenced type.
8035 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8036 T = Ref->getPointeeType();
8037
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00008038 if (T.getQualifiers().hasUnaligned())
8039 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00008040
8041 const bool AlignOfReturnsPreferred =
8042 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8043
8044 // __alignof is defined to return the preferred alignment.
8045 // Before 8, clang returned the preferred alignment for alignof and _Alignof
8046 // as well.
8047 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8048 return Info.Ctx.toCharUnitsFromBits(
8049 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8050 // alignof and _Alignof are defined to return the ABI alignment.
8051 else if (ExprKind == UETT_AlignOf)
8052 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8053 else
8054 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00008055}
8056
Richard Smith6822bd72018-10-26 19:26:45 +00008057static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8058 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008059 E = E->IgnoreParens();
8060
8061 // The kinds of expressions that we have special-case logic here for
8062 // should be kept up to date with the special checks for those
8063 // expressions in Sema.
8064
8065 // alignof decl is always accepted, even if it doesn't make sense: we default
8066 // to 1 in those cases.
8067 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8068 return Info.Ctx.getDeclAlign(DRE->getDecl(),
8069 /*RefAsPointee*/true);
8070
8071 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8072 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8073 /*RefAsPointee*/true);
8074
Richard Smith6822bd72018-10-26 19:26:45 +00008075 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008076}
8077
George Burgess IVe3763372016-12-22 02:50:20 +00008078// To be clear: this happily visits unsupported builtins. Better name welcomed.
8079bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8080 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8081 return true;
8082
George Burgess IVf9013bf2017-02-10 22:52:29 +00008083 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00008084 return false;
8085
8086 Result.setInvalid(E);
8087 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00008088 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00008089 return true;
8090}
8091
Peter Collingbournee9200682011-05-13 03:29:01 +00008092bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008093 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00008094 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00008095
Richard Smith6328cbd2016-11-16 00:57:23 +00008096 if (unsigned BuiltinOp = E->getBuiltinCallee())
8097 return VisitBuiltinCallExpr(E, BuiltinOp);
8098
George Burgess IVe3763372016-12-22 02:50:20 +00008099 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008100}
8101
8102bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8103 unsigned BuiltinOp) {
8104 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00008105 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00008106 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008107 case Builtin::BI__builtin_assume_aligned: {
8108 // We need to be very careful here because: if the pointer does not have the
8109 // asserted alignment, then the behavior is undefined, and undefined
8110 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00008111 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00008112 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00008113
Hal Finkel0dd05d42014-10-03 17:18:37 +00008114 LValue OffsetResult(Result);
8115 APSInt Alignment;
8116 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
8117 return false;
Richard Smith642a2362017-01-30 23:30:26 +00008118 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00008119
8120 if (E->getNumArgs() > 2) {
8121 APSInt Offset;
8122 if (!EvaluateInteger(E->getArg(2), Offset, Info))
8123 return false;
8124
Richard Smith642a2362017-01-30 23:30:26 +00008125 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008126 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8127 }
8128
8129 // If there is a base object, then it must have the correct alignment.
8130 if (OffsetResult.Base) {
8131 CharUnits BaseAlignment;
8132 if (const ValueDecl *VD =
8133 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
8134 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00008135 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
8136 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008137 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00008138 BaseAlignment = GetAlignOfType(
8139 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008140 }
8141
8142 if (BaseAlignment < Align) {
8143 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00008144 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00008145 CCEDiag(E->getArg(0),
8146 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00008147 << (unsigned)BaseAlignment.getQuantity()
8148 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008149 return false;
8150 }
8151 }
8152
8153 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008154 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008155 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008156
Richard Smith642a2362017-01-30 23:30:26 +00008157 (OffsetResult.Base
8158 ? CCEDiag(E->getArg(0),
8159 diag::note_constexpr_baa_insufficient_alignment) << 1
8160 : CCEDiag(E->getArg(0),
8161 diag::note_constexpr_baa_value_insufficient_alignment))
8162 << (int)OffsetResult.Offset.getQuantity()
8163 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008164 return false;
8165 }
8166
8167 return true;
8168 }
Richard Smith19ad5232019-10-03 00:39:33 +00008169 case Builtin::BI__builtin_operator_new:
8170 return HandleOperatorNewCall(Info, E, Result);
Eric Fiselier26187502018-12-14 21:11:28 +00008171 case Builtin::BI__builtin_launder:
8172 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00008173 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008174 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00008175 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008176 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00008177 if (Info.getLangOpts().CPlusPlus11)
8178 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8179 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008180 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00008181 else
8182 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008183 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00008184 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008185 case Builtin::BI__builtin_wcschr:
8186 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00008187 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008188 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00008189 if (!Visit(E->getArg(0)))
8190 return false;
8191 APSInt Desired;
8192 if (!EvaluateInteger(E->getArg(1), Desired, Info))
8193 return false;
8194 uint64_t MaxLength = uint64_t(-1);
8195 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008196 BuiltinOp != Builtin::BIwcschr &&
8197 BuiltinOp != Builtin::BI__builtin_strchr &&
8198 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00008199 APSInt N;
8200 if (!EvaluateInteger(E->getArg(2), N, Info))
8201 return false;
8202 MaxLength = N.getExtValue();
8203 }
Hubert Tong147b7432018-12-12 16:53:43 +00008204 // We cannot find the value if there are no candidates to match against.
8205 if (MaxLength == 0u)
8206 return ZeroInitialization(E);
8207 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8208 Result.Designator.Invalid)
8209 return false;
8210 QualType CharTy = Result.Designator.getType(Info.Ctx);
8211 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8212 BuiltinOp == Builtin::BI__builtin_memchr;
8213 assert(IsRawByte ||
8214 Info.Ctx.hasSameUnqualifiedType(
8215 CharTy, E->getArg(0)->getType()->getPointeeType()));
8216 // Pointers to const void may point to objects of incomplete type.
8217 if (IsRawByte && CharTy->isIncompleteType()) {
8218 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8219 return false;
8220 }
8221 // Give up on byte-oriented matching against multibyte elements.
8222 // FIXME: We can compare the bytes in the correct order.
8223 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8224 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008225 // Figure out what value we're actually looking for (after converting to
8226 // the corresponding unsigned type if necessary).
8227 uint64_t DesiredVal;
8228 bool StopAtNull = false;
8229 switch (BuiltinOp) {
8230 case Builtin::BIstrchr:
8231 case Builtin::BI__builtin_strchr:
8232 // strchr compares directly to the passed integer, and therefore
8233 // always fails if given an int that is not a char.
8234 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8235 E->getArg(1)->getType(),
8236 Desired),
8237 Desired))
8238 return ZeroInitialization(E);
8239 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008240 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008241 case Builtin::BImemchr:
8242 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00008243 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008244 // memchr compares by converting both sides to unsigned char. That's also
8245 // correct for strchr if we get this far (to cope with plain char being
8246 // unsigned in the strchr case).
8247 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8248 break;
Richard Smithe9507952016-11-12 01:39:56 +00008249
Richard Smith8110c9d2016-11-29 19:45:17 +00008250 case Builtin::BIwcschr:
8251 case Builtin::BI__builtin_wcschr:
8252 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008253 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008254 case Builtin::BIwmemchr:
8255 case Builtin::BI__builtin_wmemchr:
8256 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8257 DesiredVal = Desired.getZExtValue();
8258 break;
8259 }
Richard Smithe9507952016-11-12 01:39:56 +00008260
8261 for (; MaxLength; --MaxLength) {
8262 APValue Char;
8263 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8264 !Char.isInt())
8265 return false;
8266 if (Char.getInt().getZExtValue() == DesiredVal)
8267 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00008268 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00008269 break;
8270 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8271 return false;
8272 }
8273 // Not found: return nullptr.
8274 return ZeroInitialization(E);
8275 }
8276
Richard Smith06f71b52018-08-04 00:57:17 +00008277 case Builtin::BImemcpy:
8278 case Builtin::BImemmove:
8279 case Builtin::BIwmemcpy:
8280 case Builtin::BIwmemmove:
8281 if (Info.getLangOpts().CPlusPlus11)
8282 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8283 << /*isConstexpr*/0 << /*isConstructor*/0
8284 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8285 else
8286 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8287 LLVM_FALLTHROUGH;
8288 case Builtin::BI__builtin_memcpy:
8289 case Builtin::BI__builtin_memmove:
8290 case Builtin::BI__builtin_wmemcpy:
8291 case Builtin::BI__builtin_wmemmove: {
8292 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8293 BuiltinOp == Builtin::BIwmemmove ||
8294 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8295 BuiltinOp == Builtin::BI__builtin_wmemmove;
8296 bool Move = BuiltinOp == Builtin::BImemmove ||
8297 BuiltinOp == Builtin::BIwmemmove ||
8298 BuiltinOp == Builtin::BI__builtin_memmove ||
8299 BuiltinOp == Builtin::BI__builtin_wmemmove;
8300
8301 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00008302 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00008303 return false;
8304 LValue Dest = Result;
8305
8306 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00008307 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00008308 return false;
8309
8310 APSInt N;
8311 if (!EvaluateInteger(E->getArg(2), N, Info))
8312 return false;
8313 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8314
8315 // If the size is zero, we treat this as always being a valid no-op.
8316 // (Even if one of the src and dest pointers is null.)
8317 if (!N)
8318 return true;
8319
Richard Smith128719c2018-09-13 22:47:33 +00008320 // Otherwise, if either of the operands is null, we can't proceed. Don't
8321 // try to determine the type of the copied objects, because there aren't
8322 // any.
8323 if (!Src.Base || !Dest.Base) {
8324 APValue Val;
8325 (!Src.Base ? Src : Dest).moveInto(Val);
8326 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8327 << Move << WChar << !!Src.Base
8328 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8329 return false;
8330 }
8331 if (Src.Designator.Invalid || Dest.Designator.Invalid)
8332 return false;
8333
Richard Smith06f71b52018-08-04 00:57:17 +00008334 // We require that Src and Dest are both pointers to arrays of
8335 // trivially-copyable type. (For the wide version, the designator will be
8336 // invalid if the designated object is not a wchar_t.)
8337 QualType T = Dest.Designator.getType(Info.Ctx);
8338 QualType SrcT = Src.Designator.getType(Info.Ctx);
8339 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8340 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8341 return false;
8342 }
Petr Pavlued083f22018-10-04 09:25:44 +00008343 if (T->isIncompleteType()) {
8344 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8345 return false;
8346 }
Richard Smith06f71b52018-08-04 00:57:17 +00008347 if (!T.isTriviallyCopyableType(Info.Ctx)) {
8348 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8349 return false;
8350 }
8351
8352 // Figure out how many T's we're copying.
8353 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8354 if (!WChar) {
8355 uint64_t Remainder;
8356 llvm::APInt OrigN = N;
8357 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8358 if (Remainder) {
8359 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8360 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8361 << (unsigned)TSize;
8362 return false;
8363 }
8364 }
8365
8366 // Check that the copying will remain within the arrays, just so that we
8367 // can give a more meaningful diagnostic. This implicitly also checks that
8368 // N fits into 64 bits.
8369 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8370 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8371 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8372 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8373 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8374 << N.toString(10, /*Signed*/false);
8375 return false;
8376 }
8377 uint64_t NElems = N.getZExtValue();
8378 uint64_t NBytes = NElems * TSize;
8379
8380 // Check for overlap.
8381 int Direction = 1;
8382 if (HasSameBase(Src, Dest)) {
8383 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8384 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8385 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8386 // Dest is inside the source region.
8387 if (!Move) {
8388 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8389 return false;
8390 }
8391 // For memmove and friends, copy backwards.
8392 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8393 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8394 return false;
8395 Direction = -1;
8396 } else if (!Move && SrcOffset >= DestOffset &&
8397 SrcOffset - DestOffset < NBytes) {
8398 // Src is inside the destination region for memcpy: invalid.
8399 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8400 return false;
8401 }
8402 }
8403
8404 while (true) {
8405 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00008406 // FIXME: Set WantObjectRepresentation to true if we're copying a
8407 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00008408 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8409 !handleAssignment(Info, E, Dest, T, Val))
8410 return false;
8411 // Do not iterate past the last element; if we're copying backwards, that
8412 // might take us off the start of the array.
8413 if (--NElems == 0)
8414 return true;
8415 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8416 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8417 return false;
8418 }
8419 }
8420
Richard Smith6cbd65d2013-07-11 02:27:57 +00008421 default:
Richard Smith19ad5232019-10-03 00:39:33 +00008422 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00008423 }
Richard Smith19ad5232019-10-03 00:39:33 +00008424
8425 return visitNonBuiltinCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008426}
Chris Lattner05706e882008-07-11 18:11:29 +00008427
Richard Smithda1b4342019-09-27 01:26:47 +00008428static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8429 APValue &Result, const InitListExpr *ILE,
8430 QualType AllocType);
8431
8432bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
Richard Smith62a95562019-09-27 01:26:49 +00008433 if (!Info.getLangOpts().CPlusPlus2a)
8434 Info.CCEDiag(E, diag::note_constexpr_new);
8435
Richard Smithda1b4342019-09-27 01:26:47 +00008436 // We cannot speculatively evaluate a delete expression.
8437 if (Info.SpeculativeEvaluationDepth)
8438 return false;
8439
8440 FunctionDecl *OperatorNew = E->getOperatorNew();
8441 if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8442 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8443 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8444 return false;
8445 }
8446
Richard Smith62a95562019-09-27 01:26:49 +00008447 bool IsNothrow = false;
8448 if (E->getNumPlacementArgs()) {
8449 // The only new-placement list we support is of the form (std::nothrow).
8450 //
8451 // FIXME: There is no restriction on this, but it's not clear that any
8452 // other form makes any sense. We get here for cases such as:
8453 //
8454 // new (std::align_val_t{N}) X(int)
8455 //
8456 // (which should presumably be valid only if N is a multiple of
8457 // alignof(int), and in any case can't be deallocated unless N is
8458 // alignof(X) and X has new-extended alignment).
8459 if (E->getNumPlacementArgs() != 1 ||
8460 !E->getPlacementArg(0)->getType()->isNothrowT())
8461 return Error(E, diag::note_constexpr_new_placement);
8462
8463 LValue Nothrow;
8464 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8465 return false;
8466 IsNothrow = true;
8467 }
Richard Smithda1b4342019-09-27 01:26:47 +00008468
8469 const Expr *Init = E->getInitializer();
8470 const InitListExpr *ResizedArrayILE = nullptr;
8471
8472 QualType AllocType = E->getAllocatedType();
8473 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8474 const Expr *Stripped = *ArraySize;
8475 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8476 Stripped = ICE->getSubExpr())
8477 if (ICE->getCastKind() != CK_NoOp &&
8478 ICE->getCastKind() != CK_IntegralCast)
8479 break;
8480
8481 llvm::APSInt ArrayBound;
8482 if (!EvaluateInteger(Stripped, ArrayBound, Info))
8483 return false;
8484
8485 // C++ [expr.new]p9:
8486 // The expression is erroneous if:
8487 // -- [...] its value before converting to size_t [or] applying the
8488 // second standard conversion sequence is less than zero
8489 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
Richard Smith62a95562019-09-27 01:26:49 +00008490 if (IsNothrow)
8491 return ZeroInitialization(E);
8492
Richard Smithda1b4342019-09-27 01:26:47 +00008493 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8494 << ArrayBound << (*ArraySize)->getSourceRange();
8495 return false;
8496 }
8497
8498 // -- its value is such that the size of the allocated object would
8499 // exceed the implementation-defined limit
8500 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8501 ArrayBound) >
8502 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
Richard Smith62a95562019-09-27 01:26:49 +00008503 if (IsNothrow)
8504 return ZeroInitialization(E);
8505
Richard Smithda1b4342019-09-27 01:26:47 +00008506 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8507 << ArrayBound << (*ArraySize)->getSourceRange();
8508 return false;
8509 }
8510
8511 // -- the new-initializer is a braced-init-list and the number of
8512 // array elements for which initializers are provided [...]
8513 // exceeds the number of elements to initialize
8514 if (Init) {
8515 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8516 assert(CAT && "unexpected type for array initializer");
8517
8518 unsigned Bits =
8519 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8520 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8521 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8522 if (InitBound.ugt(AllocBound)) {
Richard Smith62a95562019-09-27 01:26:49 +00008523 if (IsNothrow)
8524 return ZeroInitialization(E);
8525
Richard Smithda1b4342019-09-27 01:26:47 +00008526 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8527 << AllocBound.toString(10, /*Signed=*/false)
8528 << InitBound.toString(10, /*Signed=*/false)
8529 << (*ArraySize)->getSourceRange();
8530 return false;
8531 }
8532
8533 // If the sizes differ, we must have an initializer list, and we need
8534 // special handling for this case when we initialize.
8535 if (InitBound != AllocBound)
8536 ResizedArrayILE = cast<InitListExpr>(Init);
8537 }
8538
8539 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound,
8540 ArrayType::Normal, 0);
8541 } else {
8542 assert(!AllocType->isArrayType() &&
8543 "array allocation with non-array new");
8544 }
8545
8546 // Perform the allocation and obtain a pointer to the resulting object.
8547 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
8548 if (!Val)
8549 return false;
8550
8551 if (ResizedArrayILE) {
8552 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8553 AllocType))
8554 return false;
8555 } else if (Init) {
8556 if (!EvaluateInPlace(*Val, Info, Result, Init))
8557 return false;
8558 } else {
8559 *Val = getDefaultInitValue(AllocType);
8560 }
8561
8562 // Array new returns a pointer to the first element, not a pointer to the
8563 // array.
8564 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8565 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8566
8567 return true;
8568}
Chris Lattner05706e882008-07-11 18:11:29 +00008569//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008570// Member Pointer Evaluation
8571//===----------------------------------------------------------------------===//
8572
8573namespace {
8574class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008575 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00008576 MemberPtr &Result;
8577
8578 bool Success(const ValueDecl *D) {
8579 Result = MemberPtr(D);
8580 return true;
8581 }
8582public:
8583
8584 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8585 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8586
Richard Smith2e312c82012-03-03 22:46:17 +00008587 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008588 Result.setFrom(V);
8589 return true;
8590 }
Richard Smithfddd3842011-12-30 21:15:51 +00008591 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00008592 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00008593 }
8594
8595 bool VisitCastExpr(const CastExpr *E);
8596 bool VisitUnaryAddrOf(const UnaryOperator *E);
8597};
8598} // end anonymous namespace
8599
8600static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8601 EvalInfo &Info) {
8602 assert(E->isRValue() && E->getType()->isMemberPointerType());
8603 return MemberPointerExprEvaluator(Info, Result).Visit(E);
8604}
8605
8606bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8607 switch (E->getCastKind()) {
8608 default:
8609 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8610
8611 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00008612 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008613 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00008614
8615 case CK_BaseToDerivedMemberPointer: {
8616 if (!Visit(E->getSubExpr()))
8617 return false;
8618 if (E->path_empty())
8619 return true;
8620 // Base-to-derived member pointer casts store the path in derived-to-base
8621 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8622 // the wrong end of the derived->base arc, so stagger the path by one class.
8623 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8624 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8625 PathI != PathE; ++PathI) {
8626 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8627 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8628 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008629 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008630 }
8631 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8632 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008633 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008634 return true;
8635 }
8636
8637 case CK_DerivedToBaseMemberPointer:
8638 if (!Visit(E->getSubExpr()))
8639 return false;
8640 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8641 PathE = E->path_end(); PathI != PathE; ++PathI) {
8642 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8643 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8644 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008645 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008646 }
8647 return true;
8648 }
8649}
8650
8651bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8652 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8653 // member can be formed.
8654 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8655}
8656
8657//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00008658// Record Evaluation
8659//===----------------------------------------------------------------------===//
8660
8661namespace {
8662 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008663 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008664 const LValue &This;
8665 APValue &Result;
8666 public:
8667
8668 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8669 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8670
Richard Smith2e312c82012-03-03 22:46:17 +00008671 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00008672 Result = V;
8673 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00008674 }
Richard Smithb8348f52016-05-12 22:16:28 +00008675 bool ZeroInitialization(const Expr *E) {
8676 return ZeroInitialization(E, E->getType());
8677 }
8678 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00008679
Richard Smith52a980a2015-08-28 02:43:42 +00008680 bool VisitCallExpr(const CallExpr *E) {
8681 return handleCallExpr(E, Result, &This);
8682 }
Richard Smithe97cbd72011-11-11 04:05:33 +00008683 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008684 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008685 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8686 return VisitCXXConstructExpr(E, E->getType());
8687 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008688 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00008689 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008690 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00008691 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008692 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008693 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008694}
Richard Smithd62306a2011-11-10 06:34:14 +00008695
Richard Smithfddd3842011-12-30 21:15:51 +00008696/// Perform zero-initialization on an object of non-union class type.
8697/// C++11 [dcl.init]p5:
8698/// To zero-initialize an object or reference of type T means:
8699/// [...]
8700/// -- if T is a (possibly cv-qualified) non-union class type,
8701/// each non-static data member and each base-class subobject is
8702/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00008703static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8704 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00008705 const LValue &This, APValue &Result) {
8706 assert(!RD->isUnion() && "Expected non-union class type");
8707 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8708 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00008709 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00008710
John McCalld7bca762012-05-01 00:38:49 +00008711 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008712 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8713
8714 if (CD) {
8715 unsigned Index = 0;
8716 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00008717 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00008718 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8719 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008720 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8721 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00008722 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00008723 Result.getStructBase(Index)))
8724 return false;
8725 }
8726 }
8727
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008728 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00008729 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00008730 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00008731 continue;
8732
8733 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008734 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008735 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008736
David Blaikie2d7c57e2012-04-30 02:36:29 +00008737 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008738 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00008739 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00008740 return false;
8741 }
8742
8743 return true;
8744}
8745
Richard Smithb8348f52016-05-12 22:16:28 +00008746bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8747 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008748 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008749 if (RD->isUnion()) {
8750 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8751 // object's first non-static named data member is zero-initialized
8752 RecordDecl::field_iterator I = RD->field_begin();
8753 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00008754 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00008755 return true;
8756 }
8757
8758 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00008759 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00008760 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00008761 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00008762 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008763 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00008764 }
8765
Richard Smith5d108602012-02-17 00:44:16 +00008766 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008767 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00008768 return false;
8769 }
8770
Richard Smitha8105bc2012-01-06 16:39:00 +00008771 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00008772}
8773
Richard Smithe97cbd72011-11-11 04:05:33 +00008774bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8775 switch (E->getCastKind()) {
8776 default:
8777 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8778
8779 case CK_ConstructorConversion:
8780 return Visit(E->getSubExpr());
8781
8782 case CK_DerivedToBase:
8783 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00008784 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008785 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00008786 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008787 if (!DerivedObject.isStruct())
8788 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00008789
8790 // Derived-to-base rvalue conversion: just slice off the derived part.
8791 APValue *Value = &DerivedObject;
8792 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8793 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8794 PathE = E->path_end(); PathI != PathE; ++PathI) {
8795 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
8796 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8797 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8798 RD = Base;
8799 }
8800 Result = *Value;
8801 return true;
8802 }
8803 }
8804}
8805
Richard Smithd62306a2011-11-10 06:34:14 +00008806bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00008807 if (E->isTransparent())
8808 return Visit(E->getInit(0));
8809
Richard Smithd62306a2011-11-10 06:34:14 +00008810 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008811 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008812 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008813 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8814
8815 EvalInfo::EvaluatingConstructorRAII EvalObj(
8816 Info,
8817 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8818 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00008819
8820 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00008821 const FieldDecl *Field = E->getInitializedFieldInUnion();
8822 Result = APValue(Field);
8823 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00008824 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00008825
8826 // If the initializer list for a union does not contain any elements, the
8827 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00008828 // FIXME: The element should be initialized from an initializer list.
8829 // Is this difference ever observable for initializer lists which
8830 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00008831 ImplicitValueInitExpr VIE(Field->getType());
8832 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8833
Richard Smithd62306a2011-11-10 06:34:14 +00008834 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008835 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8836 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00008837
8838 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8839 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8840 isa<CXXDefaultInitExpr>(InitExpr));
8841
Richard Smithb228a862012-02-15 02:18:13 +00008842 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00008843 }
8844
Richard Smithe637cbe2019-05-21 23:15:18 +00008845 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00008846 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8847 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00008848 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00008849 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00008850
8851 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008852 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00008853 for (const auto &Base : CXXRD->bases()) {
8854 assert(ElementNo < E->getNumInits() && "missing init for base class");
8855 const Expr *Init = E->getInit(ElementNo);
8856
8857 LValue Subobject = This;
8858 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8859 return false;
8860
8861 APValue &FieldVal = Result.getStructBase(ElementNo);
8862 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008863 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00008864 return false;
8865 Success = false;
8866 }
8867 ++ElementNo;
8868 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008869
8870 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00008871 }
8872
8873 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008874 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008875 // Anonymous bit-fields are not considered members of the class for
8876 // purposes of aggregate initialization.
8877 if (Field->isUnnamedBitfield())
8878 continue;
8879
8880 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00008881
Richard Smith253c2a32012-01-27 01:14:48 +00008882 bool HaveInit = ElementNo < E->getNumInits();
8883
8884 // FIXME: Diagnostics here should point to the end of the initializer
8885 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00008886 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008887 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008888 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008889
8890 // Perform an implicit value-initialization for members beyond the end of
8891 // the initializer list.
8892 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00008893 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00008894
Richard Smith852c9db2013-04-20 22:23:05 +00008895 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8896 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8897 isa<CXXDefaultInitExpr>(Init));
8898
Richard Smith49ca8aa2013-08-06 07:09:20 +00008899 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8900 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8901 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008902 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00008903 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00008904 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008905 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00008906 }
8907 }
8908
Richard Smith253c2a32012-01-27 01:14:48 +00008909 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00008910}
8911
Richard Smithb8348f52016-05-12 22:16:28 +00008912bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8913 QualType T) {
8914 // Note that E's type is not necessarily the type of our class here; we might
8915 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00008916 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00008917 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8918
Richard Smithfddd3842011-12-30 21:15:51 +00008919 bool ZeroInit = E->requiresZeroInitialization();
8920 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00008921 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00008922 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00008923 return true;
8924
Richard Smithc667cdc2019-09-18 17:37:44 +00008925 if (ZeroInit)
8926 return ZeroInitialization(E, T);
8927
8928 Result = getDefaultInitValue(T);
8929 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00008930 }
8931
Craig Topper36250ad2014-05-12 05:36:57 +00008932 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008933 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00008934
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008935 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00008936 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008937
Richard Smith1bc5c2c2012-01-10 04:32:03 +00008938 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00008939 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00008940 if (const MaterializeTemporaryExpr *ME
8941 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8942 return Visit(ME->GetTemporaryExpr());
8943
Richard Smithb8348f52016-05-12 22:16:28 +00008944 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00008945 return false;
8946
Craig Topper5fc8fc22014-08-27 06:28:36 +00008947 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00008948 return HandleConstructorCall(E, This, Args,
8949 cast<CXXConstructorDecl>(Definition), Info,
8950 Result);
8951}
8952
8953bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8954 const CXXInheritedCtorInitExpr *E) {
8955 if (!Info.CurrentCall) {
8956 assert(Info.checkingPotentialConstantExpression());
8957 return false;
8958 }
8959
8960 const CXXConstructorDecl *FD = E->getConstructor();
8961 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8962 return false;
8963
8964 const FunctionDecl *Definition = nullptr;
8965 auto Body = FD->getBody(Definition);
8966
8967 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8968 return false;
8969
8970 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008971 cast<CXXConstructorDecl>(Definition), Info,
8972 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00008973}
8974
Richard Smithcc1b96d2013-06-12 22:31:48 +00008975bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8976 const CXXStdInitializerListExpr *E) {
8977 const ConstantArrayType *ArrayType =
8978 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8979
8980 LValue Array;
8981 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8982 return false;
8983
8984 // Get a pointer to the first element of the array.
8985 Array.addArray(Info, E, ArrayType);
8986
8987 // FIXME: Perform the checks on the field types in SemaInit.
8988 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8989 RecordDecl::field_iterator Field = Record->field_begin();
8990 if (Field == Record->field_end())
8991 return Error(E);
8992
8993 // Start pointer.
8994 if (!Field->getType()->isPointerType() ||
8995 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8996 ArrayType->getElementType()))
8997 return Error(E);
8998
8999 // FIXME: What if the initializer_list type has base classes, etc?
9000 Result = APValue(APValue::UninitStruct(), 0, 2);
9001 Array.moveInto(Result.getStructField(0));
9002
9003 if (++Field == Record->field_end())
9004 return Error(E);
9005
9006 if (Field->getType()->isPointerType() &&
9007 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9008 ArrayType->getElementType())) {
9009 // End pointer.
9010 if (!HandleLValueArrayAdjustment(Info, E, Array,
9011 ArrayType->getElementType(),
9012 ArrayType->getSize().getZExtValue()))
9013 return false;
9014 Array.moveInto(Result.getStructField(1));
9015 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9016 // Length.
9017 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9018 else
9019 return Error(E);
9020
9021 if (++Field != Record->field_end())
9022 return Error(E);
9023
9024 return true;
9025}
9026
Faisal Valic72a08c2017-01-09 03:02:53 +00009027bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9028 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
Richard Smithda1b4342019-09-27 01:26:47 +00009029 if (ClosureClass->isInvalidDecl())
9030 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009031
Faisal Vali051e3a22017-02-16 04:12:21 +00009032 const size_t NumFields =
9033 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00009034
9035 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9036 E->capture_init_end()) &&
9037 "The number of lambda capture initializers should equal the number of "
9038 "fields within the closure type");
9039
Faisal Vali051e3a22017-02-16 04:12:21 +00009040 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9041 // Iterate through all the lambda's closure object's fields and initialize
9042 // them.
9043 auto *CaptureInitIt = E->capture_init_begin();
9044 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9045 bool Success = true;
9046 for (const auto *Field : ClosureClass->fields()) {
9047 assert(CaptureInitIt != E->capture_init_end());
9048 // Get the initializer for this field
9049 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00009050
Faisal Vali051e3a22017-02-16 04:12:21 +00009051 // If there is no initializer, either this is a VLA or an error has
9052 // occurred.
9053 if (!CurFieldInit)
9054 return Error(E);
9055
9056 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9057 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9058 if (!Info.keepEvaluatingAfterFailure())
9059 return false;
9060 Success = false;
9061 }
9062 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00009063 }
Faisal Vali051e3a22017-02-16 04:12:21 +00009064 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00009065}
9066
Richard Smithd62306a2011-11-10 06:34:14 +00009067static bool EvaluateRecord(const Expr *E, const LValue &This,
9068 APValue &Result, EvalInfo &Info) {
9069 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00009070 "can't evaluate expression as a record rvalue");
9071 return RecordExprEvaluator(Info, This, Result).Visit(E);
9072}
9073
9074//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00009075// Temporary Evaluation
9076//
9077// Temporaries are represented in the AST as rvalues, but generally behave like
9078// lvalues. The full-object of which the temporary is a subobject is implicitly
9079// materialized so that a reference can bind to it.
9080//===----------------------------------------------------------------------===//
9081namespace {
9082class TemporaryExprEvaluator
9083 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9084public:
9085 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00009086 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00009087
9088 /// Visit an expression which constructs the value of this temporary.
9089 bool VisitConstructExpr(const Expr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009090 APValue &Value =
9091 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00009092 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00009093 }
9094
9095 bool VisitCastExpr(const CastExpr *E) {
9096 switch (E->getCastKind()) {
9097 default:
9098 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9099
9100 case CK_ConstructorConversion:
9101 return VisitConstructExpr(E->getSubExpr());
9102 }
9103 }
9104 bool VisitInitListExpr(const InitListExpr *E) {
9105 return VisitConstructExpr(E);
9106 }
9107 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9108 return VisitConstructExpr(E);
9109 }
9110 bool VisitCallExpr(const CallExpr *E) {
9111 return VisitConstructExpr(E);
9112 }
Richard Smith513955c2014-12-17 19:24:30 +00009113 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9114 return VisitConstructExpr(E);
9115 }
Faisal Valic72a08c2017-01-09 03:02:53 +00009116 bool VisitLambdaExpr(const LambdaExpr *E) {
9117 return VisitConstructExpr(E);
9118 }
Richard Smith027bf112011-11-17 22:56:20 +00009119};
9120} // end anonymous namespace
9121
9122/// Evaluate an expression of record type as a temporary.
9123static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00009124 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00009125 return TemporaryExprEvaluator(Info, Result).Visit(E);
9126}
9127
9128//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009129// Vector Evaluation
9130//===----------------------------------------------------------------------===//
9131
9132namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009133 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009134 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00009135 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009136 public:
Mike Stump11289f42009-09-09 15:08:12 +00009137
Richard Smith2d406342011-10-22 21:10:00 +00009138 VectorExprEvaluator(EvalInfo &info, APValue &Result)
9139 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00009140
Craig Topper9798b932015-09-29 04:30:05 +00009141 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009142 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9143 // FIXME: remove this APValue copy.
9144 Result = APValue(V.data(), V.size());
9145 return true;
9146 }
Richard Smith2e312c82012-03-03 22:46:17 +00009147 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00009148 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00009149 Result = V;
9150 return true;
9151 }
Richard Smithfddd3842011-12-30 21:15:51 +00009152 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00009153
Richard Smith2d406342011-10-22 21:10:00 +00009154 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00009155 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00009156 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00009157 bool VisitInitListExpr(const InitListExpr *E);
9158 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009159 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00009160 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00009161 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009162 };
9163} // end anonymous namespace
9164
9165static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009166 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00009167 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009168}
9169
George Burgess IV533ff002015-12-11 00:23:35 +00009170bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009171 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00009172 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00009173
Richard Smith161f09a2011-12-06 22:44:34 +00009174 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00009175 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009176
Eli Friedmanc757de22011-03-25 00:43:55 +00009177 switch (E->getCastKind()) {
9178 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00009179 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00009180 if (SETy->isIntegerType()) {
9181 APSInt IntResult;
9182 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00009183 return false;
9184 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00009185 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00009186 APFloat FloatResult(0.0);
9187 if (!EvaluateFloat(SE, FloatResult, Info))
9188 return false;
9189 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00009190 } else {
Richard Smith2d406342011-10-22 21:10:00 +00009191 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009192 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00009193
9194 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00009195 SmallVector<APValue, 4> Elts(NElts, Val);
9196 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00009197 }
Eli Friedman803acb32011-12-22 03:51:45 +00009198 case CK_BitCast: {
9199 // Evaluate the operand into an APInt we can extract from.
9200 llvm::APInt SValInt;
9201 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9202 return false;
9203 // Extract the elements
9204 QualType EltTy = VTy->getElementType();
9205 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9206 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9207 SmallVector<APValue, 4> Elts;
9208 if (EltTy->isRealFloatingType()) {
9209 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00009210 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00009211 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00009212 FloatEltSize = 80;
9213 for (unsigned i = 0; i < NElts; i++) {
9214 llvm::APInt Elt;
9215 if (BigEndian)
9216 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9217 else
9218 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00009219 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00009220 }
9221 } else if (EltTy->isIntegerType()) {
9222 for (unsigned i = 0; i < NElts; i++) {
9223 llvm::APInt Elt;
9224 if (BigEndian)
9225 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9226 else
9227 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9228 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9229 }
9230 } else {
9231 return Error(E);
9232 }
9233 return Success(Elts, E);
9234 }
Eli Friedmanc757de22011-03-25 00:43:55 +00009235 default:
Richard Smith11562c52011-10-28 17:51:58 +00009236 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009237 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009238}
9239
Richard Smith2d406342011-10-22 21:10:00 +00009240bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009241VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009242 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009243 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00009244 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00009245
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009246 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009247 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009248
Eli Friedmanb9c71292012-01-03 23:24:20 +00009249 // The number of initializers can be less than the number of
9250 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00009251 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00009252 // should be initialized with zeroes.
9253 unsigned CountInits = 0, CountElts = 0;
9254 while (CountElts < NumElements) {
9255 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00009256 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00009257 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00009258 APValue v;
9259 if (!EvaluateVector(E->getInit(CountInits), v, Info))
9260 return Error(E);
9261 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00009262 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00009263 Elements.push_back(v.getVectorElt(j));
9264 CountElts += vlen;
9265 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009266 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009267 if (CountInits < NumInits) {
9268 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009269 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009270 } else // trailing integer zero.
9271 sInt = Info.Ctx.MakeIntValue(0, EltTy);
9272 Elements.push_back(APValue(sInt));
9273 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009274 } else {
9275 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009276 if (CountInits < NumInits) {
9277 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009278 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009279 } else // trailing float zero.
9280 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9281 Elements.push_back(APValue(f));
9282 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00009283 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00009284 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009285 }
Richard Smith2d406342011-10-22 21:10:00 +00009286 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009287}
9288
Richard Smith2d406342011-10-22 21:10:00 +00009289bool
Richard Smithfddd3842011-12-30 21:15:51 +00009290VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009291 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00009292 QualType EltTy = VT->getElementType();
9293 APValue ZeroElement;
9294 if (EltTy->isIntegerType())
9295 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9296 else
9297 ZeroElement =
9298 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9299
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009300 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00009301 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009302}
9303
Richard Smith2d406342011-10-22 21:10:00 +00009304bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00009305 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00009306 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009307}
9308
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009309//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00009310// Array Evaluation
9311//===----------------------------------------------------------------------===//
9312
9313namespace {
9314 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009315 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00009316 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00009317 APValue &Result;
9318 public:
9319
Richard Smithd62306a2011-11-10 06:34:14 +00009320 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9321 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00009322
9323 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00009324 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00009325 Result = V;
9326 return true;
9327 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009328
Richard Smithfddd3842011-12-30 21:15:51 +00009329 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00009330 const ConstantArrayType *CAT =
9331 Info.Ctx.getAsConstantArrayType(E->getType());
9332 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009333 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00009334
9335 Result = APValue(APValue::UninitArray(), 0,
9336 CAT->getSize().getZExtValue());
9337 if (!Result.hasArrayFiller()) return true;
9338
Richard Smithfddd3842011-12-30 21:15:51 +00009339 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00009340 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009341 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00009342 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00009343 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00009344 }
9345
Richard Smith52a980a2015-08-28 02:43:42 +00009346 bool VisitCallExpr(const CallExpr *E) {
9347 return handleCallExpr(E, Result, &This);
9348 }
Richard Smithda1b4342019-09-27 01:26:47 +00009349 bool VisitInitListExpr(const InitListExpr *E,
9350 QualType AllocType = QualType());
Richard Smith410306b2016-12-12 02:53:20 +00009351 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00009352 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00009353 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9354 const LValue &Subobject,
9355 APValue *Value, QualType Type);
Richard Smithda1b4342019-09-27 01:26:47 +00009356 bool VisitStringLiteral(const StringLiteral *E,
9357 QualType AllocType = QualType()) {
9358 expandStringLiteral(Info, E, Result, AllocType);
Eli Friedman3bf72d72019-02-08 21:18:46 +00009359 return true;
9360 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009361 };
9362} // end anonymous namespace
9363
Richard Smithd62306a2011-11-10 06:34:14 +00009364static bool EvaluateArray(const Expr *E, const LValue &This,
9365 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00009366 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00009367 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009368}
9369
Richard Smithda1b4342019-09-27 01:26:47 +00009370static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9371 APValue &Result, const InitListExpr *ILE,
9372 QualType AllocType) {
9373 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9374 "not an array rvalue");
9375 return ArrayExprEvaluator(Info, This, Result)
9376 .VisitInitListExpr(ILE, AllocType);
9377}
9378
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009379// Return true iff the given array filler may depend on the element index.
9380static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9381 // For now, just whitelist non-class value-initialization and initialization
9382 // lists comprised of them.
9383 if (isa<ImplicitValueInitExpr>(FillerExpr))
9384 return false;
9385 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9386 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9387 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9388 return true;
9389 }
9390 return false;
9391 }
9392 return true;
9393}
9394
Richard Smithda1b4342019-09-27 01:26:47 +00009395bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9396 QualType AllocType) {
9397 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9398 AllocType.isNull() ? E->getType() : AllocType);
Richard Smithf3e9e432011-11-07 09:22:26 +00009399 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009400 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009401
Richard Smithca2cfbf2011-12-22 01:07:19 +00009402 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9403 // an appropriately-typed string literal enclosed in braces.
Richard Smithda1b4342019-09-27 01:26:47 +00009404 if (E->isStringLiteralInit()) {
9405 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9406 // FIXME: Support ObjCEncodeExpr here once we support it in
9407 // ArrayExprEvaluator generally.
9408 if (!SL)
9409 return Error(E);
9410 return VisitStringLiteral(SL, AllocType);
9411 }
Richard Smithca2cfbf2011-12-22 01:07:19 +00009412
Richard Smith253c2a32012-01-27 01:14:48 +00009413 bool Success = true;
9414
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009415 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9416 "zero-initialized array shouldn't have any initialized elts");
9417 APValue Filler;
9418 if (Result.isArray() && Result.hasArrayFiller())
9419 Filler = Result.getArrayFiller();
9420
Richard Smith9543c5e2013-04-22 14:44:29 +00009421 unsigned NumEltsToInit = E->getNumInits();
9422 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00009423 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00009424
9425 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009426 // array element.
9427 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00009428 NumEltsToInit = NumElts;
9429
Nicola Zaghen3538b392018-05-15 13:30:56 +00009430 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9431 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009432
Richard Smith9543c5e2013-04-22 14:44:29 +00009433 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009434
9435 // If the array was previously zero-initialized, preserve the
9436 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00009437 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009438 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9439 Result.getArrayInitializedElt(I) = Filler;
9440 if (Result.hasArrayFiller())
9441 Result.getArrayFiller() = Filler;
9442 }
9443
Richard Smithd62306a2011-11-10 06:34:14 +00009444 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009445 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00009446 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9447 const Expr *Init =
9448 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00009449 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00009450 Info, Subobject, Init) ||
9451 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00009452 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00009453 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00009454 return false;
9455 Success = false;
9456 }
Richard Smithd62306a2011-11-10 06:34:14 +00009457 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009458
Richard Smith9543c5e2013-04-22 14:44:29 +00009459 if (!Result.hasArrayFiller())
9460 return Success;
9461
9462 // If we get here, we have a trivial filler, which we can just evaluate
9463 // once and splat over the rest of the array elements.
9464 assert(FillerExpr && "no array filler for incomplete init list");
9465 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9466 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00009467}
9468
Richard Smith410306b2016-12-12 02:53:20 +00009469bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009470 LValue CommonLV;
Richard Smith410306b2016-12-12 02:53:20 +00009471 if (E->getCommonExpr() &&
Richard Smith457226e2019-09-23 03:48:44 +00009472 !Evaluate(Info.CurrentCall->createTemporary(
9473 E->getCommonExpr(),
9474 getStorageType(Info.Ctx, E->getCommonExpr()), false,
9475 CommonLV),
Richard Smith410306b2016-12-12 02:53:20 +00009476 Info, E->getCommonExpr()->getSourceExpr()))
9477 return false;
9478
9479 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9480
9481 uint64_t Elements = CAT->getSize().getZExtValue();
9482 Result = APValue(APValue::UninitArray(), Elements, Elements);
9483
9484 LValue Subobject = This;
9485 Subobject.addArray(Info, E, CAT);
9486
9487 bool Success = true;
9488 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9489 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9490 Info, Subobject, E->getSubExpr()) ||
9491 !HandleLValueArrayAdjustment(Info, E, Subobject,
9492 CAT->getElementType(), 1)) {
9493 if (!Info.noteFailure())
9494 return false;
9495 Success = false;
9496 }
9497 }
9498
9499 return Success;
9500}
9501
Richard Smith027bf112011-11-17 22:56:20 +00009502bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00009503 return VisitCXXConstructExpr(E, This, &Result, E->getType());
9504}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009505
Richard Smith9543c5e2013-04-22 14:44:29 +00009506bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9507 const LValue &Subobject,
9508 APValue *Value,
9509 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00009510 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00009511
9512 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9513 unsigned N = CAT->getSize().getZExtValue();
9514
9515 // Preserve the array filler if we had prior zero-initialization.
9516 APValue Filler =
9517 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9518 : APValue();
9519
9520 *Value = APValue(APValue::UninitArray(), N, N);
9521
9522 if (HadZeroInit)
9523 for (unsigned I = 0; I != N; ++I)
9524 Value->getArrayInitializedElt(I) = Filler;
9525
9526 // Initialize the elements.
9527 LValue ArrayElt = Subobject;
9528 ArrayElt.addArray(Info, E, CAT);
9529 for (unsigned I = 0; I != N; ++I)
9530 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9531 CAT->getElementType()) ||
9532 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9533 CAT->getElementType(), 1))
9534 return false;
9535
9536 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009537 }
Richard Smith027bf112011-11-17 22:56:20 +00009538
Richard Smith9543c5e2013-04-22 14:44:29 +00009539 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00009540 return Error(E);
9541
Richard Smithb8348f52016-05-12 22:16:28 +00009542 return RecordExprEvaluator(Info, Subobject, *Value)
9543 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00009544}
9545
Richard Smithf3e9e432011-11-07 09:22:26 +00009546//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009547// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00009548//
9549// As a GNU extension, we support casting pointers to sufficiently-wide integer
9550// types and back in constant folding. Integer values are thus represented
9551// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00009552//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009553
9554namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009555class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009556 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00009557 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009558public:
Richard Smith2e312c82012-03-03 22:46:17 +00009559 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009560 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00009561
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009562 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009563 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009564 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009565 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009566 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009567 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009568 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009569 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009570 return true;
9571 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009572 bool Success(const llvm::APSInt &SI, const Expr *E) {
9573 return Success(SI, E, Result);
9574 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009575
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009576 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00009577 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009578 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009579 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009580 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009581 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009582 Result.getInt().setIsUnsigned(
9583 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009584 return true;
9585 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009586 bool Success(const llvm::APInt &I, const Expr *E) {
9587 return Success(I, E, Result);
9588 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009589
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009590 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009591 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009592 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009593 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009594 return true;
9595 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009596 bool Success(uint64_t Value, const Expr *E) {
9597 return Success(Value, E, Result);
9598 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009599
Ken Dyckdbc01912011-03-11 02:13:43 +00009600 bool Success(CharUnits Size, const Expr *E) {
9601 return Success(Size.getQuantity(), E);
9602 }
9603
Richard Smith2e312c82012-03-03 22:46:17 +00009604 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00009605 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00009606 Result = V;
9607 return true;
9608 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009609 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00009610 }
Mike Stump11289f42009-09-09 15:08:12 +00009611
Richard Smithfddd3842011-12-30 21:15:51 +00009612 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00009613
Peter Collingbournee9200682011-05-13 03:29:01 +00009614 //===--------------------------------------------------------------------===//
9615 // Visitor Methods
9616 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009617
Fangrui Song407659a2018-11-30 23:41:18 +00009618 bool VisitConstantExpr(const ConstantExpr *E);
9619
Chris Lattner7174bf32008-07-12 00:38:25 +00009620 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009621 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009622 }
9623 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009624 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009625 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009626
9627 bool CheckReferencedDecl(const Expr *E, const Decl *D);
9628 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009629 if (CheckReferencedDecl(E, E->getDecl()))
9630 return true;
9631
9632 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009633 }
9634 bool VisitMemberExpr(const MemberExpr *E) {
9635 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00009636 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009637 return true;
9638 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009639
9640 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009641 }
9642
Peter Collingbournee9200682011-05-13 03:29:01 +00009643 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00009644 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00009645 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00009646 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00009647 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00009648
Peter Collingbournee9200682011-05-13 03:29:01 +00009649 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009650 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00009651
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009652 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009653 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009654 }
Mike Stump11289f42009-09-09 15:08:12 +00009655
Ted Kremeneke65b0862012-03-06 20:05:56 +00009656 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9657 return Success(E->getValue(), E);
9658 }
Richard Smith410306b2016-12-12 02:53:20 +00009659
9660 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9661 if (Info.ArrayInitIndex == uint64_t(-1)) {
9662 // We were asked to evaluate this subexpression independent of the
9663 // enclosing ArrayInitLoopExpr. We can't do that.
9664 Info.FFDiag(E);
9665 return false;
9666 }
9667 return Success(Info.ArrayInitIndex, E);
9668 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009669
Richard Smith4ce706a2011-10-11 21:43:33 +00009670 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00009671 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00009672 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009673 }
9674
Douglas Gregor29c42f22012-02-24 07:38:34 +00009675 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9676 return Success(E->getValue(), E);
9677 }
9678
John Wiegley6242b6a2011-04-28 00:16:57 +00009679 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9680 return Success(E->getValue(), E);
9681 }
9682
John Wiegleyf9f65842011-04-25 06:54:41 +00009683 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9684 return Success(E->getValue(), E);
9685 }
9686
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009687 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009688 bool VisitUnaryImag(const UnaryOperator *E);
9689
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009690 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009691 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00009692 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009693 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00009694};
Leonard Chandb01c3a2018-06-20 17:19:40 +00009695
9696class FixedPointExprEvaluator
9697 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9698 APValue &Result;
9699
9700 public:
9701 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9702 : ExprEvaluatorBaseTy(info), Result(result) {}
9703
Leonard Chandb01c3a2018-06-20 17:19:40 +00009704 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009705 return Success(
9706 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009707 }
9708
Leonard Chandb01c3a2018-06-20 17:19:40 +00009709 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009710 return Success(
9711 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009712 }
9713
9714 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009715 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009716 }
9717
Leonard Chand3f3e162019-01-18 21:04:25 +00009718 bool Success(const APFixedPoint &V, const Expr *E) {
9719 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9720 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9721 "Invalid evaluation result.");
9722 Result = APValue(V);
9723 return true;
9724 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00009725
9726 //===--------------------------------------------------------------------===//
9727 // Visitor Methods
9728 //===--------------------------------------------------------------------===//
9729
9730 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9731 return Success(E->getValue(), E);
9732 }
9733
Leonard Chand3f3e162019-01-18 21:04:25 +00009734 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009735 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00009736 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009737};
Chris Lattner05706e882008-07-11 18:11:29 +00009738} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009739
Richard Smith11562c52011-10-28 17:51:58 +00009740/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9741/// produce either the integer value or a pointer.
9742///
9743/// GCC has a heinous extension which folds casts between pointer types and
9744/// pointer-sized integral types. We support this by allowing the evaluation of
9745/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9746/// Some simple arithmetic on such values is supported (they are treated much
9747/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00009748static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00009749 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009750 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009751 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00009752}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009753
Richard Smithf57d8cb2011-12-09 22:58:01 +00009754static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00009755 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009756 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00009757 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009758 if (!Val.isInt()) {
9759 // FIXME: It would be better to produce the diagnostic for casting
9760 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00009761 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009762 return false;
9763 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009764 Result = Val.getInt();
9765 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009766}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009767
Eric Fiselier708afb52019-05-16 21:04:15 +00009768bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9769 APValue Evaluated = E->EvaluateInContext(
9770 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9771 return Success(Evaluated, E);
9772}
9773
Leonard Chand3f3e162019-01-18 21:04:25 +00009774static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9775 EvalInfo &Info) {
9776 if (E->getType()->isFixedPointType()) {
9777 APValue Val;
9778 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9779 return false;
9780 if (!Val.isFixedPoint())
9781 return false;
9782
9783 Result = Val.getFixedPoint();
9784 return true;
9785 }
9786 return false;
9787}
9788
9789static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9790 EvalInfo &Info) {
9791 if (E->getType()->isIntegerType()) {
9792 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9793 APSInt Val;
9794 if (!EvaluateInteger(E, Val, Info))
9795 return false;
9796 Result = APFixedPoint(Val, FXSema);
9797 return true;
9798 } else if (E->getType()->isFixedPointType()) {
9799 return EvaluateFixedPoint(E, Result, Info);
9800 }
9801 return false;
9802}
9803
Richard Smithf57d8cb2011-12-09 22:58:01 +00009804/// Check whether the given declaration can be directly converted to an integral
9805/// rvalue. If not, no diagnostic is produced; there are other things we can
9806/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009807bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00009808 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009809 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009810 // Check for signedness/width mismatches between E type and ECD value.
9811 bool SameSign = (ECD->getInitVal().isSigned()
9812 == E->getType()->isSignedIntegerOrEnumerationType());
9813 bool SameWidth = (ECD->getInitVal().getBitWidth()
9814 == Info.Ctx.getIntWidth(E->getType()));
9815 if (SameSign && SameWidth)
9816 return Success(ECD->getInitVal(), E);
9817 else {
9818 // Get rid of mismatch (otherwise Success assertions will fail)
9819 // by computing a new value matching the type of E.
9820 llvm::APSInt Val = ECD->getInitVal();
9821 if (!SameSign)
9822 Val.setIsSigned(!ECD->getInitVal().isSigned());
9823 if (!SameWidth)
9824 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9825 return Success(Val, E);
9826 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009827 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009828 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00009829}
9830
Richard Smith08b682b2018-05-23 21:18:00 +00009831/// Values returned by __builtin_classify_type, chosen to match the values
9832/// produced by GCC's builtin.
9833enum class GCCTypeClass {
9834 None = -1,
9835 Void = 0,
9836 Integer = 1,
9837 // GCC reserves 2 for character types, but instead classifies them as
9838 // integers.
9839 Enum = 3,
9840 Bool = 4,
9841 Pointer = 5,
9842 // GCC reserves 6 for references, but appears to never use it (because
9843 // expressions never have reference type, presumably).
9844 PointerToDataMember = 7,
9845 RealFloat = 8,
9846 Complex = 9,
9847 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9848 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9849 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9850 // uses 12 for that purpose, same as for a class or struct. Maybe it
9851 // internally implements a pointer to member as a struct? Who knows.
9852 PointerToMemberFunction = 12, // Not a bug, see above.
9853 ClassOrStruct = 12,
9854 Union = 13,
9855 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9856 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9857 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9858 // literals.
9859};
9860
Chris Lattner86ee2862008-10-06 06:40:35 +00009861/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9862/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00009863static GCCTypeClass
9864EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9865 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00009866
Richard Smith08b682b2018-05-23 21:18:00 +00009867 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009868 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9869
9870 switch (CanTy->getTypeClass()) {
9871#define TYPE(ID, BASE)
9872#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9873#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9874#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
John McCall36b12a82019-10-02 06:35:23 +00009875#include "clang/AST/TypeNodes.inc"
Richard Smith08b682b2018-05-23 21:18:00 +00009876 case Type::Auto:
9877 case Type::DeducedTemplateSpecialization:
9878 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009879
9880 case Type::Builtin:
9881 switch (BT->getKind()) {
9882#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00009883#define SIGNED_TYPE(ID, SINGLETON_ID) \
9884 case BuiltinType::ID: return GCCTypeClass::Integer;
9885#define FLOATING_TYPE(ID, SINGLETON_ID) \
9886 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9887#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9888 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009889#include "clang/AST/BuiltinTypes.def"
9890 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00009891 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009892
9893 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00009894 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009895
Richard Smith08b682b2018-05-23 21:18:00 +00009896 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009897 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00009898 case BuiltinType::WChar_U:
9899 case BuiltinType::Char8:
9900 case BuiltinType::Char16:
9901 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009902 case BuiltinType::UShort:
9903 case BuiltinType::UInt:
9904 case BuiltinType::ULong:
9905 case BuiltinType::ULongLong:
9906 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00009907 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009908
Leonard Chanf921d852018-06-04 16:07:52 +00009909 case BuiltinType::UShortAccum:
9910 case BuiltinType::UAccum:
9911 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009912 case BuiltinType::UShortFract:
9913 case BuiltinType::UFract:
9914 case BuiltinType::ULongFract:
9915 case BuiltinType::SatUShortAccum:
9916 case BuiltinType::SatUAccum:
9917 case BuiltinType::SatULongAccum:
9918 case BuiltinType::SatUShortFract:
9919 case BuiltinType::SatUFract:
9920 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00009921 return GCCTypeClass::None;
9922
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009923 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009924
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009925 case BuiltinType::ObjCId:
9926 case BuiltinType::ObjCClass:
9927 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00009928#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9929 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00009930#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00009931#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9932 case BuiltinType::Id:
9933#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009934 case BuiltinType::OCLSampler:
9935 case BuiltinType::OCLEvent:
9936 case BuiltinType::OCLClkEvent:
9937 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009938 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00009939#define SVE_TYPE(Name, Id, SingletonId) \
9940 case BuiltinType::Id:
9941#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00009942 return GCCTypeClass::None;
9943
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009944 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00009945 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009946 };
Richard Smith08b682b2018-05-23 21:18:00 +00009947 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009948
9949 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00009950 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009951
9952 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009953 case Type::ConstantArray:
9954 case Type::VariableArray:
9955 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00009956 case Type::FunctionNoProto:
9957 case Type::FunctionProto:
9958 return GCCTypeClass::Pointer;
9959
9960 case Type::MemberPointer:
9961 return CanTy->isMemberDataPointerType()
9962 ? GCCTypeClass::PointerToDataMember
9963 : GCCTypeClass::PointerToMemberFunction;
9964
9965 case Type::Complex:
9966 return GCCTypeClass::Complex;
9967
9968 case Type::Record:
9969 return CanTy->isUnionType() ? GCCTypeClass::Union
9970 : GCCTypeClass::ClassOrStruct;
9971
9972 case Type::Atomic:
9973 // GCC classifies _Atomic T the same as T.
9974 return EvaluateBuiltinClassifyType(
9975 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009976
9977 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009978 case Type::Vector:
9979 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009980 case Type::ObjCObject:
9981 case Type::ObjCInterface:
9982 case Type::ObjCObjectPointer:
9983 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00009984 // GCC classifies vectors as None. We follow its lead and classify all
9985 // other types that don't fit into the regular classification the same way.
9986 return GCCTypeClass::None;
9987
9988 case Type::LValueReference:
9989 case Type::RValueReference:
9990 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009991 }
9992
Richard Smith08b682b2018-05-23 21:18:00 +00009993 llvm_unreachable("unexpected type class");
9994}
9995
9996/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9997/// as GCC.
9998static GCCTypeClass
9999EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10000 // If no argument was supplied, default to None. This isn't
10001 // ideal, however it is what gcc does.
10002 if (E->getNumArgs() == 0)
10003 return GCCTypeClass::None;
10004
10005 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10006 // being an ICE, but still folds it to a constant using the type of the first
10007 // argument.
10008 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +000010009}
10010
Richard Smith5fab0c92011-12-28 19:48:30 +000010011/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +000010012/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +000010013///
Richard Smith31cfb312019-04-27 02:58:17 +000010014/// A pointer is only "constant" if it is null (or a pointer cast to integer)
10015/// or it points to the first character of a string literal.
10016static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10017 APValue::LValueBase Base = LV.getLValueBase();
10018 if (Base.isNull()) {
10019 // A null base is acceptable.
10020 return true;
10021 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10022 if (!isa<StringLiteral>(E))
10023 return false;
10024 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +000010025 } else if (Base.is<TypeInfoLValue>()) {
10026 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10027 // evaluate to true.
10028 return true;
Richard Smith31cfb312019-04-27 02:58:17 +000010029 } else {
10030 // Any other base is not constant enough for GCC.
10031 return false;
10032 }
Richard Smith5fab0c92011-12-28 19:48:30 +000010033}
10034
10035/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10036/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +000010037static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +000010038 // This evaluation is not permitted to have side-effects, so evaluate it in
10039 // a speculative evaluation context.
10040 SpeculativeEvaluationRAII SpeculativeEval(Info);
10041
Richard Smith31cfb312019-04-27 02:58:17 +000010042 // Constant-folding is always enabled for the operand of __builtin_constant_p
10043 // (even when the enclosing evaluation context otherwise requires a strict
10044 // language-specific constant expression).
10045 FoldConstant Fold(Info, true);
10046
Richard Smith5fab0c92011-12-28 19:48:30 +000010047 QualType ArgType = Arg->getType();
10048
10049 // __builtin_constant_p always has one operand. The rules which gcc follows
10050 // are not precisely documented, but are as follows:
10051 //
10052 // - If the operand is of integral, floating, complex or enumeration type,
10053 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +000010054 // - If the operand can be folded to a pointer to the first character
10055 // of a string literal (or such a pointer cast to an integral type)
10056 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +000010057 //
10058 // Otherwise, it returns 0.
10059 //
10060 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +000010061 // its support for this did not work prior to GCC 9 and is not yet well
10062 // understood.
10063 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10064 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10065 ArgType->isNullPtrType()) {
10066 APValue V;
10067 if (!::EvaluateAsRValue(Info, Arg, V)) {
10068 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +000010069 return false;
Richard Smith31cfb312019-04-27 02:58:17 +000010070 }
Richard Smith5fab0c92011-12-28 19:48:30 +000010071
Richard Smith31cfb312019-04-27 02:58:17 +000010072 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +000010073 if (V.getKind() == APValue::LValue)
10074 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +000010075
10076 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +000010077 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +000010078 }
10079
10080 // Anything else isn't considered to be sufficiently constant.
10081 return false;
10082}
10083
John McCall95007602010-05-10 23:27:23 +000010084/// Retrieves the "underlying object type" of the given expression,
10085/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +000010086static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000010087 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10088 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +000010089 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000010090 } else if (const Expr *E = B.get<const Expr*>()) {
10091 if (isa<CompoundLiteralExpr>(E))
10092 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +000010093 } else if (B.is<TypeInfoLValue>()) {
10094 return B.getTypeInfoType();
Richard Smithda1b4342019-09-27 01:26:47 +000010095 } else if (B.is<DynamicAllocLValue>()) {
10096 return B.getDynamicAllocType();
John McCall95007602010-05-10 23:27:23 +000010097 }
10098
10099 return QualType();
10100}
10101
George Burgess IV3a03fab2015-09-04 21:28:13 +000010102/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +000010103/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +000010104/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +000010105/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10106///
10107/// Always returns an RValue with a pointer representation.
10108static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10109 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10110
10111 auto *NoParens = E->IgnoreParens();
10112 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +000010113 if (Cast == nullptr)
10114 return NoParens;
10115
10116 // We only conservatively allow a few kinds of casts, because this code is
10117 // inherently a simple solution that seeks to support the common case.
10118 auto CastKind = Cast->getCastKind();
10119 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10120 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +000010121 return NoParens;
10122
10123 auto *SubExpr = Cast->getSubExpr();
10124 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10125 return NoParens;
10126 return ignorePointerCastsAndParens(SubExpr);
10127}
10128
George Burgess IVa51c4072015-10-16 01:49:01 +000010129/// Checks to see if the given LValue's Designator is at the end of the LValue's
10130/// record layout. e.g.
10131/// struct { struct { int a, b; } fst, snd; } obj;
10132/// obj.fst // no
10133/// obj.snd // yes
10134/// obj.fst.a // no
10135/// obj.fst.b // no
10136/// obj.snd.a // no
10137/// obj.snd.b // yes
10138///
10139/// Please note: this function is specialized for how __builtin_object_size
10140/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +000010141///
Richard Smith6f4f0f12017-10-20 22:56:25 +000010142/// If this encounters an invalid RecordDecl or otherwise cannot determine the
10143/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +000010144static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10145 assert(!LVal.Designator.Invalid);
10146
George Burgess IV4168d752016-06-27 19:40:41 +000010147 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10148 const RecordDecl *Parent = FD->getParent();
10149 Invalid = Parent->isInvalidDecl();
10150 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +000010151 return true;
George Burgess IV4168d752016-06-27 19:40:41 +000010152 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +000010153 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10154 };
10155
10156 auto &Base = LVal.getLValueBase();
10157 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10158 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +000010159 bool Invalid;
10160 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10161 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +000010162 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +000010163 for (auto *FD : IFD->chain()) {
10164 bool Invalid;
10165 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10166 return Invalid;
10167 }
George Burgess IVa51c4072015-10-16 01:49:01 +000010168 }
10169 }
10170
George Burgess IVe3763372016-12-22 02:50:20 +000010171 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +000010172 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +000010173 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000010174 // If we don't know the array bound, conservatively assume we're looking at
10175 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +000010176 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +000010177 if (BaseType->isIncompleteArrayType())
10178 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10179 else
10180 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +000010181 }
10182
10183 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10184 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +000010185 if (BaseType->isArrayType()) {
10186 // Because __builtin_object_size treats arrays as objects, we can ignore
10187 // the index iff this is the last array in the Designator.
10188 if (I + 1 == E)
10189 return true;
George Burgess IVe3763372016-12-22 02:50:20 +000010190 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +000010191 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +000010192 if (Index + 1 != CAT->getSize())
10193 return false;
10194 BaseType = CAT->getElementType();
10195 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +000010196 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010197 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +000010198 if (Index != 1)
10199 return false;
10200 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +000010201 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +000010202 bool Invalid;
10203 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10204 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +000010205 BaseType = FD->getType();
10206 } else {
George Burgess IVe3763372016-12-22 02:50:20 +000010207 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +000010208 return false;
10209 }
10210 }
10211 return true;
10212}
10213
George Burgess IVe3763372016-12-22 02:50:20 +000010214/// Tests to see if the LValue has a user-specified designator (that isn't
10215/// necessarily valid). Note that this always returns 'true' if the LValue has
10216/// an unsized array as its first designator entry, because there's currently no
10217/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +000010218static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +000010219 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +000010220 return false;
10221
George Burgess IVe3763372016-12-22 02:50:20 +000010222 if (!LVal.Designator.Entries.empty())
10223 return LVal.Designator.isMostDerivedAnUnsizedArray();
10224
George Burgess IVa51c4072015-10-16 01:49:01 +000010225 if (!LVal.InvalidBase)
10226 return true;
10227
George Burgess IVe3763372016-12-22 02:50:20 +000010228 // If `E` is a MemberExpr, then the first part of the designator is hiding in
10229 // the LValueBase.
10230 const auto *E = LVal.Base.dyn_cast<const Expr *>();
10231 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +000010232}
10233
George Burgess IVe3763372016-12-22 02:50:20 +000010234/// Attempts to detect a user writing into a piece of memory that's impossible
10235/// to figure out the size of by just using types.
10236static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10237 const SubobjectDesignator &Designator = LVal.Designator;
10238 // Notes:
10239 // - Users can only write off of the end when we have an invalid base. Invalid
10240 // bases imply we don't know where the memory came from.
10241 // - We used to be a bit more aggressive here; we'd only be conservative if
10242 // the array at the end was flexible, or if it had 0 or 1 elements. This
10243 // broke some common standard library extensions (PR30346), but was
10244 // otherwise seemingly fine. It may be useful to reintroduce this behavior
10245 // with some sort of whitelist. OTOH, it seems that GCC is always
10246 // conservative with the last element in structs (if it's an array), so our
10247 // current behavior is more compatible than a whitelisting approach would
10248 // be.
10249 return LVal.InvalidBase &&
10250 Designator.Entries.size() == Designator.MostDerivedPathLength &&
10251 Designator.MostDerivedIsArrayElement &&
10252 isDesignatorAtObjectEnd(Ctx, LVal);
10253}
10254
10255/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10256/// Fails if the conversion would cause loss of precision.
10257static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10258 CharUnits &Result) {
10259 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10260 if (Int.ugt(CharUnitsMax))
10261 return false;
10262 Result = CharUnits::fromQuantity(Int.getZExtValue());
10263 return true;
10264}
10265
10266/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10267/// determine how many bytes exist from the beginning of the object to either
10268/// the end of the current subobject, or the end of the object itself, depending
10269/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +000010270///
George Burgess IVe3763372016-12-22 02:50:20 +000010271/// If this returns false, the value of Result is undefined.
10272static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10273 unsigned Type, const LValue &LVal,
10274 CharUnits &EndOffset) {
10275 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010276
George Burgess IV7fb7e362017-01-03 23:35:19 +000010277 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10278 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10279 return false;
10280 return HandleSizeof(Info, ExprLoc, Ty, Result);
10281 };
10282
George Burgess IVe3763372016-12-22 02:50:20 +000010283 // We want to evaluate the size of the entire object. This is a valid fallback
10284 // for when Type=1 and the designator is invalid, because we're asked for an
10285 // upper-bound.
10286 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10287 // Type=3 wants a lower bound, so we can't fall back to this.
10288 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +000010289 return false;
George Burgess IVe3763372016-12-22 02:50:20 +000010290
10291 llvm::APInt APEndOffset;
10292 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10293 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10294 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10295
10296 if (LVal.InvalidBase)
10297 return false;
10298
10299 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +000010300 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +000010301 }
10302
George Burgess IVe3763372016-12-22 02:50:20 +000010303 // We want to evaluate the size of a subobject.
10304 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010305
10306 // The following is a moderately common idiom in C:
10307 //
10308 // struct Foo { int a; char c[1]; };
10309 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10310 // strcpy(&F->c[0], Bar);
10311 //
George Burgess IVe3763372016-12-22 02:50:20 +000010312 // In order to not break too much legacy code, we need to support it.
10313 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10314 // If we can resolve this to an alloc_size call, we can hand that back,
10315 // because we know for certain how many bytes there are to write to.
10316 llvm::APInt APEndOffset;
10317 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10318 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10319 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10320
10321 // If we cannot determine the size of the initial allocation, then we can't
10322 // given an accurate upper-bound. However, we are still able to give
10323 // conservative lower-bounds for Type=3.
10324 if (Type == 1)
10325 return false;
10326 }
10327
10328 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +000010329 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010330 return false;
10331
George Burgess IVe3763372016-12-22 02:50:20 +000010332 // According to the GCC documentation, we want the size of the subobject
10333 // denoted by the pointer. But that's not quite right -- what we actually
10334 // want is the size of the immediately-enclosing array, if there is one.
10335 int64_t ElemsRemaining;
10336 if (Designator.MostDerivedIsArrayElement &&
10337 Designator.Entries.size() == Designator.MostDerivedPathLength) {
10338 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010339 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +000010340 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10341 } else {
10342 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10343 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010344
George Burgess IVe3763372016-12-22 02:50:20 +000010345 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10346 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010347}
10348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010349/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +000010350/// returns true and stores the result in @p Size.
10351///
10352/// If @p WasError is non-null, this will report whether the failure to evaluate
10353/// is to be treated as an Error in IntExprEvaluator.
10354static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10355 EvalInfo &Info, uint64_t &Size) {
10356 // Determine the denoted object.
10357 LValue LVal;
10358 {
10359 // The operand of __builtin_object_size is never evaluated for side-effects.
10360 // If there are any, but we can determine the pointed-to object anyway, then
10361 // ignore the side-effects.
10362 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +000010363 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +000010364
10365 if (E->isGLValue()) {
10366 // It's possible for us to be given GLValues if we're called via
10367 // Expr::tryEvaluateObjectSize.
10368 APValue RVal;
10369 if (!EvaluateAsRValue(Info, E, RVal))
10370 return false;
10371 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +000010372 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10373 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +000010374 return false;
10375 }
10376
10377 // If we point to before the start of the object, there are no accessible
10378 // bytes.
10379 if (LVal.getLValueOffset().isNegative()) {
10380 Size = 0;
10381 return true;
10382 }
10383
10384 CharUnits EndOffset;
10385 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10386 return false;
10387
10388 // If we've fallen outside of the end offset, just pretend there's nothing to
10389 // write to/read from.
10390 if (EndOffset <= LVal.getLValueOffset())
10391 Size = 0;
10392 else
10393 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10394 return true;
John McCall95007602010-05-10 23:27:23 +000010395}
10396
Fangrui Song407659a2018-11-30 23:41:18 +000010397bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10398 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +000010399 if (E->getResultAPValueKind() != APValue::None)
10400 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +000010401 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10402}
10403
Peter Collingbournee9200682011-05-13 03:29:01 +000010404bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +000010405 if (unsigned BuiltinOp = E->getBuiltinCallee())
10406 return VisitBuiltinCallExpr(E, BuiltinOp);
10407
10408 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10409}
10410
10411bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10412 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +000010413 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010414 default:
Peter Collingbournee9200682011-05-13 03:29:01 +000010415 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +000010416
Erik Pilkington9c3b5882019-01-30 20:34:53 +000010417 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +000010418 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +000010419 // The type was checked when we built the expression.
10420 unsigned Type =
10421 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10422 assert(Type <= 3 && "unexpected type");
10423
George Burgess IVe3763372016-12-22 02:50:20 +000010424 uint64_t Size;
10425 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10426 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +000010427
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010428 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +000010429 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +000010430
Richard Smith01ade172012-05-23 04:13:20 +000010431 // Expression had no side effects, but we couldn't statically determine the
10432 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010433 switch (Info.EvalMode) {
10434 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010435 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010436 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010437 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010438 return Error(E);
10439 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010440 // Reduce it to a constant now.
10441 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010442 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +000010443
10444 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +000010445 }
10446
Tim Northover314fbfa2018-11-02 13:14:11 +000010447 case Builtin::BI__builtin_os_log_format_buffer_size: {
10448 analyze_os_log::OSLogBufferLayout Layout;
10449 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10450 return Success(Layout.size().getQuantity(), E);
10451 }
10452
Benjamin Kramera801f4a2012-10-06 14:42:22 +000010453 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +000010454 case Builtin::BI__builtin_bswap32:
10455 case Builtin::BI__builtin_bswap64: {
10456 APSInt Val;
10457 if (!EvaluateInteger(E->getArg(0), Val, Info))
10458 return false;
10459
10460 return Success(Val.byteSwap(), E);
10461 }
10462
Richard Smith8889a3d2013-06-13 06:26:32 +000010463 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +000010464 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +000010465
Craig Topperf95a6d92018-08-08 22:31:12 +000010466 case Builtin::BI__builtin_clrsb:
10467 case Builtin::BI__builtin_clrsbl:
10468 case Builtin::BI__builtin_clrsbll: {
10469 APSInt Val;
10470 if (!EvaluateInteger(E->getArg(0), Val, Info))
10471 return false;
10472
10473 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10474 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010475
Richard Smith80b3c8e2013-06-13 05:04:16 +000010476 case Builtin::BI__builtin_clz:
10477 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010478 case Builtin::BI__builtin_clzll:
10479 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010480 APSInt Val;
10481 if (!EvaluateInteger(E->getArg(0), Val, Info))
10482 return false;
10483 if (!Val)
10484 return Error(E);
10485
10486 return Success(Val.countLeadingZeros(), E);
10487 }
10488
Fangrui Song407659a2018-11-30 23:41:18 +000010489 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +000010490 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +000010491 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +000010492 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +000010493 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +000010494 // Outside a constant context, eagerly evaluate to false in the presence
10495 // of side-effects in order to avoid -Wunsequenced false-positives in
10496 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +000010497 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +000010498 }
David Blaikie639b3d12019-05-03 18:11:31 +000010499 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10500 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000010501 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010502
Eric Fiselieradd16a82019-04-24 02:23:30 +000010503 case Builtin::BI__builtin_is_constant_evaluated:
10504 return Success(Info.InConstantContext, E);
10505
Richard Smith80b3c8e2013-06-13 05:04:16 +000010506 case Builtin::BI__builtin_ctz:
10507 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010508 case Builtin::BI__builtin_ctzll:
10509 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010510 APSInt Val;
10511 if (!EvaluateInteger(E->getArg(0), Val, Info))
10512 return false;
10513 if (!Val)
10514 return Error(E);
10515
10516 return Success(Val.countTrailingZeros(), E);
10517 }
10518
Richard Smith8889a3d2013-06-13 06:26:32 +000010519 case Builtin::BI__builtin_eh_return_data_regno: {
10520 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10521 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10522 return Success(Operand, E);
10523 }
10524
10525 case Builtin::BI__builtin_expect:
10526 return Visit(E->getArg(0));
10527
10528 case Builtin::BI__builtin_ffs:
10529 case Builtin::BI__builtin_ffsl:
10530 case Builtin::BI__builtin_ffsll: {
10531 APSInt Val;
10532 if (!EvaluateInteger(E->getArg(0), Val, Info))
10533 return false;
10534
10535 unsigned N = Val.countTrailingZeros();
10536 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10537 }
10538
10539 case Builtin::BI__builtin_fpclassify: {
10540 APFloat Val(0.0);
10541 if (!EvaluateFloat(E->getArg(5), Val, Info))
10542 return false;
10543 unsigned Arg;
10544 switch (Val.getCategory()) {
10545 case APFloat::fcNaN: Arg = 0; break;
10546 case APFloat::fcInfinity: Arg = 1; break;
10547 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10548 case APFloat::fcZero: Arg = 4; break;
10549 }
10550 return Visit(E->getArg(Arg));
10551 }
10552
10553 case Builtin::BI__builtin_isinf_sign: {
10554 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +000010555 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +000010556 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10557 }
10558
Richard Smithea3019d2013-10-15 19:07:14 +000010559 case Builtin::BI__builtin_isinf: {
10560 APFloat Val(0.0);
10561 return EvaluateFloat(E->getArg(0), Val, Info) &&
10562 Success(Val.isInfinity() ? 1 : 0, E);
10563 }
10564
10565 case Builtin::BI__builtin_isfinite: {
10566 APFloat Val(0.0);
10567 return EvaluateFloat(E->getArg(0), Val, Info) &&
10568 Success(Val.isFinite() ? 1 : 0, E);
10569 }
10570
10571 case Builtin::BI__builtin_isnan: {
10572 APFloat Val(0.0);
10573 return EvaluateFloat(E->getArg(0), Val, Info) &&
10574 Success(Val.isNaN() ? 1 : 0, E);
10575 }
10576
10577 case Builtin::BI__builtin_isnormal: {
10578 APFloat Val(0.0);
10579 return EvaluateFloat(E->getArg(0), Val, Info) &&
10580 Success(Val.isNormal() ? 1 : 0, E);
10581 }
10582
Richard Smith8889a3d2013-06-13 06:26:32 +000010583 case Builtin::BI__builtin_parity:
10584 case Builtin::BI__builtin_parityl:
10585 case Builtin::BI__builtin_parityll: {
10586 APSInt Val;
10587 if (!EvaluateInteger(E->getArg(0), Val, Info))
10588 return false;
10589
10590 return Success(Val.countPopulation() % 2, E);
10591 }
10592
Richard Smith80b3c8e2013-06-13 05:04:16 +000010593 case Builtin::BI__builtin_popcount:
10594 case Builtin::BI__builtin_popcountl:
10595 case Builtin::BI__builtin_popcountll: {
10596 APSInt Val;
10597 if (!EvaluateInteger(E->getArg(0), Val, Info))
10598 return false;
10599
10600 return Success(Val.countPopulation(), E);
10601 }
10602
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010603 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +000010604 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +000010605 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010606 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010607 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +000010608 << /*isConstexpr*/0 << /*isConstructor*/0
10609 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +000010610 else
Richard Smithce1ec5e2012-03-15 04:53:45 +000010611 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010612 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +000010613 case Builtin::BI__builtin_strlen:
10614 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +000010615 // As an extension, we support __builtin_strlen() as a constant expression,
10616 // and support folding strlen() to a constant.
10617 LValue String;
10618 if (!EvaluatePointer(E->getArg(0), String, Info))
10619 return false;
10620
Richard Smith8110c9d2016-11-29 19:45:17 +000010621 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10622
Richard Smithe6c19f22013-11-15 02:10:04 +000010623 // Fast path: if it's a string literal, search the string value.
10624 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10625 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010626 // The string literal may have embedded null characters. Find the first
10627 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +000010628 StringRef Str = S->getBytes();
10629 int64_t Off = String.Offset.getQuantity();
10630 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010631 S->getCharByteWidth() == 1 &&
10632 // FIXME: Add fast-path for wchar_t too.
10633 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +000010634 Str = Str.substr(Off);
10635
10636 StringRef::size_type Pos = Str.find(0);
10637 if (Pos != StringRef::npos)
10638 Str = Str.substr(0, Pos);
10639
10640 return Success(Str.size(), E);
10641 }
10642
10643 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010644 }
Richard Smithe6c19f22013-11-15 02:10:04 +000010645
10646 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +000010647 for (uint64_t Strlen = 0; /**/; ++Strlen) {
10648 APValue Char;
10649 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
10650 !Char.isInt())
10651 return false;
10652 if (!Char.getInt())
10653 return Success(Strlen, E);
10654 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
10655 return false;
10656 }
10657 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010658
Richard Smithe151bab2016-11-11 23:43:35 +000010659 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010660 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010661 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010662 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010663 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010664 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010665 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010666 // A call to strlen is not a constant expression.
10667 if (Info.getLangOpts().CPlusPlus11)
10668 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10669 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +000010670 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +000010671 else
10672 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010673 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +000010674 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010675 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010676 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010677 case Builtin::BI__builtin_wcsncmp:
10678 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010679 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010680 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +000010681 LValue String1, String2;
10682 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10683 !EvaluatePointer(E->getArg(1), String2, Info))
10684 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +000010685
Richard Smithe151bab2016-11-11 23:43:35 +000010686 uint64_t MaxLength = uint64_t(-1);
10687 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010688 BuiltinOp != Builtin::BIwcscmp &&
10689 BuiltinOp != Builtin::BI__builtin_strcmp &&
10690 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +000010691 APSInt N;
10692 if (!EvaluateInteger(E->getArg(2), N, Info))
10693 return false;
10694 MaxLength = N.getExtValue();
10695 }
Hubert Tong147b7432018-12-12 16:53:43 +000010696
10697 // Empty substrings compare equal by definition.
10698 if (MaxLength == 0u)
10699 return Success(0, E);
10700
10701 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10702 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10703 String1.Designator.Invalid || String2.Designator.Invalid)
10704 return false;
10705
10706 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10707 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10708
10709 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +000010710 BuiltinOp == Builtin::BIbcmp ||
10711 BuiltinOp == Builtin::BI__builtin_memcmp ||
10712 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010713
10714 assert(IsRawByte ||
10715 (Info.Ctx.hasSameUnqualifiedType(
10716 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
10717 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
10718
10719 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10720 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10721 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10722 Char1.isInt() && Char2.isInt();
10723 };
10724 const auto &AdvanceElems = [&] {
10725 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10726 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10727 };
10728
10729 if (IsRawByte) {
10730 uint64_t BytesRemaining = MaxLength;
10731 // Pointers to const void may point to objects of incomplete type.
10732 if (CharTy1->isIncompleteType()) {
10733 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10734 return false;
10735 }
10736 if (CharTy2->isIncompleteType()) {
10737 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10738 return false;
10739 }
10740 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10741 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10742 // Give up on comparing between elements with disparate widths.
10743 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10744 return false;
10745 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10746 assert(BytesRemaining && "BytesRemaining should not be zero: the "
10747 "following loop considers at least one element");
10748 while (true) {
10749 APValue Char1, Char2;
10750 if (!ReadCurElems(Char1, Char2))
10751 return false;
10752 // We have compatible in-memory widths, but a possible type and
10753 // (for `bool`) internal representation mismatch.
10754 // Assuming two's complement representation, including 0 for `false` and
10755 // 1 for `true`, we can check an appropriate number of elements for
10756 // equality even if they are not byte-sized.
10757 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10758 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10759 if (Char1InMem.ne(Char2InMem)) {
10760 // If the elements are byte-sized, then we can produce a three-way
10761 // comparison result in a straightforward manner.
10762 if (BytesPerElement == 1u) {
10763 // memcmp always compares unsigned chars.
10764 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10765 }
10766 // The result is byte-order sensitive, and we have multibyte elements.
10767 // FIXME: We can compare the remaining bytes in the correct order.
10768 return false;
10769 }
10770 if (!AdvanceElems())
10771 return false;
10772 if (BytesRemaining <= BytesPerElement)
10773 break;
10774 BytesRemaining -= BytesPerElement;
10775 }
10776 // Enough elements are equal to account for the memcmp limit.
10777 return Success(0, E);
10778 }
10779
Clement Courbet8c3343d2019-02-14 12:00:34 +000010780 bool StopAtNull =
10781 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10782 BuiltinOp != Builtin::BIwmemcmp &&
10783 BuiltinOp != Builtin::BI__builtin_memcmp &&
10784 BuiltinOp != Builtin::BI__builtin_bcmp &&
10785 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +000010786 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10787 BuiltinOp == Builtin::BIwcsncmp ||
10788 BuiltinOp == Builtin::BIwmemcmp ||
10789 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10790 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10791 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010792
Richard Smithe151bab2016-11-11 23:43:35 +000010793 for (; MaxLength; --MaxLength) {
10794 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +000010795 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +000010796 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +000010797 if (Char1.getInt() != Char2.getInt()) {
10798 if (IsWide) // wmemcmp compares with wchar_t signedness.
10799 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10800 // memcmp always compares unsigned chars.
10801 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10802 }
Richard Smithe151bab2016-11-11 23:43:35 +000010803 if (StopAtNull && !Char1.getInt())
10804 return Success(0, E);
10805 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +000010806 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +000010807 return false;
10808 }
10809 // We hit the strncmp / memcmp limit.
10810 return Success(0, E);
10811 }
10812
Richard Smith01ba47d2012-04-13 00:45:38 +000010813 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +000010814 case Builtin::BI__atomic_is_lock_free:
10815 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +000010816 APSInt SizeVal;
10817 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10818 return false;
10819
10820 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10821 // of two less than the maximum inline atomic width, we know it is
10822 // lock-free. If the size isn't a power of two, or greater than the
10823 // maximum alignment where we promote atomics, we know it is not lock-free
10824 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10825 // the answer can only be determined at runtime; for example, 16-byte
10826 // atomics have lock-free implementations on some, but not all,
10827 // x86-64 processors.
10828
10829 // Check power-of-two.
10830 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +000010831 if (Size.isPowerOfTwo()) {
10832 // Check against inlining width.
10833 unsigned InlineWidthBits =
10834 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10835 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10836 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10837 Size == CharUnits::One() ||
10838 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10839 Expr::NPC_NeverValueDependent))
10840 // OK, we will inline appropriately-aligned operations of this size,
10841 // and _Atomic(T) is appropriately-aligned.
10842 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010843
Richard Smith01ba47d2012-04-13 00:45:38 +000010844 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10845 castAs<PointerType>()->getPointeeType();
10846 if (!PointeeType->isIncompleteType() &&
10847 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10848 // OK, we will inline operations on this object.
10849 return Success(1, E);
10850 }
10851 }
10852 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010853
Richard Smith01ba47d2012-04-13 00:45:38 +000010854 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10855 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010856 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +000010857 case Builtin::BIomp_is_initial_device:
10858 // We can decide statically which value the runtime would return if called.
10859 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +000010860 case Builtin::BI__builtin_add_overflow:
10861 case Builtin::BI__builtin_sub_overflow:
10862 case Builtin::BI__builtin_mul_overflow:
10863 case Builtin::BI__builtin_sadd_overflow:
10864 case Builtin::BI__builtin_uadd_overflow:
10865 case Builtin::BI__builtin_uaddl_overflow:
10866 case Builtin::BI__builtin_uaddll_overflow:
10867 case Builtin::BI__builtin_usub_overflow:
10868 case Builtin::BI__builtin_usubl_overflow:
10869 case Builtin::BI__builtin_usubll_overflow:
10870 case Builtin::BI__builtin_umul_overflow:
10871 case Builtin::BI__builtin_umull_overflow:
10872 case Builtin::BI__builtin_umulll_overflow:
10873 case Builtin::BI__builtin_saddl_overflow:
10874 case Builtin::BI__builtin_saddll_overflow:
10875 case Builtin::BI__builtin_ssub_overflow:
10876 case Builtin::BI__builtin_ssubl_overflow:
10877 case Builtin::BI__builtin_ssubll_overflow:
10878 case Builtin::BI__builtin_smul_overflow:
10879 case Builtin::BI__builtin_smull_overflow:
10880 case Builtin::BI__builtin_smulll_overflow: {
10881 LValue ResultLValue;
10882 APSInt LHS, RHS;
10883
10884 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10885 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10886 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10887 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10888 return false;
10889
10890 APSInt Result;
10891 bool DidOverflow = false;
10892
10893 // If the types don't have to match, enlarge all 3 to the largest of them.
10894 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10895 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10896 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10897 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
10898 ResultType->isSignedIntegerOrEnumerationType();
10899 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
10900 ResultType->isSignedIntegerOrEnumerationType();
10901 uint64_t LHSSize = LHS.getBitWidth();
10902 uint64_t RHSSize = RHS.getBitWidth();
10903 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
10904 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
10905
10906 // Add an additional bit if the signedness isn't uniformly agreed to. We
10907 // could do this ONLY if there is a signed and an unsigned that both have
10908 // MaxBits, but the code to check that is pretty nasty. The issue will be
10909 // caught in the shrink-to-result later anyway.
10910 if (IsSigned && !AllSigned)
10911 ++MaxBits;
10912
Erich Keanefc3dfd32019-05-30 21:35:32 +000010913 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
10914 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +000010915 Result = APSInt(MaxBits, !IsSigned);
10916 }
10917
10918 // Find largest int.
10919 switch (BuiltinOp) {
10920 default:
10921 llvm_unreachable("Invalid value for BuiltinOp");
10922 case Builtin::BI__builtin_add_overflow:
10923 case Builtin::BI__builtin_sadd_overflow:
10924 case Builtin::BI__builtin_saddl_overflow:
10925 case Builtin::BI__builtin_saddll_overflow:
10926 case Builtin::BI__builtin_uadd_overflow:
10927 case Builtin::BI__builtin_uaddl_overflow:
10928 case Builtin::BI__builtin_uaddll_overflow:
10929 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10930 : LHS.uadd_ov(RHS, DidOverflow);
10931 break;
10932 case Builtin::BI__builtin_sub_overflow:
10933 case Builtin::BI__builtin_ssub_overflow:
10934 case Builtin::BI__builtin_ssubl_overflow:
10935 case Builtin::BI__builtin_ssubll_overflow:
10936 case Builtin::BI__builtin_usub_overflow:
10937 case Builtin::BI__builtin_usubl_overflow:
10938 case Builtin::BI__builtin_usubll_overflow:
10939 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10940 : LHS.usub_ov(RHS, DidOverflow);
10941 break;
10942 case Builtin::BI__builtin_mul_overflow:
10943 case Builtin::BI__builtin_smul_overflow:
10944 case Builtin::BI__builtin_smull_overflow:
10945 case Builtin::BI__builtin_smulll_overflow:
10946 case Builtin::BI__builtin_umul_overflow:
10947 case Builtin::BI__builtin_umull_overflow:
10948 case Builtin::BI__builtin_umulll_overflow:
10949 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10950 : LHS.umul_ov(RHS, DidOverflow);
10951 break;
10952 }
10953
10954 // In the case where multiple sizes are allowed, truncate and see if
10955 // the values are the same.
10956 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10957 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10958 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10959 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10960 // since it will give us the behavior of a TruncOrSelf in the case where
10961 // its parameter <= its size. We previously set Result to be at least the
10962 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10963 // will work exactly like TruncOrSelf.
10964 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10965 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10966
10967 if (!APSInt::isSameValue(Temp, Result))
10968 DidOverflow = true;
10969 Result = Temp;
10970 }
10971
10972 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000010973 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10974 return false;
Erich Keane00958272018-06-13 20:43:27 +000010975 return Success(DidOverflow, E);
10976 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010977 }
Chris Lattner7174bf32008-07-12 00:38:25 +000010978}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000010979
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010980/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000010981/// object referred to by the lvalue.
10982static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10983 const LValue &LV) {
10984 // A null pointer can be viewed as being "past the end" but we don't
10985 // choose to look at it that way here.
10986 if (!LV.getLValueBase())
10987 return false;
10988
10989 // If the designator is valid and refers to a subobject, we're not pointing
10990 // past the end.
10991 if (!LV.getLValueDesignator().Invalid &&
10992 !LV.getLValueDesignator().isOnePastTheEnd())
10993 return false;
10994
David Majnemerc378ca52015-08-29 08:32:55 +000010995 // A pointer to an incomplete type might be past-the-end if the type's size is
10996 // zero. We cannot tell because the type is incomplete.
10997 QualType Ty = getType(LV.getLValueBase());
10998 if (Ty->isIncompleteType())
10999 return true;
11000
Richard Smithd20f1e62014-10-21 23:01:04 +000011001 // We're a past-the-end pointer if we point to the byte after the object,
11002 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000011003 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000011004 return LV.getLValueOffset() == Size;
11005}
11006
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011007namespace {
Richard Smith11562c52011-10-28 17:51:58 +000011008
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011009/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011010///
11011/// We use a data recursive algorithm for binary operators so that we are able
11012/// to handle extreme cases of chained binary operators without causing stack
11013/// overflow.
11014class DataRecursiveIntBinOpEvaluator {
11015 struct EvalResult {
11016 APValue Val;
11017 bool Failed;
11018
11019 EvalResult() : Failed(false) { }
11020
11021 void swap(EvalResult &RHS) {
11022 Val.swap(RHS.Val);
11023 Failed = RHS.Failed;
11024 RHS.Failed = false;
11025 }
11026 };
11027
11028 struct Job {
11029 const Expr *E;
11030 EvalResult LHSResult; // meaningful only for binary operator expression.
11031 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000011032
David Blaikie73726062015-08-12 23:09:24 +000011033 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000011034 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000011035
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011036 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000011037 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011038 }
George Burgess IV8c892b52016-05-25 22:31:54 +000011039
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011040 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000011041 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011042 };
11043
11044 SmallVector<Job, 16> Queue;
11045
11046 IntExprEvaluator &IntEval;
11047 EvalInfo &Info;
11048 APValue &FinalResult;
11049
11050public:
11051 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11052 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11053
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011054 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011055 /// data recursively.
11056 /// We handle binary operators that are comma, logical, or that have operands
11057 /// with integral or enumeration type.
11058 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011059 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11060 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000011061 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011062 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000011063 }
11064
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011065 bool Traverse(const BinaryOperator *E) {
11066 enqueue(E);
11067 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000011068 while (!Queue.empty())
11069 process(PrevResult);
11070
11071 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011072
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011073 FinalResult.swap(PrevResult.Val);
11074 return true;
11075 }
11076
11077private:
11078 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11079 return IntEval.Success(Value, E, Result);
11080 }
11081 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11082 return IntEval.Success(Value, E, Result);
11083 }
11084 bool Error(const Expr *E) {
11085 return IntEval.Error(E);
11086 }
11087 bool Error(const Expr *E, diag::kind D) {
11088 return IntEval.Error(E, D);
11089 }
11090
11091 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11092 return Info.CCEDiag(E, D);
11093 }
11094
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011095 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011096 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011097 bool &SuppressRHSDiags);
11098
11099 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11100 const BinaryOperator *E, APValue &Result);
11101
11102 void EvaluateExpr(const Expr *E, EvalResult &Result) {
11103 Result.Failed = !Evaluate(Result.Val, Info, E);
11104 if (Result.Failed)
11105 Result.Val = APValue();
11106 }
11107
Richard Trieuba4d0872012-03-21 23:30:30 +000011108 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011109
11110 void enqueue(const Expr *E) {
11111 E = E->IgnoreParens();
11112 Queue.resize(Queue.size()+1);
11113 Queue.back().E = E;
11114 Queue.back().Kind = Job::AnyExprKind;
11115 }
11116};
11117
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011118}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011119
11120bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011121 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011122 bool &SuppressRHSDiags) {
11123 if (E->getOpcode() == BO_Comma) {
11124 // Ignore LHS but note if we could not evaluate it.
11125 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000011126 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011127 return true;
11128 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011129
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011130 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000011131 bool LHSAsBool;
11132 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011133 // We were able to evaluate the LHS, see if we can get away with not
11134 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000011135 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11136 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011137 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011138 }
11139 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000011140 LHSResult.Failed = true;
11141
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011142 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000011143 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000011144 if (!Info.noteSideEffect())
11145 return false;
11146
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011147 // We can't evaluate the LHS; however, sometimes the result
11148 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11149 // Don't ignore RHS and suppress diagnostics from this arm.
11150 SuppressRHSDiags = true;
11151 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011152
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011153 return true;
11154 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011155
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011156 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11157 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000011158
George Burgess IVa145e252016-05-25 22:38:36 +000011159 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011160 return false; // Ignore RHS;
11161
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011162 return true;
11163}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011164
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000011165static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11166 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000011167 // Compute the new offset in the appropriate width, wrapping at 64 bits.
11168 // FIXME: When compiling for a 32-bit target, we should use 32-bit
11169 // offsets.
11170 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11171 CharUnits &Offset = LVal.getLValueOffset();
11172 uint64_t Offset64 = Offset.getQuantity();
11173 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11174 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11175 : Offset64 + Index64);
11176}
11177
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011178bool DataRecursiveIntBinOpEvaluator::
11179 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11180 const BinaryOperator *E, APValue &Result) {
11181 if (E->getOpcode() == BO_Comma) {
11182 if (RHSResult.Failed)
11183 return false;
11184 Result = RHSResult.Val;
11185 return true;
11186 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011187
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011188 if (E->isLogicalOp()) {
11189 bool lhsResult, rhsResult;
11190 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11191 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000011192
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011193 if (LHSIsOK) {
11194 if (RHSIsOK) {
11195 if (E->getOpcode() == BO_LOr)
11196 return Success(lhsResult || rhsResult, E, Result);
11197 else
11198 return Success(lhsResult && rhsResult, E, Result);
11199 }
11200 } else {
11201 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011202 // We can't evaluate the LHS; however, sometimes the result
11203 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11204 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011205 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011206 }
11207 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011208
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011209 return false;
11210 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011211
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011212 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11213 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000011214
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011215 if (LHSResult.Failed || RHSResult.Failed)
11216 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000011217
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011218 const APValue &LHSVal = LHSResult.Val;
11219 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000011220
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011221 // Handle cases like (unsigned long)&a + 4.
11222 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11223 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000011224 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011225 return true;
11226 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011227
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011228 // Handle cases like 4 + (unsigned long)&a
11229 if (E->getOpcode() == BO_Add &&
11230 RHSVal.isLValue() && LHSVal.isInt()) {
11231 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000011232 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011233 return true;
11234 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011235
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011236 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11237 // Handle (intptr_t)&&A - (intptr_t)&&B.
11238 if (!LHSVal.getLValueOffset().isZero() ||
11239 !RHSVal.getLValueOffset().isZero())
11240 return false;
11241 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11242 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11243 if (!LHSExpr || !RHSExpr)
11244 return false;
11245 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11246 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11247 if (!LHSAddrExpr || !RHSAddrExpr)
11248 return false;
11249 // Make sure both labels come from the same function.
11250 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11251 RHSAddrExpr->getLabel()->getDeclContext())
11252 return false;
11253 Result = APValue(LHSAddrExpr, RHSAddrExpr);
11254 return true;
11255 }
Richard Smith43e77732013-05-07 04:50:00 +000011256
11257 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011258 if (!LHSVal.isInt() || !RHSVal.isInt())
11259 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000011260
11261 // Set up the width and signedness manually, in case it can't be deduced
11262 // from the operation we're performing.
11263 // FIXME: Don't do this in the cases where we can deduce it.
11264 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11265 E->getType()->isUnsignedIntegerOrEnumerationType());
11266 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11267 RHSVal.getInt(), Value))
11268 return false;
11269 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011270}
11271
Richard Trieuba4d0872012-03-21 23:30:30 +000011272void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011273 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000011274
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011275 switch (job.Kind) {
11276 case Job::AnyExprKind: {
11277 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11278 if (shouldEnqueue(Bop)) {
11279 job.Kind = Job::BinOpKind;
11280 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011281 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011282 }
11283 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011284
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011285 EvaluateExpr(job.E, Result);
11286 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011287 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011288 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011289
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011290 case Job::BinOpKind: {
11291 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011292 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011293 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011294 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011295 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011296 }
11297 if (SuppressRHSDiags)
11298 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011299 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011300 job.Kind = Job::BinOpVisitedLHSKind;
11301 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011302 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011303 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011304
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011305 case Job::BinOpVisitedLHSKind: {
11306 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11307 EvalResult RHS;
11308 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000011309 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011310 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011311 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011312 }
11313 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011314
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011315 llvm_unreachable("Invalid Job::Kind!");
11316}
11317
George Burgess IV8c892b52016-05-25 22:31:54 +000011318namespace {
11319/// Used when we determine that we should fail, but can keep evaluating prior to
11320/// noting that we had a failure.
11321class DelayedNoteFailureRAII {
11322 EvalInfo &Info;
11323 bool NoteFailure;
11324
11325public:
11326 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11327 : Info(Info), NoteFailure(NoteFailure) {}
11328 ~DelayedNoteFailureRAII() {
11329 if (NoteFailure) {
11330 bool ContinueAfterFailure = Info.noteFailure();
11331 (void)ContinueAfterFailure;
11332 assert(ContinueAfterFailure &&
11333 "Shouldn't have kept evaluating on failure.");
11334 }
11335 }
11336};
11337}
11338
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011339template <class SuccessCB, class AfterCB>
11340static bool
11341EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11342 SuccessCB &&Success, AfterCB &&DoAfter) {
11343 assert(E->isComparisonOp() && "expected comparison operator");
11344 assert((E->getOpcode() == BO_Cmp ||
11345 E->getType()->isIntegralOrEnumerationType()) &&
11346 "unsupported binary expression evaluation");
11347 auto Error = [&](const Expr *E) {
11348 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11349 return false;
11350 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011351
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011352 using CCR = ComparisonCategoryResult;
11353 bool IsRelational = E->isRelationalOp();
11354 bool IsEquality = E->isEqualityOp();
11355 if (E->getOpcode() == BO_Cmp) {
11356 const ComparisonCategoryInfo &CmpInfo =
11357 Info.Ctx.CompCategories.getInfoForType(E->getType());
11358 IsRelational = CmpInfo.isOrdered();
11359 IsEquality = CmpInfo.isEquality();
11360 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000011361
Anders Carlssonacc79812008-11-16 07:17:21 +000011362 QualType LHSTy = E->getLHS()->getType();
11363 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011364
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011365 if (LHSTy->isIntegralOrEnumerationType() &&
11366 RHSTy->isIntegralOrEnumerationType()) {
11367 APSInt LHS, RHS;
11368 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11369 if (!LHSOK && !Info.noteFailure())
11370 return false;
11371 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11372 return false;
11373 if (LHS < RHS)
11374 return Success(CCR::Less, E);
11375 if (LHS > RHS)
11376 return Success(CCR::Greater, E);
11377 return Success(CCR::Equal, E);
11378 }
11379
Leonard Chance1d4f12019-02-21 20:50:09 +000011380 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11381 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11382 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11383
11384 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11385 if (!LHSOK && !Info.noteFailure())
11386 return false;
11387 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11388 return false;
11389 if (LHSFX < RHSFX)
11390 return Success(CCR::Less, E);
11391 if (LHSFX > RHSFX)
11392 return Success(CCR::Greater, E);
11393 return Success(CCR::Equal, E);
11394 }
11395
Chandler Carruthb29a7432014-10-11 11:03:30 +000011396 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011397 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000011398 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000011399 if (E->isAssignmentOp()) {
11400 LValue LV;
11401 EvaluateLValue(E->getLHS(), LV, Info);
11402 LHSOK = false;
11403 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000011404 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11405 if (LHSOK) {
11406 LHS.makeComplexFloat();
11407 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11408 }
11409 } else {
11410 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11411 }
George Burgess IVa145e252016-05-25 22:38:36 +000011412 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011413 return false;
11414
Chandler Carruthb29a7432014-10-11 11:03:30 +000011415 if (E->getRHS()->getType()->isRealFloatingType()) {
11416 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11417 return false;
11418 RHS.makeComplexFloat();
11419 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11420 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011421 return false;
11422
11423 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000011424 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011425 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000011426 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011427 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011428 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11429 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011430 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011431 assert(IsEquality && "invalid complex comparison");
11432 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11433 LHS.getComplexIntImag() == RHS.getComplexIntImag();
11434 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011435 }
11436 }
Mike Stump11289f42009-09-09 15:08:12 +000011437
Anders Carlssonacc79812008-11-16 07:17:21 +000011438 if (LHSTy->isRealFloatingType() &&
11439 RHSTy->isRealFloatingType()) {
11440 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000011441
Richard Smith253c2a32012-01-27 01:14:48 +000011442 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011443 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000011444 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011445
Richard Smith253c2a32012-01-27 01:14:48 +000011446 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000011447 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011448
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011449 assert(E->isComparisonOp() && "Invalid binary operator!");
11450 auto GetCmpRes = [&]() {
11451 switch (LHS.compare(RHS)) {
11452 case APFloat::cmpEqual:
11453 return CCR::Equal;
11454 case APFloat::cmpLessThan:
11455 return CCR::Less;
11456 case APFloat::cmpGreaterThan:
11457 return CCR::Greater;
11458 case APFloat::cmpUnordered:
11459 return CCR::Unordered;
11460 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000011461 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011462 };
11463 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000011464 }
Mike Stump11289f42009-09-09 15:08:12 +000011465
Eli Friedmana38da572009-04-28 19:17:36 +000011466 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011467 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000011468
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011469 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11470 if (!LHSOK && !Info.noteFailure())
11471 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011472
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011473 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11474 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011475
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011476 // Reject differing bases from the normal codepath; we special-case
11477 // comparisons to null.
11478 if (!HasSameBase(LHSValue, RHSValue)) {
11479 // Inequalities and subtractions between unrelated pointers have
11480 // unspecified or undefined behavior.
11481 if (!IsEquality)
11482 return Error(E);
11483 // A constant address may compare equal to the address of a symbol.
11484 // The one exception is that address of an object cannot compare equal
11485 // to a null pointer constant.
11486 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11487 (!RHSValue.Base && !RHSValue.Offset.isZero()))
11488 return Error(E);
11489 // It's implementation-defined whether distinct literals will have
11490 // distinct addresses. In clang, the result of such a comparison is
11491 // unspecified, so it is not a constant expression. However, we do know
11492 // that the address of a literal will be non-null.
11493 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11494 LHSValue.Base && RHSValue.Base)
11495 return Error(E);
11496 // We can't tell whether weak symbols will end up pointing to the same
11497 // object.
11498 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11499 return Error(E);
11500 // We can't compare the address of the start of one object with the
11501 // past-the-end address of another object, per C++ DR1652.
11502 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11503 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11504 (RHSValue.Base && RHSValue.Offset.isZero() &&
11505 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11506 return Error(E);
11507 // We can't tell whether an object is at the same address as another
11508 // zero sized object.
11509 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11510 (LHSValue.Base && isZeroSized(RHSValue)))
11511 return Error(E);
11512 return Success(CCR::Nonequal, E);
11513 }
Eli Friedman64004332009-03-23 04:38:34 +000011514
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011515 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11516 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000011517
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011518 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11519 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000011520
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011521 // C++11 [expr.rel]p3:
11522 // Pointers to void (after pointer conversions) can be compared, with a
11523 // result defined as follows: If both pointers represent the same
11524 // address or are both the null pointer value, the result is true if the
11525 // operator is <= or >= and false otherwise; otherwise the result is
11526 // unspecified.
11527 // We interpret this as applying to pointers to *cv* void.
11528 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11529 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000011530
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011531 // C++11 [expr.rel]p2:
11532 // - If two pointers point to non-static data members of the same object,
11533 // or to subobjects or array elements fo such members, recursively, the
11534 // pointer to the later declared member compares greater provided the
11535 // two members have the same access control and provided their class is
11536 // not a union.
11537 // [...]
11538 // - Otherwise pointer comparisons are unspecified.
11539 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11540 bool WasArrayIndex;
11541 unsigned Mismatch = FindDesignatorMismatch(
11542 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11543 // At the point where the designators diverge, the comparison has a
11544 // specified value if:
11545 // - we are comparing array indices
11546 // - we are comparing fields of a union, or fields with the same access
11547 // Otherwise, the result is unspecified and thus the comparison is not a
11548 // constant expression.
11549 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11550 Mismatch < RHSDesignator.Entries.size()) {
11551 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11552 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11553 if (!LF && !RF)
11554 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11555 else if (!LF)
11556 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011557 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11558 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011559 else if (!RF)
11560 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011561 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11562 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011563 else if (!LF->getParent()->isUnion() &&
11564 LF->getAccess() != RF->getAccess())
11565 Info.CCEDiag(E,
11566 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011567 << LF << LF->getAccess() << RF << RF->getAccess()
11568 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000011569 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011570 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011571
11572 // The comparison here must be unsigned, and performed with the same
11573 // width as the pointer.
11574 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11575 uint64_t CompareLHS = LHSOffset.getQuantity();
11576 uint64_t CompareRHS = RHSOffset.getQuantity();
11577 assert(PtrSize <= 64 && "Unexpected pointer width");
11578 uint64_t Mask = ~0ULL >> (64 - PtrSize);
11579 CompareLHS &= Mask;
11580 CompareRHS &= Mask;
11581
11582 // If there is a base and this is a relational operator, we can only
11583 // compare pointers within the object in question; otherwise, the result
11584 // depends on where the object is located in memory.
11585 if (!LHSValue.Base.isNull() && IsRelational) {
11586 QualType BaseTy = getType(LHSValue.Base);
11587 if (BaseTy->isIncompleteType())
11588 return Error(E);
11589 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11590 uint64_t OffsetLimit = Size.getQuantity();
11591 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11592 return Error(E);
11593 }
11594
11595 if (CompareLHS < CompareRHS)
11596 return Success(CCR::Less, E);
11597 if (CompareLHS > CompareRHS)
11598 return Success(CCR::Greater, E);
11599 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011600 }
Richard Smith7bb00672012-02-01 01:42:44 +000011601
11602 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011603 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000011604 assert(RHSTy->isMemberPointerType() && "invalid comparison");
11605
11606 MemberPtr LHSValue, RHSValue;
11607
11608 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011609 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000011610 return false;
11611
11612 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11613 return false;
11614
11615 // C++11 [expr.eq]p2:
11616 // If both operands are null, they compare equal. Otherwise if only one is
11617 // null, they compare unequal.
11618 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11619 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011620 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011621 }
11622
11623 // Otherwise if either is a pointer to a virtual member function, the
11624 // result is unspecified.
11625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11626 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011627 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011628 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11629 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011630 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011631
11632 // Otherwise they compare equal if and only if they would refer to the
11633 // same member of the same most derived object or the same subobject if
11634 // they were dereferenced with a hypothetical object of the associated
11635 // class type.
11636 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011637 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011638 }
11639
Richard Smithab44d9b2012-02-14 22:35:28 +000011640 if (LHSTy->isNullPtrType()) {
11641 assert(E->isComparisonOp() && "unexpected nullptr operation");
11642 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
11643 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
11644 // are compared, the result is true of the operator is <=, >= or ==, and
11645 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011646 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000011647 }
11648
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011649 return DoAfter();
11650}
11651
11652bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
11653 if (!CheckLiteralType(Info, E))
11654 return false;
11655
11656 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11657 const BinaryOperator *E) {
11658 // Evaluation succeeded. Lookup the information for the comparison category
11659 // type and fetch the VarDecl for the result.
11660 const ComparisonCategoryInfo &CmpInfo =
11661 Info.Ctx.CompCategories.getInfoForType(E->getType());
11662 const VarDecl *VD =
11663 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
11664 // Check and evaluate the result as a constant expression.
11665 LValue LV;
11666 LV.set(VD);
11667 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11668 return false;
11669 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11670 };
11671 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11672 return ExprEvaluatorBaseTy::VisitBinCmp(E);
11673 });
11674}
11675
11676bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11677 // We don't call noteFailure immediately because the assignment happens after
11678 // we evaluate LHS and RHS.
11679 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11680 return Error(E);
11681
11682 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11683 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11684 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11685
11686 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
11687 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011688 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011689
11690 if (E->isComparisonOp()) {
11691 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11692 // comparisons and then translating the result.
11693 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11694 const BinaryOperator *E) {
11695 using CCR = ComparisonCategoryResult;
11696 bool IsEqual = ResKind == CCR::Equal,
11697 IsLess = ResKind == CCR::Less,
11698 IsGreater = ResKind == CCR::Greater;
11699 auto Op = E->getOpcode();
11700 switch (Op) {
11701 default:
11702 llvm_unreachable("unsupported binary operator");
11703 case BO_EQ:
11704 case BO_NE:
11705 return Success(IsEqual == (Op == BO_EQ), E);
11706 case BO_LT: return Success(IsLess, E);
11707 case BO_GT: return Success(IsGreater, E);
11708 case BO_LE: return Success(IsEqual || IsLess, E);
11709 case BO_GE: return Success(IsEqual || IsGreater, E);
11710 }
11711 };
11712 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11713 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11714 });
11715 }
11716
11717 QualType LHSTy = E->getLHS()->getType();
11718 QualType RHSTy = E->getRHS()->getType();
11719
11720 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11721 E->getOpcode() == BO_Sub) {
11722 LValue LHSValue, RHSValue;
11723
11724 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11725 if (!LHSOK && !Info.noteFailure())
11726 return false;
11727
11728 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11729 return false;
11730
11731 // Reject differing bases from the normal codepath; we special-case
11732 // comparisons to null.
11733 if (!HasSameBase(LHSValue, RHSValue)) {
11734 // Handle &&A - &&B.
11735 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11736 return Error(E);
11737 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11738 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11739 if (!LHSExpr || !RHSExpr)
11740 return Error(E);
11741 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11742 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11743 if (!LHSAddrExpr || !RHSAddrExpr)
11744 return Error(E);
11745 // Make sure both labels come from the same function.
11746 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11747 RHSAddrExpr->getLabel()->getDeclContext())
11748 return Error(E);
11749 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11750 }
11751 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11752 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11753
11754 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11755 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11756
11757 // C++11 [expr.add]p6:
11758 // Unless both pointers point to elements of the same array object, or
11759 // one past the last element of the array object, the behavior is
11760 // undefined.
11761 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11762 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11763 RHSDesignator))
11764 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11765
11766 QualType Type = E->getLHS()->getType();
11767 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
11768
11769 CharUnits ElementSize;
11770 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11771 return false;
11772
11773 // As an extension, a type may have zero size (empty struct or union in
11774 // C, array of zero length). Pointer subtraction in such cases has
11775 // undefined behavior, so is not constant.
11776 if (ElementSize.isZero()) {
11777 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11778 << ElementType;
11779 return false;
11780 }
11781
11782 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11783 // and produce incorrect results when it overflows. Such behavior
11784 // appears to be non-conforming, but is common, so perhaps we should
11785 // assume the standard intended for such cases to be undefined behavior
11786 // and check for them.
11787
11788 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11789 // overflow in the final conversion to ptrdiff_t.
11790 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11791 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11792 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11793 false);
11794 APSInt TrueResult = (LHS - RHS) / ElemSize;
11795 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11796
11797 if (Result.extend(65) != TrueResult &&
11798 !HandleOverflow(Info, E, TrueResult, E->getType()))
11799 return false;
11800 return Success(Result, E);
11801 }
11802
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011803 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000011804}
11805
Peter Collingbournee190dee2011-03-11 19:24:49 +000011806/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11807/// a result as the expression's type.
11808bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11809 const UnaryExprOrTypeTraitExpr *E) {
11810 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000011811 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000011812 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000011813 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000011814 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11815 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011816 else
Richard Smith6822bd72018-10-26 19:26:45 +000011817 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11818 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011819 }
Eli Friedman64004332009-03-23 04:38:34 +000011820
Peter Collingbournee190dee2011-03-11 19:24:49 +000011821 case UETT_VecStep: {
11822 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000011823
Peter Collingbournee190dee2011-03-11 19:24:49 +000011824 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000011825 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000011826
Peter Collingbournee190dee2011-03-11 19:24:49 +000011827 // The vec_step built-in functions that take a 3-component
11828 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11829 if (n == 3)
11830 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000011831
Peter Collingbournee190dee2011-03-11 19:24:49 +000011832 return Success(n, E);
11833 } else
11834 return Success(1, E);
11835 }
11836
11837 case UETT_SizeOf: {
11838 QualType SrcTy = E->getTypeOfArgument();
11839 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11840 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000011841 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11842 SrcTy = Ref->getPointeeType();
11843
Richard Smithd62306a2011-11-10 06:34:14 +000011844 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000011845 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000011846 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000011847 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011848 }
Alexey Bataev00396512015-07-02 03:40:19 +000011849 case UETT_OpenMPRequiredSimdAlign:
11850 assert(E->isArgumentType());
11851 return Success(
11852 Info.Ctx.toCharUnitsFromBits(
11853 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11854 .getQuantity(),
11855 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011856 }
11857
11858 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000011859}
11860
Peter Collingbournee9200682011-05-13 03:29:01 +000011861bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011862 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000011863 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000011864 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011865 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000011866 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000011867 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000011868 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000011869 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000011870 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000011871 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000011872 APSInt IdxResult;
11873 if (!EvaluateInteger(Idx, IdxResult, Info))
11874 return false;
11875 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11876 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011877 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011878 CurrentType = AT->getElementType();
11879 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11880 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000011881 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000011882 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011883
James Y Knight7281c352015-12-29 22:31:18 +000011884 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000011885 FieldDecl *MemberDecl = ON.getField();
11886 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011887 if (!RT)
11888 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011889 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011890 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000011891 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000011892 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000011893 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000011894 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000011895 CurrentType = MemberDecl->getType().getNonReferenceType();
11896 break;
11897 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011898
James Y Knight7281c352015-12-29 22:31:18 +000011899 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000011900 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000011901
James Y Knight7281c352015-12-29 22:31:18 +000011902 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000011903 CXXBaseSpecifier *BaseSpec = ON.getBase();
11904 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000011905 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011906
11907 // Find the layout of the class whose base we are looking into.
11908 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011909 if (!RT)
11910 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011911 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011912 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000011913 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11914
11915 // Find the base class itself.
11916 CurrentType = BaseSpec->getType();
11917 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
11918 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011919 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000011920
Douglas Gregord1702062010-04-29 00:18:15 +000011921 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000011922 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000011923 break;
11924 }
Douglas Gregor882211c2010-04-28 22:16:22 +000011925 }
11926 }
Peter Collingbournee9200682011-05-13 03:29:01 +000011927 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011928}
11929
Chris Lattnere13042c2008-07-11 19:10:17 +000011930bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011931 switch (E->getOpcode()) {
11932 default:
11933 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11934 // See C99 6.6p3.
11935 return Error(E);
11936 case UO_Extension:
11937 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11938 // If so, we could clear the diagnostic ID.
11939 return Visit(E->getSubExpr());
11940 case UO_Plus:
11941 // The result is just the value.
11942 return Visit(E->getSubExpr());
11943 case UO_Minus: {
11944 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000011945 return false;
11946 if (!Result.isInt()) return Error(E);
11947 const APSInt &Value = Result.getInt();
11948 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11949 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11950 E->getType()))
11951 return false;
Richard Smithfe800032012-01-31 04:08:20 +000011952 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011953 }
11954 case UO_Not: {
11955 if (!Visit(E->getSubExpr()))
11956 return false;
11957 if (!Result.isInt()) return Error(E);
11958 return Success(~Result.getInt(), E);
11959 }
11960 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000011961 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000011962 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000011963 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000011964 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000011965 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011966 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011967}
Mike Stump11289f42009-09-09 15:08:12 +000011968
Chris Lattner477c4be2008-07-12 01:15:53 +000011969/// HandleCast - This is used to evaluate implicit or explicit casts where the
11970/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000011971bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11972 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011973 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000011974 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011975
Eli Friedmanc757de22011-03-25 00:43:55 +000011976 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000011977 case CK_BaseToDerived:
11978 case CK_DerivedToBase:
11979 case CK_UncheckedDerivedToBase:
11980 case CK_Dynamic:
11981 case CK_ToUnion:
11982 case CK_ArrayToPointerDecay:
11983 case CK_FunctionToPointerDecay:
11984 case CK_NullToPointer:
11985 case CK_NullToMemberPointer:
11986 case CK_BaseToDerivedMemberPointer:
11987 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000011988 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000011989 case CK_ConstructorConversion:
11990 case CK_IntegralToPointer:
11991 case CK_ToVoid:
11992 case CK_VectorSplat:
11993 case CK_IntegralToFloating:
11994 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011995 case CK_CPointerToObjCPointerCast:
11996 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011997 case CK_AnyPointerToBlockPointerCast:
11998 case CK_ObjCObjectLValueCast:
11999 case CK_FloatingRealToComplex:
12000 case CK_FloatingComplexToReal:
12001 case CK_FloatingComplexCast:
12002 case CK_FloatingComplexToIntegralComplex:
12003 case CK_IntegralRealToComplex:
12004 case CK_IntegralComplexCast:
12005 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000012006 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012007 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012008 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012009 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012010 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012011 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012012 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000012013 llvm_unreachable("invalid cast kind for integral value");
12014
Eli Friedman9faf2f92011-03-25 19:07:11 +000012015 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000012016 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012017 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000012018 case CK_ARCProduceObject:
12019 case CK_ARCConsumeObject:
12020 case CK_ARCReclaimReturnedObject:
12021 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012022 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012023 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012024
Richard Smith4ef685b2012-01-17 21:17:26 +000012025 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000012026 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012027 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000012028 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012029 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012030 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012031
12032 case CK_MemberPointerToBoolean:
12033 case CK_PointerToBoolean:
12034 case CK_IntegralToBoolean:
12035 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012036 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000012037 case CK_FloatingComplexToBoolean:
12038 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012039 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000012040 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000012041 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000012042 uint64_t IntResult = BoolResult;
12043 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12044 IntResult = (uint64_t)-1;
12045 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000012046 }
12047
Leonard Chan8f7caae2019-03-06 00:28:43 +000012048 case CK_FixedPointToIntegral: {
12049 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12050 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12051 return false;
12052 bool Overflowed;
12053 llvm::APSInt Result = Src.convertToInt(
12054 Info.Ctx.getIntWidth(DestType),
12055 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12056 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12057 return false;
12058 return Success(Result, E);
12059 }
12060
Leonard Chanb4ba4672018-10-23 17:55:35 +000012061 case CK_FixedPointToBoolean: {
12062 // Unsigned padding does not affect this.
12063 APValue Val;
12064 if (!Evaluate(Val, Info, SubExpr))
12065 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000012066 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000012067 }
12068
Eli Friedmanc757de22011-03-25 00:43:55 +000012069 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000012070 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000012071 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000012072
Eli Friedman742421e2009-02-20 01:15:07 +000012073 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000012074 // Allow casts of address-of-label differences if they are no-ops
12075 // or narrowing. (The narrowing case isn't actually guaranteed to
12076 // be constant-evaluatable except in some narrow cases which are hard
12077 // to detect here. We let it through on the assumption the user knows
12078 // what they are doing.)
12079 if (Result.isAddrLabelDiff())
12080 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000012081 // Only allow casts of lvalues if they are lossless.
12082 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12083 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000012084
Richard Smith911e1422012-01-30 22:27:01 +000012085 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12086 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000012087 }
Mike Stump11289f42009-09-09 15:08:12 +000012088
Eli Friedmanc757de22011-03-25 00:43:55 +000012089 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000012090 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12091
John McCall45d55e42010-05-07 21:00:08 +000012092 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000012093 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000012094 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000012095
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012096 if (LV.getLValueBase()) {
12097 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000012098 // FIXME: Allow a larger integer size than the pointer size, and allow
12099 // narrowing back down to pointer width in subsequent integral casts.
12100 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012101 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012102 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000012103
Richard Smithcf74da72011-11-16 07:18:12 +000012104 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000012105 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012106 return true;
12107 }
12108
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000012109 APSInt AsInt;
12110 APValue V;
12111 LV.moveInto(V);
12112 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12113 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000012114
Richard Smith911e1422012-01-30 22:27:01 +000012115 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000012116 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012117
Eli Friedmanc757de22011-03-25 00:43:55 +000012118 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000012119 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000012120 if (!EvaluateComplex(SubExpr, C, Info))
12121 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000012122 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000012123 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000012124
Eli Friedmanc757de22011-03-25 00:43:55 +000012125 case CK_FloatingToIntegral: {
12126 APFloat F(0.0);
12127 if (!EvaluateFloat(SubExpr, F, Info))
12128 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000012129
Richard Smith357362d2011-12-13 06:39:58 +000012130 APSInt Value;
12131 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12132 return false;
12133 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012134 }
12135 }
Mike Stump11289f42009-09-09 15:08:12 +000012136
Eli Friedmanc757de22011-03-25 00:43:55 +000012137 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000012138}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000012139
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012140bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12141 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000012142 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012143 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12144 return false;
12145 if (!LV.isComplexInt())
12146 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012147 return Success(LV.getComplexIntReal(), E);
12148 }
12149
12150 return Visit(E->getSubExpr());
12151}
12152
Eli Friedman4e7a2412009-02-27 04:45:43 +000012153bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012154 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000012155 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012156 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12157 return false;
12158 if (!LV.isComplexInt())
12159 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012160 return Success(LV.getComplexIntImag(), E);
12161 }
12162
Richard Smith4a678122011-10-24 18:44:57 +000012163 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000012164 return Success(0, E);
12165}
12166
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012167bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12168 return Success(E->getPackLength(), E);
12169}
12170
Sebastian Redl5f0180d2010-09-10 20:55:47 +000012171bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12172 return Success(E->getValue(), E);
12173}
12174
Leonard Chandb01c3a2018-06-20 17:19:40 +000012175bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12176 switch (E->getOpcode()) {
12177 default:
12178 // Invalid unary operators
12179 return Error(E);
12180 case UO_Plus:
12181 // The result is just the value.
12182 return Visit(E->getSubExpr());
12183 case UO_Minus: {
12184 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000012185 if (!Result.isFixedPoint())
12186 return Error(E);
12187 bool Overflowed;
12188 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12189 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12190 return false;
12191 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012192 }
12193 case UO_LNot: {
12194 bool bres;
12195 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12196 return false;
12197 return Success(!bres, E);
12198 }
12199 }
12200}
12201
Leonard Chand3f3e162019-01-18 21:04:25 +000012202bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12203 const Expr *SubExpr = E->getSubExpr();
12204 QualType DestType = E->getType();
12205 assert(DestType->isFixedPointType() &&
12206 "Expected destination type to be a fixed point type");
12207 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12208
12209 switch (E->getCastKind()) {
12210 case CK_FixedPointCast: {
12211 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12212 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12213 return false;
12214 bool Overflowed;
12215 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12216 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12217 return false;
12218 return Success(Result, E);
12219 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000012220 case CK_IntegralToFixedPoint: {
12221 APSInt Src;
12222 if (!EvaluateInteger(SubExpr, Src, Info))
12223 return false;
12224
12225 bool Overflowed;
12226 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12227 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12228
12229 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12230 return false;
12231
12232 return Success(IntResult, E);
12233 }
Leonard Chand3f3e162019-01-18 21:04:25 +000012234 case CK_NoOp:
12235 case CK_LValueToRValue:
12236 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12237 default:
12238 return Error(E);
12239 }
12240}
12241
12242bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12243 const Expr *LHS = E->getLHS();
12244 const Expr *RHS = E->getRHS();
12245 FixedPointSemantics ResultFXSema =
12246 Info.Ctx.getFixedPointSemantics(E->getType());
12247
12248 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12249 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12250 return false;
12251 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12252 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12253 return false;
12254
12255 switch (E->getOpcode()) {
12256 case BO_Add: {
12257 bool AddOverflow, ConversionOverflow;
12258 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12259 .convert(ResultFXSema, &ConversionOverflow);
12260 if ((AddOverflow || ConversionOverflow) &&
12261 !HandleOverflow(Info, E, Result, E->getType()))
12262 return false;
12263 return Success(Result, E);
12264 }
12265 default:
12266 return false;
12267 }
12268 llvm_unreachable("Should've exited before this");
12269}
12270
Chris Lattner05706e882008-07-11 18:11:29 +000012271//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000012272// Float Evaluation
12273//===----------------------------------------------------------------------===//
12274
12275namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012276class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012277 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000012278 APFloat &Result;
12279public:
12280 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012281 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000012282
Richard Smith2e312c82012-03-03 22:46:17 +000012283 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012284 Result = V.getFloat();
12285 return true;
12286 }
Eli Friedman24c01542008-08-22 00:06:13 +000012287
Richard Smithfddd3842011-12-30 21:15:51 +000012288 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000012289 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12290 return true;
12291 }
12292
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012293 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012294
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012295 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012296 bool VisitBinaryOperator(const BinaryOperator *E);
12297 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012298 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000012299
John McCallb1fb0d32010-05-07 22:08:54 +000012300 bool VisitUnaryReal(const UnaryOperator *E);
12301 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000012302
Richard Smithfddd3842011-12-30 21:15:51 +000012303 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000012304};
12305} // end anonymous namespace
12306
12307static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012308 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012309 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000012310}
12311
Jay Foad39c79802011-01-12 09:06:06 +000012312static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000012313 QualType ResultTy,
12314 const Expr *Arg,
12315 bool SNaN,
12316 llvm::APFloat &Result) {
12317 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12318 if (!S) return false;
12319
12320 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12321
12322 llvm::APInt fill;
12323
12324 // Treat empty strings as if they were zero.
12325 if (S->getString().empty())
12326 fill = llvm::APInt(32, 0);
12327 else if (S->getString().getAsInteger(0, fill))
12328 return false;
12329
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000012330 if (Context.getTargetInfo().isNan2008()) {
12331 if (SNaN)
12332 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12333 else
12334 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12335 } else {
12336 // Prior to IEEE 754-2008, architectures were allowed to choose whether
12337 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12338 // a different encoding to what became a standard in 2008, and for pre-
12339 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12340 // sNaN. This is now known as "legacy NaN" encoding.
12341 if (SNaN)
12342 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12343 else
12344 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12345 }
12346
John McCall16291492010-02-28 13:00:19 +000012347 return true;
12348}
12349
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012350bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000012351 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012352 default:
12353 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12354
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012355 case Builtin::BI__builtin_huge_val:
12356 case Builtin::BI__builtin_huge_valf:
12357 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012358 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012359 case Builtin::BI__builtin_inf:
12360 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012361 case Builtin::BI__builtin_infl:
12362 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012363 const llvm::fltSemantics &Sem =
12364 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000012365 Result = llvm::APFloat::getInf(Sem);
12366 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012367 }
Mike Stump11289f42009-09-09 15:08:12 +000012368
John McCall16291492010-02-28 13:00:19 +000012369 case Builtin::BI__builtin_nans:
12370 case Builtin::BI__builtin_nansf:
12371 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012372 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012373 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12374 true, Result))
12375 return Error(E);
12376 return true;
John McCall16291492010-02-28 13:00:19 +000012377
Chris Lattner0b7282e2008-10-06 06:31:58 +000012378 case Builtin::BI__builtin_nan:
12379 case Builtin::BI__builtin_nanf:
12380 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012381 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000012382 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000012383 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000012384 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12385 false, Result))
12386 return Error(E);
12387 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012388
12389 case Builtin::BI__builtin_fabs:
12390 case Builtin::BI__builtin_fabsf:
12391 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012392 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012393 if (!EvaluateFloat(E->getArg(0), Result, Info))
12394 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012395
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012396 if (Result.isNegative())
12397 Result.changeSign();
12398 return true;
12399
Richard Smith8889a3d2013-06-13 06:26:32 +000012400 // FIXME: Builtin::BI__builtin_powi
12401 // FIXME: Builtin::BI__builtin_powif
12402 // FIXME: Builtin::BI__builtin_powil
12403
Mike Stump11289f42009-09-09 15:08:12 +000012404 case Builtin::BI__builtin_copysign:
12405 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012406 case Builtin::BI__builtin_copysignl:
12407 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012408 APFloat RHS(0.);
12409 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12410 !EvaluateFloat(E->getArg(1), RHS, Info))
12411 return false;
12412 Result.copySign(RHS);
12413 return true;
12414 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012415 }
12416}
12417
John McCallb1fb0d32010-05-07 22:08:54 +000012418bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012419 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12420 ComplexValue CV;
12421 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12422 return false;
12423 Result = CV.FloatReal;
12424 return true;
12425 }
12426
12427 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000012428}
12429
12430bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012431 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12432 ComplexValue CV;
12433 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12434 return false;
12435 Result = CV.FloatImag;
12436 return true;
12437 }
12438
Richard Smith4a678122011-10-24 18:44:57 +000012439 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000012440 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12441 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000012442 return true;
12443}
12444
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012445bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012446 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012447 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012448 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000012449 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000012450 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000012451 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12452 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012453 Result.changeSign();
12454 return true;
12455 }
12456}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012457
Eli Friedman24c01542008-08-22 00:06:13 +000012458bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012459 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12460 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000012461
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012462 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000012463 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000012464 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000012465 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000012466 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12467 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000012468}
12469
12470bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12471 Result = E->getValue();
12472 return true;
12473}
12474
Peter Collingbournee9200682011-05-13 03:29:01 +000012475bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12476 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000012477
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012478 switch (E->getCastKind()) {
12479 default:
Richard Smith11562c52011-10-28 17:51:58 +000012480 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012481
12482 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012483 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000012484 return EvaluateInteger(SubExpr, IntResult, Info) &&
12485 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12486 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012487 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012488
12489 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012490 if (!Visit(SubExpr))
12491 return false;
Richard Smith357362d2011-12-13 06:39:58 +000012492 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12493 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012494 }
John McCalld7646252010-11-14 08:17:51 +000012495
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012496 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000012497 ComplexValue V;
12498 if (!EvaluateComplex(SubExpr, V, Info))
12499 return false;
12500 Result = V.getComplexFloatReal();
12501 return true;
12502 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012503 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012504}
12505
Eli Friedman24c01542008-08-22 00:06:13 +000012506//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012507// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000012508//===----------------------------------------------------------------------===//
12509
12510namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012511class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012512 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000012513 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000012514
Anders Carlsson537969c2008-11-16 20:27:53 +000012515public:
John McCall93d91dc2010-05-07 17:22:02 +000012516 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012517 : ExprEvaluatorBaseTy(info), Result(Result) {}
12518
Richard Smith2e312c82012-03-03 22:46:17 +000012519 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012520 Result.setFrom(V);
12521 return true;
12522 }
Mike Stump11289f42009-09-09 15:08:12 +000012523
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012524 bool ZeroInitialization(const Expr *E);
12525
Anders Carlsson537969c2008-11-16 20:27:53 +000012526 //===--------------------------------------------------------------------===//
12527 // Visitor Methods
12528 //===--------------------------------------------------------------------===//
12529
Peter Collingbournee9200682011-05-13 03:29:01 +000012530 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012531 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000012532 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012533 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012534 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012535};
12536} // end anonymous namespace
12537
John McCall93d91dc2010-05-07 17:22:02 +000012538static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12539 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012540 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012541 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012542}
12543
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012544bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000012545 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012546 if (ElemTy->isRealFloatingType()) {
12547 Result.makeComplexFloat();
12548 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12549 Result.FloatReal = Zero;
12550 Result.FloatImag = Zero;
12551 } else {
12552 Result.makeComplexInt();
12553 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12554 Result.IntReal = Zero;
12555 Result.IntImag = Zero;
12556 }
12557 return true;
12558}
12559
Peter Collingbournee9200682011-05-13 03:29:01 +000012560bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12561 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012562
12563 if (SubExpr->getType()->isRealFloatingType()) {
12564 Result.makeComplexFloat();
12565 APFloat &Imag = Result.FloatImag;
12566 if (!EvaluateFloat(SubExpr, Imag, Info))
12567 return false;
12568
12569 Result.FloatReal = APFloat(Imag.getSemantics());
12570 return true;
12571 } else {
12572 assert(SubExpr->getType()->isIntegerType() &&
12573 "Unexpected imaginary literal.");
12574
12575 Result.makeComplexInt();
12576 APSInt &Imag = Result.IntImag;
12577 if (!EvaluateInteger(SubExpr, Imag, Info))
12578 return false;
12579
12580 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12581 return true;
12582 }
12583}
12584
Peter Collingbournee9200682011-05-13 03:29:01 +000012585bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012586
John McCallfcef3cf2010-12-14 17:51:41 +000012587 switch (E->getCastKind()) {
12588 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012589 case CK_BaseToDerived:
12590 case CK_DerivedToBase:
12591 case CK_UncheckedDerivedToBase:
12592 case CK_Dynamic:
12593 case CK_ToUnion:
12594 case CK_ArrayToPointerDecay:
12595 case CK_FunctionToPointerDecay:
12596 case CK_NullToPointer:
12597 case CK_NullToMemberPointer:
12598 case CK_BaseToDerivedMemberPointer:
12599 case CK_DerivedToBaseMemberPointer:
12600 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000012601 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000012602 case CK_ConstructorConversion:
12603 case CK_IntegralToPointer:
12604 case CK_PointerToIntegral:
12605 case CK_PointerToBoolean:
12606 case CK_ToVoid:
12607 case CK_VectorSplat:
12608 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012609 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000012610 case CK_IntegralToBoolean:
12611 case CK_IntegralToFloating:
12612 case CK_FloatingToIntegral:
12613 case CK_FloatingToBoolean:
12614 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000012615 case CK_CPointerToObjCPointerCast:
12616 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012617 case CK_AnyPointerToBlockPointerCast:
12618 case CK_ObjCObjectLValueCast:
12619 case CK_FloatingComplexToReal:
12620 case CK_FloatingComplexToBoolean:
12621 case CK_IntegralComplexToReal:
12622 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000012623 case CK_ARCProduceObject:
12624 case CK_ARCConsumeObject:
12625 case CK_ARCReclaimReturnedObject:
12626 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012627 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000012628 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012629 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012630 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012631 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012632 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012633 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000012634 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012635 case CK_FixedPointToIntegral:
12636 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000012637 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000012638
John McCallfcef3cf2010-12-14 17:51:41 +000012639 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012640 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000012641 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012642 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012643 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012644
12645 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012646 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012647 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012648 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012649
12650 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012651 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000012652 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012653 return false;
12654
John McCallfcef3cf2010-12-14 17:51:41 +000012655 Result.makeComplexFloat();
12656 Result.FloatImag = APFloat(Real.getSemantics());
12657 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012658 }
12659
John McCallfcef3cf2010-12-14 17:51:41 +000012660 case CK_FloatingComplexCast: {
12661 if (!Visit(E->getSubExpr()))
12662 return false;
12663
12664 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12665 QualType From
12666 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12667
Richard Smith357362d2011-12-13 06:39:58 +000012668 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
12669 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012670 }
12671
12672 case CK_FloatingComplexToIntegralComplex: {
12673 if (!Visit(E->getSubExpr()))
12674 return false;
12675
12676 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12677 QualType From
12678 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12679 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000012680 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12681 To, Result.IntReal) &&
12682 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12683 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012684 }
12685
12686 case CK_IntegralRealToComplex: {
12687 APSInt &Real = Result.IntReal;
12688 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12689 return false;
12690
12691 Result.makeComplexInt();
12692 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12693 return true;
12694 }
12695
12696 case CK_IntegralComplexCast: {
12697 if (!Visit(E->getSubExpr()))
12698 return false;
12699
12700 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12701 QualType From
12702 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12703
Richard Smith911e1422012-01-30 22:27:01 +000012704 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12705 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012706 return true;
12707 }
12708
12709 case CK_IntegralComplexToFloatingComplex: {
12710 if (!Visit(E->getSubExpr()))
12711 return false;
12712
Ted Kremenek28831752012-08-23 20:46:57 +000012713 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012714 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000012715 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012716 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000012717 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12718 To, Result.FloatReal) &&
12719 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12720 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012721 }
12722 }
12723
12724 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012725}
12726
John McCall93d91dc2010-05-07 17:22:02 +000012727bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012728 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000012729 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12730
Chandler Carrutha216cad2014-10-11 00:57:18 +000012731 // Track whether the LHS or RHS is real at the type system level. When this is
12732 // the case we can simplify our evaluation strategy.
12733 bool LHSReal = false, RHSReal = false;
12734
12735 bool LHSOK;
12736 if (E->getLHS()->getType()->isRealFloatingType()) {
12737 LHSReal = true;
12738 APFloat &Real = Result.FloatReal;
12739 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12740 if (LHSOK) {
12741 Result.makeComplexFloat();
12742 Result.FloatImag = APFloat(Real.getSemantics());
12743 }
12744 } else {
12745 LHSOK = Visit(E->getLHS());
12746 }
George Burgess IVa145e252016-05-25 22:38:36 +000012747 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000012748 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012749
John McCall93d91dc2010-05-07 17:22:02 +000012750 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012751 if (E->getRHS()->getType()->isRealFloatingType()) {
12752 RHSReal = true;
12753 APFloat &Real = RHS.FloatReal;
12754 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12755 return false;
12756 RHS.makeComplexFloat();
12757 RHS.FloatImag = APFloat(Real.getSemantics());
12758 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000012759 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012760
Chandler Carrutha216cad2014-10-11 00:57:18 +000012761 assert(!(LHSReal && RHSReal) &&
12762 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012763 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012764 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012765 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012766 if (Result.isComplexFloat()) {
12767 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12768 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012769 if (LHSReal)
12770 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12771 else if (!RHSReal)
12772 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12773 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012774 } else {
12775 Result.getComplexIntReal() += RHS.getComplexIntReal();
12776 Result.getComplexIntImag() += RHS.getComplexIntImag();
12777 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012778 break;
John McCalle3027922010-08-25 11:45:40 +000012779 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012780 if (Result.isComplexFloat()) {
12781 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12782 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012783 if (LHSReal) {
12784 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12785 Result.getComplexFloatImag().changeSign();
12786 } else if (!RHSReal) {
12787 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12788 APFloat::rmNearestTiesToEven);
12789 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012790 } else {
12791 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12792 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12793 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012794 break;
John McCalle3027922010-08-25 11:45:40 +000012795 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012796 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012797 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012798 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012799 // following naming scheme:
12800 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000012801 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012802 APFloat &A = LHS.getComplexFloatReal();
12803 APFloat &B = LHS.getComplexFloatImag();
12804 APFloat &C = RHS.getComplexFloatReal();
12805 APFloat &D = RHS.getComplexFloatImag();
12806 APFloat &ResR = Result.getComplexFloatReal();
12807 APFloat &ResI = Result.getComplexFloatImag();
12808 if (LHSReal) {
12809 assert(!RHSReal && "Cannot have two real operands for a complex op!");
12810 ResR = A * C;
12811 ResI = A * D;
12812 } else if (RHSReal) {
12813 ResR = C * A;
12814 ResI = C * B;
12815 } else {
12816 // In the fully general case, we need to handle NaNs and infinities
12817 // robustly.
12818 APFloat AC = A * C;
12819 APFloat BD = B * D;
12820 APFloat AD = A * D;
12821 APFloat BC = B * C;
12822 ResR = AC - BD;
12823 ResI = AD + BC;
12824 if (ResR.isNaN() && ResI.isNaN()) {
12825 bool Recalc = false;
12826 if (A.isInfinity() || B.isInfinity()) {
12827 A = APFloat::copySign(
12828 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12829 B = APFloat::copySign(
12830 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12831 if (C.isNaN())
12832 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12833 if (D.isNaN())
12834 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12835 Recalc = true;
12836 }
12837 if (C.isInfinity() || D.isInfinity()) {
12838 C = APFloat::copySign(
12839 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12840 D = APFloat::copySign(
12841 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12842 if (A.isNaN())
12843 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12844 if (B.isNaN())
12845 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12846 Recalc = true;
12847 }
12848 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12849 AD.isInfinity() || BC.isInfinity())) {
12850 if (A.isNaN())
12851 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12852 if (B.isNaN())
12853 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12854 if (C.isNaN())
12855 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12856 if (D.isNaN())
12857 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12858 Recalc = true;
12859 }
12860 if (Recalc) {
12861 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12862 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12863 }
12864 }
12865 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012866 } else {
John McCall93d91dc2010-05-07 17:22:02 +000012867 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000012868 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012869 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12870 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000012871 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012872 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12873 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12874 }
12875 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012876 case BO_Div:
12877 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012878 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012879 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012880 // following naming scheme:
12881 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012882 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012883 APFloat &A = LHS.getComplexFloatReal();
12884 APFloat &B = LHS.getComplexFloatImag();
12885 APFloat &C = RHS.getComplexFloatReal();
12886 APFloat &D = RHS.getComplexFloatImag();
12887 APFloat &ResR = Result.getComplexFloatReal();
12888 APFloat &ResI = Result.getComplexFloatImag();
12889 if (RHSReal) {
12890 ResR = A / C;
12891 ResI = B / C;
12892 } else {
12893 if (LHSReal) {
12894 // No real optimizations we can do here, stub out with zero.
12895 B = APFloat::getZero(A.getSemantics());
12896 }
12897 int DenomLogB = 0;
12898 APFloat MaxCD = maxnum(abs(C), abs(D));
12899 if (MaxCD.isFinite()) {
12900 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000012901 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
12902 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012903 }
12904 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000012905 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
12906 APFloat::rmNearestTiesToEven);
12907 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
12908 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012909 if (ResR.isNaN() && ResI.isNaN()) {
12910 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
12911 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
12912 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
12913 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
12914 D.isFinite()) {
12915 A = APFloat::copySign(
12916 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12917 B = APFloat::copySign(
12918 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12919 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
12920 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
12921 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
12922 C = APFloat::copySign(
12923 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12924 D = APFloat::copySign(
12925 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12926 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
12927 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12928 }
12929 }
12930 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012931 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012932 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12933 return Error(E, diag::note_expr_divide_by_zero);
12934
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012935 ComplexValue LHS = Result;
12936 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12937 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12938 Result.getComplexIntReal() =
12939 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12940 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12941 Result.getComplexIntImag() =
12942 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12943 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12944 }
12945 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012946 }
12947
John McCall93d91dc2010-05-07 17:22:02 +000012948 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012949}
12950
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012951bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12952 // Get the operand value into 'Result'.
12953 if (!Visit(E->getSubExpr()))
12954 return false;
12955
12956 switch (E->getOpcode()) {
12957 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012958 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012959 case UO_Extension:
12960 return true;
12961 case UO_Plus:
12962 // The result is always just the subexpr.
12963 return true;
12964 case UO_Minus:
12965 if (Result.isComplexFloat()) {
12966 Result.getComplexFloatReal().changeSign();
12967 Result.getComplexFloatImag().changeSign();
12968 }
12969 else {
12970 Result.getComplexIntReal() = -Result.getComplexIntReal();
12971 Result.getComplexIntImag() = -Result.getComplexIntImag();
12972 }
12973 return true;
12974 case UO_Not:
12975 if (Result.isComplexFloat())
12976 Result.getComplexFloatImag().changeSign();
12977 else
12978 Result.getComplexIntImag() = -Result.getComplexIntImag();
12979 return true;
12980 }
12981}
12982
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012983bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12984 if (E->getNumInits() == 2) {
12985 if (E->getType()->isComplexType()) {
12986 Result.makeComplexFloat();
12987 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12988 return false;
12989 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12990 return false;
12991 } else {
12992 Result.makeComplexInt();
12993 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12994 return false;
12995 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12996 return false;
12997 }
12998 return true;
12999 }
13000 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13001}
13002
Anders Carlsson537969c2008-11-16 20:27:53 +000013003//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000013004// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13005// implicit conversion.
13006//===----------------------------------------------------------------------===//
13007
13008namespace {
13009class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000013010 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000013011 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000013012 APValue &Result;
13013public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000013014 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13015 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000013016
13017 bool Success(const APValue &V, const Expr *E) {
13018 Result = V;
13019 return true;
13020 }
13021
13022 bool ZeroInitialization(const Expr *E) {
13023 ImplicitValueInitExpr VIE(
13024 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000013025 // For atomic-qualified class (and array) types in C++, initialize the
13026 // _Atomic-wrapped subobject directly, in-place.
13027 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13028 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000013029 }
13030
13031 bool VisitCastExpr(const CastExpr *E) {
13032 switch (E->getCastKind()) {
13033 default:
13034 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13035 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000013036 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13037 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000013038 }
13039 }
13040};
13041} // end anonymous namespace
13042
Richard Smith64cb9ca2017-02-22 22:09:50 +000013043static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13044 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000013045 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000013046 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000013047}
13048
13049//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000013050// Void expression evaluation, primarily for a cast to void on the LHS of a
13051// comma operator
13052//===----------------------------------------------------------------------===//
13053
13054namespace {
13055class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000013056 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000013057public:
13058 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13059
Richard Smith2e312c82012-03-03 22:46:17 +000013060 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000013061
Richard Smith7cd577b2017-08-17 19:35:50 +000013062 bool ZeroInitialization(const Expr *E) { return true; }
13063
Richard Smith42d3af92011-12-07 00:43:50 +000013064 bool VisitCastExpr(const CastExpr *E) {
13065 switch (E->getCastKind()) {
13066 default:
13067 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13068 case CK_ToVoid:
13069 VisitIgnoredValue(E->getSubExpr());
13070 return true;
13071 }
13072 }
Hal Finkela8443c32014-07-17 14:49:58 +000013073
13074 bool VisitCallExpr(const CallExpr *E) {
13075 switch (E->getBuiltinCallee()) {
Hal Finkela8443c32014-07-17 14:49:58 +000013076 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000013077 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000013078 // The argument is not evaluated!
13079 return true;
Richard Smith19ad5232019-10-03 00:39:33 +000013080
13081 case Builtin::BI__builtin_operator_delete:
13082 return HandleOperatorDeleteCall(Info, E);
13083
13084 default:
13085 break;
Hal Finkela8443c32014-07-17 14:49:58 +000013086 }
Richard Smith19ad5232019-10-03 00:39:33 +000013087
13088 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Hal Finkela8443c32014-07-17 14:49:58 +000013089 }
Richard Smithda1b4342019-09-27 01:26:47 +000013090
13091 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
Richard Smith42d3af92011-12-07 00:43:50 +000013092};
13093} // end anonymous namespace
13094
Richard Smithda1b4342019-09-27 01:26:47 +000013095bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13096 // We cannot speculatively evaluate a delete expression.
13097 if (Info.SpeculativeEvaluationDepth)
13098 return false;
13099
13100 FunctionDecl *OperatorDelete = E->getOperatorDelete();
13101 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13102 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13103 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13104 return false;
13105 }
13106
13107 const Expr *Arg = E->getArgument();
13108
13109 LValue Pointer;
13110 if (!EvaluatePointer(Arg, Pointer, Info))
13111 return false;
13112 if (Pointer.Designator.Invalid)
13113 return false;
13114
13115 // Deleting a null pointer has no effect.
13116 if (Pointer.isNullPointer()) {
13117 // This is the only case where we need to produce an extension warning:
13118 // the only other way we can succeed is if we find a dynamic allocation,
13119 // and we will have warned when we allocated it in that case.
13120 if (!Info.getLangOpts().CPlusPlus2a)
13121 Info.CCEDiag(E, diag::note_constexpr_new);
13122 return true;
13123 }
13124
Richard Smith19ad5232019-10-03 00:39:33 +000013125 Optional<DynAlloc *> Alloc = CheckDeleteKind(
13126 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13127 if (!Alloc)
Richard Smithda1b4342019-09-27 01:26:47 +000013128 return false;
Richard Smithda1b4342019-09-27 01:26:47 +000013129 QualType AllocType = Pointer.Base.getDynamicAllocType();
13130
Richard Smithda1b4342019-09-27 01:26:47 +000013131 // For the non-array case, the designator must be empty if the static type
13132 // does not have a virtual destructor.
13133 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13134 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13135 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13136 << Arg->getType()->getPointeeType() << AllocType;
13137 return false;
13138 }
13139
Richard Smith61422f92019-09-27 20:24:36 +000013140 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13141 (*Alloc)->Value, AllocType))
Richard Smithda1b4342019-09-27 01:26:47 +000013142 return false;
13143
Richard Smith19ad5232019-10-03 00:39:33 +000013144 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
Richard Smithda1b4342019-09-27 01:26:47 +000013145 // The element was already erased. This means the destructor call also
13146 // deleted the object.
13147 // FIXME: This probably results in undefined behavior before we get this
13148 // far, and should be diagnosed elsewhere first.
13149 Info.FFDiag(E, diag::note_constexpr_double_delete);
13150 return false;
13151 }
13152
13153 return true;
13154}
13155
Richard Smith42d3af92011-12-07 00:43:50 +000013156static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13157 assert(E->isRValue() && E->getType()->isVoidType());
13158 return VoidExprEvaluator(Info).Visit(E);
13159}
13160
13161//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000013162// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000013163//===----------------------------------------------------------------------===//
13164
Richard Smith2e312c82012-03-03 22:46:17 +000013165static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000013166 // In C, function designators are not lvalues, but we evaluate them as if they
13167 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000013168 QualType T = E->getType();
13169 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000013170 LValue LV;
13171 if (!EvaluateLValue(E, LV, Info))
13172 return false;
13173 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000013174 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000013175 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000013176 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013177 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000013178 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013179 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013180 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000013181 LValue LV;
13182 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013183 return false;
Richard Smith725810a2011-10-16 21:26:27 +000013184 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000013185 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000013186 llvm::APFloat F(0.0);
13187 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013188 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000013189 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000013190 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000013191 ComplexValue C;
13192 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013193 return false;
Richard Smith725810a2011-10-16 21:26:27 +000013194 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000013195 } else if (T->isFixedPointType()) {
13196 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013197 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000013198 MemberPtr P;
13199 if (!EvaluateMemberPointer(E, P, Info))
13200 return false;
13201 P.moveInto(Result);
13202 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000013203 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000013204 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013205 APValue &Value =
13206 Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000013207 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000013208 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000013209 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000013210 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000013211 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013212 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000013213 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000013214 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000013215 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000013216 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013217 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000013218 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000013219 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000013220 if (!EvaluateVoid(E, Info))
13221 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013222 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000013223 QualType Unqual = T.getAtomicUnqualifiedType();
13224 if (Unqual->isArrayType() || Unqual->isRecordType()) {
13225 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013226 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013227 if (!EvaluateAtomic(E, &LV, Value, Info))
13228 return false;
13229 } else {
13230 if (!EvaluateAtomic(E, nullptr, Result, Info))
13231 return false;
13232 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013233 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000013234 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000013235 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013236 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000013237 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000013238 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013239 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013240
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000013241 return true;
13242}
13243
Richard Smithb228a862012-02-15 02:18:13 +000013244/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13245/// cases, the in-place evaluation is essential, since later initializers for
13246/// an object can indirectly refer to subobjects which were initialized earlier.
13247static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000013248 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000013249 assert(!E->isValueDependent());
13250
Richard Smith7525ff62013-05-09 07:14:00 +000013251 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000013252 return false;
13253
13254 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000013255 // Evaluate arrays and record types in-place, so that later initializers can
13256 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000013257 QualType T = E->getType();
13258 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000013259 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013260 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000013261 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013262 else if (T->isAtomicType()) {
13263 QualType Unqual = T.getAtomicUnqualifiedType();
13264 if (Unqual->isArrayType() || Unqual->isRecordType())
13265 return EvaluateAtomic(E, &This, Result, Info);
13266 }
Richard Smithed5165f2011-11-04 05:33:44 +000013267 }
13268
13269 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000013270 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000013271}
13272
Richard Smithf57d8cb2011-12-09 22:58:01 +000013273/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13274/// lvalue-to-rvalue cast if it is an lvalue.
13275static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Licker950b70d2019-09-13 09:46:16 +000013276 if (Info.EnableNewConstInterp) {
13277 auto &InterpCtx = Info.Ctx.getInterpContext();
13278 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
13279 case interp::InterpResult::Success:
13280 return true;
13281 case interp::InterpResult::Fail:
13282 return false;
13283 case interp::InterpResult::Bail:
13284 break;
13285 }
13286 }
13287
James Dennett0492ef02014-03-14 17:44:10 +000013288 if (E->getType().isNull())
13289 return false;
13290
Nick Lewyckyc190f962017-05-02 01:06:16 +000013291 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000013292 return false;
13293
Richard Smith2e312c82012-03-03 22:46:17 +000013294 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000013295 return false;
13296
13297 if (E->isGLValue()) {
13298 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000013299 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000013300 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000013301 return false;
13302 }
13303
Richard Smith2e312c82012-03-03 22:46:17 +000013304 // Check this core constant expression is a constant expression.
Richard Smithda1b4342019-09-27 01:26:47 +000013305 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13306 CheckMemoryLeaks(Info);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013307}
Richard Smith11562c52011-10-28 17:51:58 +000013308
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013309static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000013310 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013311 // Fast-path evaluations of integer literals, since we sometimes see files
13312 // containing vast quantities of these.
13313 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13314 Result.Val = APValue(APSInt(L->getValue(),
13315 L->getType()->isUnsignedIntegerType()));
13316 IsConst = true;
13317 return true;
13318 }
James Dennett0492ef02014-03-14 17:44:10 +000013319
13320 // This case should be rare, but we need to check it before we check on
13321 // the type below.
13322 if (Exp->getType().isNull()) {
13323 IsConst = false;
13324 return true;
13325 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013326
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013327 // FIXME: Evaluating values of large array and record types can cause
13328 // performance problems. Only do so in C++11 for now.
13329 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13330 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000013331 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013332 IsConst = false;
13333 return true;
13334 }
13335 return false;
13336}
13337
Fangrui Song407659a2018-11-30 23:41:18 +000013338static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13339 Expr::SideEffectsKind SEK) {
13340 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13341 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13342}
13343
13344static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13345 const ASTContext &Ctx, EvalInfo &Info) {
13346 bool IsConst;
13347 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13348 return IsConst;
13349
13350 return EvaluateAsRValue(Info, E, Result.Val);
13351}
13352
13353static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13354 const ASTContext &Ctx,
13355 Expr::SideEffectsKind AllowSideEffects,
13356 EvalInfo &Info) {
13357 if (!E->getType()->isIntegralOrEnumerationType())
13358 return false;
13359
13360 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13361 !ExprResult.Val.isInt() ||
13362 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13363 return false;
13364
13365 return true;
13366}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013367
Leonard Chand3f3e162019-01-18 21:04:25 +000013368static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13369 const ASTContext &Ctx,
13370 Expr::SideEffectsKind AllowSideEffects,
13371 EvalInfo &Info) {
13372 if (!E->getType()->isFixedPointType())
13373 return false;
13374
13375 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13376 return false;
13377
13378 if (!ExprResult.Val.isFixedPoint() ||
13379 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13380 return false;
13381
13382 return true;
13383}
13384
Richard Smith7b553f12011-10-29 00:50:52 +000013385/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000013386/// any crazy technique (that has nothing to do with language standards) that
13387/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000013388/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13389/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000013390bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13391 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013392 assert(!isValueDependent() &&
13393 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000013394 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013395 Info.InConstantContext = InConstantContext;
13396 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000013397}
13398
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013399bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13400 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013401 assert(!isValueDependent() &&
13402 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000013403 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013404 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000013405 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000013406}
13407
Fangrui Song407659a2018-11-30 23:41:18 +000013408bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013409 SideEffectsKind AllowSideEffects,
13410 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013411 assert(!isValueDependent() &&
13412 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000013413 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013414 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000013415 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000013416}
13417
Leonard Chand3f3e162019-01-18 21:04:25 +000013418bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013419 SideEffectsKind AllowSideEffects,
13420 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013421 assert(!isValueDependent() &&
13422 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000013423 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013424 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000013425 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13426}
13427
Richard Trieube234c32016-04-21 21:04:55 +000013428bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013429 SideEffectsKind AllowSideEffects,
13430 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013431 assert(!isValueDependent() &&
13432 "Expression evaluator can't be called on a dependent expression.");
13433
Richard Trieube234c32016-04-21 21:04:55 +000013434 if (!getType()->isRealFloatingType())
13435 return false;
13436
13437 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013438 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13439 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000013440 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000013441 return false;
13442
13443 Result = ExprResult.Val.getFloat();
13444 return true;
13445}
13446
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013447bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13448 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013449 assert(!isValueDependent() &&
13450 "Expression evaluator can't be called on a dependent expression.");
13451
Richard Smith6d4c6582013-11-05 22:18:15 +000013452 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013453 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000013454 LValue LV;
Richard Smith4566f872019-09-29 05:58:31 +000013455 CheckedTemporaries CheckedTemps;
Richard Smith457226e2019-09-23 03:48:44 +000013456 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13457 Result.HasSideEffects ||
Richard Smithb228a862012-02-15 02:18:13 +000013458 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000013459 Ctx.getLValueReferenceType(getType()), LV,
Richard Smith4566f872019-09-29 05:58:31 +000013460 Expr::EvaluateForCodeGen, CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +000013461 return false;
13462
Richard Smith2e312c82012-03-03 22:46:17 +000013463 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000013464 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000013465}
13466
Reid Kleckner1a840d22018-05-10 18:57:35 +000013467bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13468 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013469 assert(!isValueDependent() &&
13470 "Expression evaluator can't be called on a dependent expression.");
13471
Reid Kleckner1a840d22018-05-10 18:57:35 +000013472 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13473 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000013474 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000013475
Richard Smithda1b4342019-09-27 01:26:47 +000013476 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
Reid Kleckner1a840d22018-05-10 18:57:35 +000013477 return false;
13478
Richard Smith457226e2019-09-23 03:48:44 +000013479 if (!Info.discardCleanups())
13480 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13481
Reid Kleckner1a840d22018-05-10 18:57:35 +000013482 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
Richard Smithda1b4342019-09-27 01:26:47 +000013483 Usage) &&
13484 CheckMemoryLeaks(Info);
Reid Kleckner1a840d22018-05-10 18:57:35 +000013485}
13486
Richard Smithd0b4dd62011-12-19 06:19:21 +000013487bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13488 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013489 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013490 assert(!isValueDependent() &&
13491 "Expression evaluator can't be called on a dependent expression.");
13492
Richard Smithdafff942012-01-14 04:30:29 +000013493 // FIXME: Evaluating initializers for large array and record types can cause
13494 // performance problems. Only do so in C++11 for now.
13495 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013496 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000013497 return false;
13498
Richard Smithd0b4dd62011-12-19 06:19:21 +000013499 Expr::EvalStatus EStatus;
13500 EStatus.Diag = &Notes;
13501
Nandor Licker950b70d2019-09-13 09:46:16 +000013502 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000013503 ? EvalInfo::EM_ConstantExpression
13504 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000013505 Info.setEvaluatingDecl(VD, Value);
13506 Info.InConstantContext = true;
13507
13508 SourceLocation DeclLoc = VD->getLocation();
13509 QualType DeclTy = VD->getType();
13510
13511 if (Info.EnableNewConstInterp) {
13512 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13513 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
13514 case interp::InterpResult::Fail:
13515 // Bail out if an error was encountered.
13516 return false;
13517 case interp::InterpResult::Success:
13518 // Evaluation succeeded and value was set.
13519 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
13520 case interp::InterpResult::Bail:
13521 // Evaluate the value again for the tree evaluator to use.
13522 break;
13523 }
13524 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000013525
13526 LValue LVal;
13527 LVal.set(VD);
13528
Richard Smithfddd3842011-12-30 21:15:51 +000013529 // C++11 [basic.start.init]p2:
13530 // Variables with static storage duration or thread storage duration shall be
13531 // zero-initialized before any other initialization takes place.
13532 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013533 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Nandor Licker950b70d2019-09-13 09:46:16 +000013534 !DeclTy->isReferenceType()) {
13535 ImplicitValueInitExpr VIE(DeclTy);
13536 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000013537 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000013538 return false;
13539 }
13540
Nandor Licker950b70d2019-09-13 09:46:16 +000013541 if (!EvaluateInPlace(Value, Info, LVal, this,
Richard Smith7525ff62013-05-09 07:14:00 +000013542 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000013543 EStatus.HasSideEffects)
13544 return false;
13545
Richard Smith457226e2019-09-23 03:48:44 +000013546 // At this point, any lifetime-extended temporaries are completely
13547 // initialized.
13548 Info.performLifetimeExtension();
13549
13550 if (!Info.discardCleanups())
13551 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13552
Richard Smithda1b4342019-09-27 01:26:47 +000013553 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13554 CheckMemoryLeaks(Info);
Richard Smithd0b4dd62011-12-19 06:19:21 +000013555}
13556
Richard Smith2b4fa532019-09-29 05:08:46 +000013557bool VarDecl::evaluateDestruction(
13558 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13559 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
13560 "cannot evaluate destruction of non-constant-initialized variable");
13561
13562 Expr::EvalStatus EStatus;
13563 EStatus.Diag = &Notes;
13564
13565 // Make a copy of the value for the destructor to mutate.
13566 APValue DestroyedValue = *getEvaluatedValue();
13567
13568 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13569 Info.setEvaluatingDecl(this, DestroyedValue,
13570 EvalInfo::EvaluatingDeclKind::Dtor);
13571 Info.InConstantContext = true;
13572
13573 SourceLocation DeclLoc = getLocation();
13574 QualType DeclTy = getType();
13575
13576 LValue LVal;
13577 LVal.set(this);
13578
13579 // FIXME: Consider storing whether this variable has constant destruction in
13580 // the EvaluatedStmt so that CodeGen can query it.
13581 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13582 EStatus.HasSideEffects)
13583 return false;
13584
13585 if (!Info.discardCleanups())
13586 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13587
13588 ensureEvaluatedStmt()->HasConstantDestruction = true;
13589 return true;
13590}
13591
Richard Smith7b553f12011-10-29 00:50:52 +000013592/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13593/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000013594bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013595 assert(!isValueDependent() &&
13596 "Expression evaluator can't be called on a dependent expression.");
13597
Anders Carlsson5b3638b2008-12-01 06:44:05 +000013598 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000013599 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000013600 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000013601}
Anders Carlsson59689ed2008-11-22 21:04:56 +000013602
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000013603APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013604 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013605 assert(!isValueDependent() &&
13606 "Expression evaluator can't be called on a dependent expression.");
13607
Fangrui Song407659a2018-11-30 23:41:18 +000013608 EvalResult EVResult;
13609 EVResult.Diag = Diag;
13610 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13611 Info.InConstantContext = true;
13612
13613 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000013614 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000013615 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013616 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000013617
Fangrui Song407659a2018-11-30 23:41:18 +000013618 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000013619}
John McCall864e3962010-05-07 05:32:02 +000013620
David Bolvansky3b6ae572018-10-18 20:49:06 +000013621APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13622 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013623 assert(!isValueDependent() &&
13624 "Expression evaluator can't be called on a dependent expression.");
13625
Fangrui Song407659a2018-11-30 23:41:18 +000013626 EvalResult EVResult;
13627 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000013628 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013629 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013630 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013631
13632 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000013633 (void)Result;
13634 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013635 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000013636
Fangrui Song407659a2018-11-30 23:41:18 +000013637 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000013638}
13639
Richard Smithe9ff7702013-11-05 22:23:30 +000013640void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013641 assert(!isValueDependent() &&
13642 "Expression evaluator can't be called on a dependent expression.");
13643
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013644 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000013645 EvalResult EVResult;
13646 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000013647 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13648 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013649 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013650 }
13651}
13652
Richard Smithe6c01442013-06-05 00:46:14 +000013653bool Expr::EvalResult::isGlobalLValue() const {
13654 assert(Val.isLValue());
13655 return IsGlobalLValue(Val.getLValueBase());
13656}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000013657
13658
John McCall864e3962010-05-07 05:32:02 +000013659/// isIntegerConstantExpr - this recursive routine will test if an expression is
13660/// an integer constant expression.
13661
13662/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
13663/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000013664
13665// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000013666// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
13667// and a (possibly null) SourceLocation indicating the location of the problem.
13668//
John McCall864e3962010-05-07 05:32:02 +000013669// Note that to reduce code duplication, this helper does no evaluation
13670// itself; the caller checks whether the expression is evaluatable, and
13671// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000013672// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000013673
Dan Gohman28ade552010-07-26 21:25:24 +000013674namespace {
13675
Richard Smith9e575da2012-12-28 13:25:52 +000013676enum ICEKind {
13677 /// This expression is an ICE.
13678 IK_ICE,
13679 /// This expression is not an ICE, but if it isn't evaluated, it's
13680 /// a legal subexpression for an ICE. This return value is used to handle
13681 /// the comma operator in C99 mode, and non-constant subexpressions.
13682 IK_ICEIfUnevaluated,
13683 /// This expression is not an ICE, and is not a legal subexpression for one.
13684 IK_NotICE
13685};
13686
John McCall864e3962010-05-07 05:32:02 +000013687struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000013688 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000013689 SourceLocation Loc;
13690
Richard Smith9e575da2012-12-28 13:25:52 +000013691 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000013692};
13693
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013694}
Dan Gohman28ade552010-07-26 21:25:24 +000013695
Richard Smith9e575da2012-12-28 13:25:52 +000013696static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
13697
13698static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000013699
Craig Toppera31a8822013-08-22 07:09:37 +000013700static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013701 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000013702 Expr::EvalStatus Status;
13703 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13704
13705 Info.InConstantContext = true;
13706 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000013707 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013708 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000013709
John McCall864e3962010-05-07 05:32:02 +000013710 return NoDiag();
13711}
13712
Craig Toppera31a8822013-08-22 07:09:37 +000013713static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013714 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000013715 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013716 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013717
13718 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000013719#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000013720#define STMT(Node, Base) case Expr::Node##Class:
13721#define EXPR(Node, Base)
13722#include "clang/AST/StmtNodes.inc"
13723 case Expr::PredefinedExprClass:
13724 case Expr::FloatingLiteralClass:
13725 case Expr::ImaginaryLiteralClass:
13726 case Expr::StringLiteralClass:
13727 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000013728 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000013729 case Expr::MemberExprClass:
13730 case Expr::CompoundAssignOperatorClass:
13731 case Expr::CompoundLiteralExprClass:
13732 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000013733 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000013734 case Expr::ArrayInitLoopExprClass:
13735 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000013736 case Expr::NoInitExprClass:
13737 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000013738 case Expr::ImplicitValueInitExprClass:
13739 case Expr::ParenListExprClass:
13740 case Expr::VAArgExprClass:
13741 case Expr::AddrLabelExprClass:
13742 case Expr::StmtExprClass:
13743 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000013744 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000013745 case Expr::CXXDynamicCastExprClass:
13746 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000013747 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000013748 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000013749 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013750 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000013751 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013752 case Expr::CXXThisExprClass:
13753 case Expr::CXXThrowExprClass:
13754 case Expr::CXXNewExprClass:
13755 case Expr::CXXDeleteExprClass:
13756 case Expr::CXXPseudoDestructorExprClass:
13757 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000013758 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000013759 case Expr::DependentScopeDeclRefExprClass:
13760 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000013761 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000013762 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000013763 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000013764 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000013765 case Expr::CXXTemporaryObjectExprClass:
13766 case Expr::CXXUnresolvedConstructExprClass:
13767 case Expr::CXXDependentScopeMemberExprClass:
13768 case Expr::UnresolvedMemberExprClass:
13769 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000013770 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013771 case Expr::ObjCArrayLiteralClass:
13772 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013773 case Expr::ObjCEncodeExprClass:
13774 case Expr::ObjCMessageExprClass:
13775 case Expr::ObjCSelectorExprClass:
13776 case Expr::ObjCProtocolExprClass:
13777 case Expr::ObjCIvarRefExprClass:
13778 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013779 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000013780 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000013781 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000013782 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000013783 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000013784 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000013785 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000013786 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000013787 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000013788 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000013789 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000013790 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000013791 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000013792 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000013793 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000013794 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000013795 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000013796 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013797 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000013798 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013799 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013800 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000013801
Richard Smithf137f932014-01-25 20:50:08 +000013802 case Expr::InitListExprClass: {
13803 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13804 // form "T x = { a };" is equivalent to "T x = a;".
13805 // Unless we're initializing a reference, T is a scalar as it is known to be
13806 // of integral or enumeration type.
13807 if (E->isRValue())
13808 if (cast<InitListExpr>(E)->getNumInits() == 1)
13809 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013810 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000013811 }
13812
Douglas Gregor820ba7b2011-01-04 17:33:58 +000013813 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000013814 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000013815 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000013816 return NoDiag();
13817
John McCall7c454bb2011-07-15 05:09:51 +000013818 case Expr::SubstNonTypeTemplateParmExprClass:
13819 return
13820 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13821
Bill Wendling7c44da22018-10-31 03:48:47 +000013822 case Expr::ConstantExprClass:
13823 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13824
John McCall864e3962010-05-07 05:32:02 +000013825 case Expr::ParenExprClass:
13826 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000013827 case Expr::GenericSelectionExprClass:
13828 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013829 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000013830 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013831 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013832 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000013833 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000013834 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000013835 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000013836 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000013837 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000013838 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013839 return NoDiag();
13840 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000013841 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000013842 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13843 // constant expressions, but they can never be ICEs because an ICE cannot
13844 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000013845 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000013846 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000013847 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013848 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013849 }
Richard Smith6365c912012-02-24 22:12:32 +000013850 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013851 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13852 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000013853 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000013854 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000013855 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000013856 // Parameter variables are never constants. Without this check,
13857 // getAnyInitializer() can find a default argument, which leads
13858 // to chaos.
13859 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000013860 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013861
13862 // C++ 7.1.5.1p2
13863 // A variable of non-volatile const-qualified integral or enumeration
13864 // type initialized by an ICE can be used in ICEs.
13865 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000013866 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000013867 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000013868
Richard Smithd0b4dd62011-12-19 06:19:21 +000013869 const VarDecl *VD;
13870 // Look for a declaration of this variable that has an initializer, and
13871 // check whether it is an ICE.
13872 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13873 return NoDiag();
13874 else
Richard Smith9e575da2012-12-28 13:25:52 +000013875 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013876 }
13877 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013878 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000013879 }
John McCall864e3962010-05-07 05:32:02 +000013880 case Expr::UnaryOperatorClass: {
13881 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13882 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013883 case UO_PostInc:
13884 case UO_PostDec:
13885 case UO_PreInc:
13886 case UO_PreDec:
13887 case UO_AddrOf:
13888 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000013889 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000013890 // C99 6.6/3 allows increment and decrement within unevaluated
13891 // subexpressions of constant expressions, but they can never be ICEs
13892 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013893 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000013894 case UO_Extension:
13895 case UO_LNot:
13896 case UO_Plus:
13897 case UO_Minus:
13898 case UO_Not:
13899 case UO_Real:
13900 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000013901 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013902 }
Reid Klecknere540d972018-11-01 17:51:48 +000013903 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000013904 }
13905 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000013906 // Note that per C99, offsetof must be an ICE. And AFAIK, using
13907 // EvaluateAsRValue matches the proposed gcc behavior for cases like
13908 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
13909 // compliance: we should warn earlier for offsetof expressions with
13910 // array subscripts that aren't ICEs, and if the array subscripts
13911 // are ICEs, the value of the offsetof must be an integer constant.
13912 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000013913 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000013914 case Expr::UnaryExprOrTypeTraitExprClass: {
13915 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
13916 if ((Exp->getKind() == UETT_SizeOf) &&
13917 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013918 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013919 return NoDiag();
13920 }
13921 case Expr::BinaryOperatorClass: {
13922 const BinaryOperator *Exp = cast<BinaryOperator>(E);
13923 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013924 case BO_PtrMemD:
13925 case BO_PtrMemI:
13926 case BO_Assign:
13927 case BO_MulAssign:
13928 case BO_DivAssign:
13929 case BO_RemAssign:
13930 case BO_AddAssign:
13931 case BO_SubAssign:
13932 case BO_ShlAssign:
13933 case BO_ShrAssign:
13934 case BO_AndAssign:
13935 case BO_XorAssign:
13936 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000013937 // C99 6.6/3 allows assignments within unevaluated subexpressions of
13938 // constant expressions, but they can never be ICEs because an ICE cannot
13939 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013940 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013941
John McCalle3027922010-08-25 11:45:40 +000013942 case BO_Mul:
13943 case BO_Div:
13944 case BO_Rem:
13945 case BO_Add:
13946 case BO_Sub:
13947 case BO_Shl:
13948 case BO_Shr:
13949 case BO_LT:
13950 case BO_GT:
13951 case BO_LE:
13952 case BO_GE:
13953 case BO_EQ:
13954 case BO_NE:
13955 case BO_And:
13956 case BO_Xor:
13957 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000013958 case BO_Comma:
13959 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000013960 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13961 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000013962 if (Exp->getOpcode() == BO_Div ||
13963 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000013964 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000013965 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000013966 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000013967 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000013968 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013969 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013970 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000013971 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000013972 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013973 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013974 }
13975 }
13976 }
John McCalle3027922010-08-25 11:45:40 +000013977 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013978 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000013979 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
13980 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000013981 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013982 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013983 } else {
13984 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013985 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013986 }
13987 }
Richard Smith9e575da2012-12-28 13:25:52 +000013988 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000013989 }
John McCalle3027922010-08-25 11:45:40 +000013990 case BO_LAnd:
13991 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000013992 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13993 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013994 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000013995 // Rare case where the RHS has a comma "side-effect"; we need
13996 // to actually check the condition to see whether the side
13997 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000013998 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000013999 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000014000 return RHSResult;
14001 return NoDiag();
14002 }
14003
Richard Smith9e575da2012-12-28 13:25:52 +000014004 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000014005 }
14006 }
Reid Klecknere540d972018-11-01 17:51:48 +000014007 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000014008 }
14009 case Expr::ImplicitCastExprClass:
14010 case Expr::CStyleCastExprClass:
14011 case Expr::CXXFunctionalCastExprClass:
14012 case Expr::CXXStaticCastExprClass:
14013 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000014014 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000014015 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000014016 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000014017 if (isa<ExplicitCastExpr>(E)) {
14018 if (const FloatingLiteral *FL
14019 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14020 unsigned DestWidth = Ctx.getIntWidth(E->getType());
14021 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14022 APSInt IgnoredVal(DestWidth, !DestSigned);
14023 bool Ignored;
14024 // If the value does not fit in the destination type, the behavior is
14025 // undefined, so we are not required to treat it as a constant
14026 // expression.
14027 if (FL->getValue().convertToInteger(IgnoredVal,
14028 llvm::APFloat::rmTowardZero,
14029 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014030 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000014031 return NoDiag();
14032 }
14033 }
Eli Friedman76d4e432011-09-29 21:49:34 +000014034 switch (cast<CastExpr>(E)->getCastKind()) {
14035 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000014036 case CK_AtomicToNonAtomic:
14037 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000014038 case CK_NoOp:
14039 case CK_IntegralToBoolean:
14040 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000014041 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000014042 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014043 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000014044 }
John McCall864e3962010-05-07 05:32:02 +000014045 }
John McCallc07a0c72011-02-17 10:25:35 +000014046 case Expr::BinaryConditionalOperatorClass: {
14047 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14048 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014049 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000014050 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014051 if (FalseResult.Kind == IK_NotICE) return FalseResult;
14052 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14053 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000014054 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000014055 return FalseResult;
14056 }
John McCall864e3962010-05-07 05:32:02 +000014057 case Expr::ConditionalOperatorClass: {
14058 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14059 // If the condition (ignoring parens) is a __builtin_constant_p call,
14060 // then only the true side is actually considered in an integer constant
14061 // expression, and it is fully evaluated. This is an important GNU
14062 // extension. See GCC PR38377 for discussion.
14063 if (const CallExpr *CallCE
14064 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000014065 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000014066 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000014067 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014068 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014069 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000014070
Richard Smithf57d8cb2011-12-09 22:58:01 +000014071 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14072 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000014073
Richard Smith9e575da2012-12-28 13:25:52 +000014074 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014075 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014076 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014077 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014078 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000014079 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014080 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000014081 return NoDiag();
14082 // Rare case where the diagnostics depend on which side is evaluated
14083 // Note that if we get here, CondResult is 0, and at least one of
14084 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000014085 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000014086 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000014087 return TrueResult;
14088 }
14089 case Expr::CXXDefaultArgExprClass:
14090 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000014091 case Expr::CXXDefaultInitExprClass:
14092 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014093 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000014094 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014095 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000014096 case Expr::BuiltinBitCastExprClass: {
14097 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14098 return ICEDiag(IK_NotICE, E->getBeginLoc());
14099 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14100 }
John McCall864e3962010-05-07 05:32:02 +000014101 }
14102
David Blaikiee4d798f2012-01-20 21:50:17 +000014103 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000014104}
14105
Richard Smithf57d8cb2011-12-09 22:58:01 +000014106/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000014107static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000014108 const Expr *E,
14109 llvm::APSInt *Value,
14110 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000014111 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000014112 if (Loc) *Loc = E->getExprLoc();
14113 return false;
14114 }
14115
Richard Smith66e05fe2012-01-18 05:21:49 +000014116 APValue Result;
14117 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000014118 return false;
14119
Richard Smith98710fc2014-11-13 23:03:19 +000014120 if (!Result.isInt()) {
14121 if (Loc) *Loc = E->getExprLoc();
14122 return false;
14123 }
14124
Richard Smith66e05fe2012-01-18 05:21:49 +000014125 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000014126 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000014127}
14128
Craig Toppera31a8822013-08-22 07:09:37 +000014129bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14130 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014131 assert(!isValueDependent() &&
14132 "Expression evaluator can't be called on a dependent expression.");
14133
Richard Smith2bf7fdb2013-01-02 11:42:31 +000014134 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000014135 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000014136
Richard Smith9e575da2012-12-28 13:25:52 +000014137 ICEDiag D = CheckICE(this, Ctx);
14138 if (D.Kind != IK_ICE) {
14139 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000014140 return false;
14141 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000014142 return true;
14143}
14144
Craig Toppera31a8822013-08-22 07:09:37 +000014145bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000014146 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014147 assert(!isValueDependent() &&
14148 "Expression evaluator can't be called on a dependent expression.");
14149
Richard Smith2bf7fdb2013-01-02 11:42:31 +000014150 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000014151 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14152
14153 if (!isIntegerConstantExpr(Ctx, Loc))
14154 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000014155
Richard Smith5c40f092015-12-04 03:00:44 +000014156 // The only possible side-effects here are due to UB discovered in the
14157 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14158 // required to treat the expression as an ICE, so we produce the folded
14159 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000014160 EvalResult ExprResult;
14161 Expr::EvalStatus Status;
14162 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14163 Info.InConstantContext = true;
14164
14165 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000014166 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000014167
14168 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000014169 return true;
14170}
Richard Smith66e05fe2012-01-18 05:21:49 +000014171
Craig Toppera31a8822013-08-22 07:09:37 +000014172bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014173 assert(!isValueDependent() &&
14174 "Expression evaluator can't be called on a dependent expression.");
14175
Richard Smith9e575da2012-12-28 13:25:52 +000014176 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000014177}
14178
Craig Toppera31a8822013-08-22 07:09:37 +000014179bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000014180 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014181 assert(!isValueDependent() &&
14182 "Expression evaluator can't be called on a dependent expression.");
14183
Richard Smith66e05fe2012-01-18 05:21:49 +000014184 // We support this checking in C++98 mode in order to diagnose compatibility
14185 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000014186 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000014187
Richard Smith98a0a492012-02-14 21:38:30 +000014188 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000014189 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014190 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000014191 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000014192 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000014193
14194 APValue Scratch;
Richard Smith457226e2019-09-23 03:48:44 +000014195 bool IsConstExpr =
14196 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14197 // FIXME: We don't produce a diagnostic for this, but the callers that
14198 // call us on arbitrary full-expressions should generally not care.
Richard Smithda1b4342019-09-27 01:26:47 +000014199 Info.discardCleanups() && !Status.HasSideEffects;
Richard Smith66e05fe2012-01-18 05:21:49 +000014200
14201 if (!Diags.empty()) {
14202 IsConstExpr = false;
14203 if (Loc) *Loc = Diags[0].first;
14204 } else if (!IsConstExpr) {
14205 // FIXME: This shouldn't happen.
14206 if (Loc) *Loc = getExprLoc();
14207 }
14208
14209 return IsConstExpr;
14210}
Richard Smith253c2a32012-01-27 01:14:48 +000014211
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014212bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14213 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000014214 ArrayRef<const Expr*> Args,
14215 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014216 assert(!isValueDependent() &&
14217 "Expression evaluator can't be called on a dependent expression.");
14218
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014219 Expr::EvalStatus Status;
14220 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014221 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014222
George Burgess IV177399e2017-01-09 04:12:14 +000014223 LValue ThisVal;
14224 const LValue *ThisPtr = nullptr;
14225 if (This) {
14226#ifndef NDEBUG
14227 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14228 assert(MD && "Don't provide `this` for non-methods.");
14229 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14230#endif
14231 if (EvaluateObjectArgument(Info, This, ThisVal))
14232 ThisPtr = &ThisVal;
14233 if (Info.EvalStatus.HasSideEffects)
14234 return false;
14235 }
14236
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014237 ArgVector ArgValues(Args.size());
14238 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14239 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000014240 if ((*I)->isValueDependent() ||
14241 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014242 // If evaluation fails, throw away the argument entirely.
14243 ArgValues[I - Args.begin()] = APValue();
14244 if (Info.EvalStatus.HasSideEffects)
14245 return false;
14246 }
14247
14248 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000014249 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014250 ArgValues.data());
Richard Smith457226e2019-09-23 03:48:44 +000014251 return Evaluate(Value, Info, this) && Info.discardCleanups() &&
14252 !Info.EvalStatus.HasSideEffects;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014253}
14254
Richard Smith253c2a32012-01-27 01:14:48 +000014255bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014256 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000014257 PartialDiagnosticAt> &Diags) {
14258 // FIXME: It would be useful to check constexpr function templates, but at the
14259 // moment the constant expression evaluator cannot cope with the non-rigorous
14260 // ASTs which we build for dependent expressions.
14261 if (FD->isDependentContext())
14262 return true;
14263
14264 Expr::EvalStatus Status;
14265 Status.Diag = &Diags;
14266
Richard Smith045b2272019-09-10 21:24:09 +000014267 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000014268 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014269 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000014270
Nandor Licker950b70d2019-09-13 09:46:16 +000014271 // The constexpr VM attempts to compile all methods to bytecode here.
14272 if (Info.EnableNewConstInterp) {
14273 auto &InterpCtx = Info.Ctx.getInterpContext();
14274 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
14275 case interp::InterpResult::Success:
14276 case interp::InterpResult::Fail:
14277 return Diags.empty();
14278 case interp::InterpResult::Bail:
14279 break;
14280 }
14281 }
14282
Richard Smith253c2a32012-01-27 01:14:48 +000014283 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000014284 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000014285
Richard Smith7525ff62013-05-09 07:14:00 +000014286 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000014287 // is a temporary being used as the 'this' pointer.
14288 LValue This;
14289 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000014290 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000014291
Richard Smith253c2a32012-01-27 01:14:48 +000014292 ArrayRef<const Expr*> Args;
14293
Richard Smith2e312c82012-03-03 22:46:17 +000014294 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000014295 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14296 // Evaluate the call as a constant initializer, to allow the construction
14297 // of objects of non-literal types.
14298 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000014299 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14300 } else {
14301 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000014302 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000014303 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000014304 }
Richard Smith253c2a32012-01-27 01:14:48 +000014305
14306 return Diags.empty();
14307}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014308
14309bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14310 const FunctionDecl *FD,
14311 SmallVectorImpl<
14312 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014313 assert(!E->isValueDependent() &&
14314 "Expression evaluator can't be called on a dependent expression.");
14315
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014316 Expr::EvalStatus Status;
14317 Status.Diag = &Diags;
14318
14319 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000014320 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014321 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014322 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014323
14324 // Fabricate a call stack frame to give the arguments a plausible cover story.
14325 ArrayRef<const Expr*> Args;
14326 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014327 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014328 (void)Success;
14329 assert(Success &&
14330 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000014331 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014332
14333 APValue ResultScratch;
14334 Evaluate(ResultScratch, Info, E);
14335 return Diags.empty();
14336}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014337
14338bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14339 unsigned Type) const {
14340 if (!getType()->isPointerType())
14341 return false;
14342
14343 Expr::EvalStatus Status;
14344 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000014345 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014346}