blob: 33608db6e4297257655fd461b231cea1564de130 [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 Smithb228a862012-02-15 02:18:13 +0000693 /// EvalInfo - This is a private struct used by the evaluator to capture
694 /// information about a subexpression as it is folded. It retains information
695 /// about the AST context, but also maintains information about the folded
696 /// expression.
697 ///
698 /// If an expression could be evaluated, it is still possible it is not a C
699 /// "integer constant expression" or constant expression. If not, this struct
700 /// captures information about how and why not.
701 ///
702 /// One bit of information passed *into* the request for constant folding
703 /// indicates whether the subexpression is "evaluated" or not according to C
704 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
705 /// evaluate the expression regardless of what the RHS is, but C only allows
706 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000707 class EvalInfo : public interp::State {
708 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000709 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000710
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000711 /// EvalStatus - Contains information about the evaluation.
712 Expr::EvalStatus &EvalStatus;
713
714 /// CurrentCall - The top of the constexpr call stack.
715 CallStackFrame *CurrentCall;
716
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000717 /// CallStackDepth - The number of calls in the call stack right now.
718 unsigned CallStackDepth;
719
Richard Smithb228a862012-02-15 02:18:13 +0000720 /// NextCallIndex - The next call index to assign.
721 unsigned NextCallIndex;
722
Richard Smitha3d3bd22013-05-08 02:12:03 +0000723 /// StepsLeft - The remaining number of evaluation steps we're permitted
724 /// to perform. This is essentially a limit for the number of statements
725 /// we will evaluate.
726 unsigned StepsLeft;
727
Nandor Licker950b70d2019-09-13 09:46:16 +0000728 /// Force the use of the experimental new constant interpreter, bailing out
729 /// with an error if a feature is not supported.
730 bool ForceNewConstInterp;
731
732 /// Enable the experimental new constant interpreter.
733 bool EnableNewConstInterp;
734
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000735 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000736 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000737 CallStackFrame BottomFrame;
738
Richard Smith08d6a2c2013-07-24 07:11:57 +0000739 /// A stack of values whose lifetimes end at the end of some surrounding
740 /// evaluation frame.
741 llvm::SmallVector<Cleanup, 16> CleanupStack;
742
Richard Smithd62306a2011-11-10 06:34:14 +0000743 /// EvaluatingDecl - This is the declaration whose initializer is being
744 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000745 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000746
Richard Smith2b4fa532019-09-29 05:08:46 +0000747 enum class EvaluatingDeclKind {
748 None,
749 /// We're evaluating the construction of EvaluatingDecl.
750 Ctor,
751 /// We're evaluating the destruction of EvaluatingDecl.
752 Dtor,
753 };
754 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
755
Richard Smithd62306a2011-11-10 06:34:14 +0000756 /// EvaluatingDeclValue - This is the value being constructed for the
757 /// declaration whose initializer is being evaluated, if any.
758 APValue *EvaluatingDeclValue;
759
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000760 /// Set of objects that are currently being constructed.
761 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
762 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000763
Richard Smithda1b4342019-09-27 01:26:47 +0000764 /// A dynamically-allocated heap object.
765 struct DynAlloc {
766 /// The value of this heap-allocated object.
767 APValue Value;
768 /// The allocating expression; used for diagnostics.
769 const Expr *AllocExpr = nullptr;
770 };
771
772 struct DynAllocOrder {
773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774 return L.getIndex() < R.getIndex();
775 }
776 };
777
778 /// Current heap allocations, along with the location where each was
779 /// allocated. We use std::map here because we need stable addresses
780 /// for the stored APValues.
781 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
782
783 /// The number of heap allocations performed so far in this evaluation.
784 unsigned NumHeapAllocs = 0;
785
Erik Pilkington42925492017-10-04 00:18:55 +0000786 struct EvaluatingConstructorRAII {
787 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000788 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000789 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000790 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
791 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000792 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000793 DidInsert =
794 EI.ObjectsUnderConstruction
795 .insert({Object, HasBases ? ConstructionPhase::Bases
796 : ConstructionPhase::AfterBases})
797 .second;
798 }
799 void finishedConstructingBases() {
800 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000801 }
802 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000803 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000804 }
805 };
806
Richard Smith457226e2019-09-23 03:48:44 +0000807 struct EvaluatingDestructorRAII {
808 EvalInfo &EI;
809 ObjectUnderConstruction Object;
Richard Smithda1b4342019-09-27 01:26:47 +0000810 bool DidInsert;
Richard Smith457226e2019-09-23 03:48:44 +0000811 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
812 : EI(EI), Object(Object) {
Richard Smithda1b4342019-09-27 01:26:47 +0000813 DidInsert = EI.ObjectsUnderConstruction
814 .insert({Object, ConstructionPhase::Destroying})
815 .second;
Richard Smith457226e2019-09-23 03:48:44 +0000816 }
817 void startedDestroyingBases() {
818 EI.ObjectsUnderConstruction[Object] =
819 ConstructionPhase::DestroyingBases;
820 }
821 ~EvaluatingDestructorRAII() {
Richard Smithda1b4342019-09-27 01:26:47 +0000822 if (DidInsert)
823 EI.ObjectsUnderConstruction.erase(Object);
Richard Smith457226e2019-09-23 03:48:44 +0000824 }
825 };
826
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000827 ConstructionPhase
Richard Smith457226e2019-09-23 03:48:44 +0000828 isEvaluatingCtorDtor(APValue::LValueBase Base,
829 ArrayRef<APValue::LValuePathEntry> Path) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000830 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000831 }
832
Richard Smith37be3362019-05-04 04:00:45 +0000833 /// If we're currently speculatively evaluating, the outermost call stack
834 /// depth at which we can mutate state, otherwise 0.
835 unsigned SpeculativeEvaluationDepth = 0;
836
Richard Smith410306b2016-12-12 02:53:20 +0000837 /// The current array initialization index, if we're performing array
838 /// initialization.
839 uint64_t ArrayInitIndex = -1;
840
Richard Smith357362d2011-12-13 06:39:58 +0000841 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
842 /// notes attached to it will also be stored, otherwise they will not be.
843 bool HasActiveDiagnostic;
844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000845 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000846 /// fold (not just why it's not strictly a constant expression)?
847 bool HasFoldFailureDiagnostic;
848
Fangrui Song407659a2018-11-30 23:41:18 +0000849 /// Whether or not we're in a context where the front end requires a
850 /// constant value.
851 bool InConstantContext;
852
Richard Smith045b2272019-09-10 21:24:09 +0000853 /// Whether we're checking that an expression is a potential constant
854 /// expression. If so, do not fail on constructs that could become constant
855 /// later on (such as a use of an undefined global).
856 bool CheckingPotentialConstantExpression = false;
857
858 /// Whether we're checking for an expression that has undefined behavior.
859 /// If so, we will produce warnings if we encounter an operation that is
860 /// always undefined.
861 bool CheckingForUndefinedBehavior = false;
862
Richard Smith6d4c6582013-11-05 22:18:15 +0000863 enum EvaluationMode {
864 /// Evaluate as a constant expression. Stop if we find that the expression
865 /// is not a constant expression.
866 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000867
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000868 /// Evaluate as a constant expression. Stop if we find that the expression
869 /// is not a constant expression. Some expressions can be retried in the
870 /// optimizer if we don't constant fold them here, but in an unevaluated
871 /// context we try to fold them immediately since the optimizer never
872 /// gets a chance to look at it.
873 EM_ConstantExpressionUnevaluated,
874
Richard Smith045b2272019-09-10 21:24:09 +0000875 /// Fold the expression to a constant. Stop if we hit a side-effect that
876 /// we can't model.
877 EM_ConstantFold,
878
879 /// Evaluate in any way we know how. Don't worry about side-effects that
880 /// can't be modeled.
881 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000882 } EvalMode;
883
884 /// Are we checking whether the expression is a potential constant
885 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000886 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000887 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 }
889
890 /// Are we checking an expression for overflow?
891 // FIXME: We should check for any kind of undefined or suspicious behavior
892 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000893 bool checkingForUndefinedBehavior() const override {
894 return CheckingForUndefinedBehavior;
895 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000896
897 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000898 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
899 CallStackDepth(0), NextCallIndex(1),
900 StepsLeft(getLangOpts().ConstexprStepLimit),
901 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
902 EnableNewConstInterp(ForceNewConstInterp ||
903 getLangOpts().EnableNewConstInterp),
904 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
905 EvaluatingDecl((const ValueDecl *)nullptr),
906 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
907 HasFoldFailureDiagnostic(false), InConstantContext(false),
908 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000909
Richard Smith457226e2019-09-23 03:48:44 +0000910 ~EvalInfo() {
911 discardCleanups();
912 }
913
Richard Smith2b4fa532019-09-29 05:08:46 +0000914 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
915 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
Richard Smith7525ff62013-05-09 07:14:00 +0000916 EvaluatingDecl = Base;
Richard Smith2b4fa532019-09-29 05:08:46 +0000917 IsEvaluatingDecl = EDK;
Richard Smithd62306a2011-11-10 06:34:14 +0000918 EvaluatingDeclValue = &Value;
919 }
920
Richard Smith357362d2011-12-13 06:39:58 +0000921 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000922 // Don't perform any constexpr calls (other than the call we're checking)
923 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000924 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000925 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000926 if (NextCallIndex == 0) {
927 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000928 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000929 return false;
930 }
Richard Smith357362d2011-12-13 06:39:58 +0000931 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
932 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000933 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000934 << getLangOpts().ConstexprCallDepth;
935 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000936 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000937
Richard Smith37be3362019-05-04 04:00:45 +0000938 std::pair<CallStackFrame *, unsigned>
939 getCallFrameAndDepth(unsigned CallIndex) {
940 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000941 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
942 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000943 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000944 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000945 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000946 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000947 --Depth;
948 }
949 if (Frame->Index == CallIndex)
950 return {Frame, Depth};
951 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000952 }
953
Richard Smitha3d3bd22013-05-08 02:12:03 +0000954 bool nextStep(const Stmt *S) {
955 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000956 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000957 return false;
958 }
959 --StepsLeft;
960 return true;
961 }
962
Richard Smithda1b4342019-09-27 01:26:47 +0000963 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
964
965 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
966 Optional<DynAlloc*> Result;
967 auto It = HeapAllocs.find(DA);
968 if (It != HeapAllocs.end())
969 Result = &It->second;
970 return Result;
971 }
972
Richard Smith457226e2019-09-23 03:48:44 +0000973 void performLifetimeExtension() {
974 // Disable the cleanups for lifetime-extended temporaries.
975 CleanupStack.erase(
976 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
977 [](Cleanup &C) { return C.isLifetimeExtended(); }),
978 CleanupStack.end());
979 }
980
981 /// Throw away any remaining cleanups at the end of evaluation. If any
982 /// cleanups would have had a side-effect, note that as an unmodeled
983 /// side-effect and return false. Otherwise, return true.
984 bool discardCleanups() {
985 for (Cleanup &C : CleanupStack)
986 if (C.hasSideEffect())
987 if (!noteSideEffect())
988 return false;
989 return true;
990 }
991
Richard Smith357362d2011-12-13 06:39:58 +0000992 private:
Nandor Licker950b70d2019-09-13 09:46:16 +0000993 interp::Frame *getCurrentFrame() override { return CurrentCall; }
994 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
995
996 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
997 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
998
999 void setFoldFailureDiagnostic(bool Flag) override {
1000 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +00001001 }
1002
Nandor Licker950b70d2019-09-13 09:46:16 +00001003 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +00001004
Nandor Licker950b70d2019-09-13 09:46:16 +00001005 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +00001006
Nandor Licker950b70d2019-09-13 09:46:16 +00001007 // If we have a prior diagnostic, it will be noting that the expression
1008 // isn't a constant expression. This diagnostic is more important,
1009 // unless we require this evaluation to produce a constant expression.
1010 //
1011 // FIXME: We might want to show both diagnostics to the user in
1012 // EM_ConstantFold mode.
1013 bool hasPriorDiagnostic() override {
1014 if (!EvalStatus.Diag->empty()) {
1015 switch (EvalMode) {
1016 case EM_ConstantFold:
1017 case EM_IgnoreSideEffects:
1018 if (!HasFoldFailureDiagnostic)
1019 break;
1020 // We've already failed to fold something. Keep that diagnostic.
1021 LLVM_FALLTHROUGH;
1022 case EM_ConstantExpression:
1023 case EM_ConstantExpressionUnevaluated:
1024 setActiveDiagnostic(false);
1025 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +00001026 }
Richard Smith92b1ce02011-12-12 09:28:41 +00001027 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001028 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +00001029 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001030
1031 unsigned getCallStackDepth() override { return CallStackDepth; }
1032
Faisal Valie690b7a2016-07-02 22:34:24 +00001033 public:
Richard Smith6d4c6582013-11-05 22:18:15 +00001034 /// Should we continue evaluation after encountering a side-effect that we
1035 /// couldn't model?
1036 bool keepEvaluatingAfterSideEffect() {
1037 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001038 case EM_IgnoreSideEffects:
1039 return true;
1040
Richard Smith6d4c6582013-11-05 22:18:15 +00001041 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001042 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001043 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +00001044 // By default, assume any side effect might be valid in some other
1045 // evaluation of this expression from a different context.
1046 return checkingPotentialConstantExpression() ||
1047 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001048 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001049 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001050 }
1051
1052 /// Note that we have had a side-effect, and determine whether we should
1053 /// keep evaluating.
1054 bool noteSideEffect() {
1055 EvalStatus.HasSideEffects = true;
1056 return keepEvaluatingAfterSideEffect();
1057 }
1058
Richard Smithce8eca52015-12-08 03:21:47 +00001059 /// Should we continue evaluation after encountering undefined behavior?
1060 bool keepEvaluatingAfterUndefinedBehavior() {
1061 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +00001062 case EM_IgnoreSideEffects:
1063 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001064 return true;
1065
Richard Smithce8eca52015-12-08 03:21:47 +00001066 case EM_ConstantExpression:
1067 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +00001068 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +00001069 }
1070 llvm_unreachable("Missed EvalMode case");
1071 }
1072
1073 /// Note that we hit something that was technically undefined behavior, but
1074 /// that we can evaluate past it (such as signed overflow or floating-point
1075 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +00001076 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +00001077 EvalStatus.HasUndefinedBehavior = true;
1078 return keepEvaluatingAfterUndefinedBehavior();
1079 }
1080
Richard Smith253c2a32012-01-27 01:14:48 +00001081 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001082 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +00001083 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +00001084 if (!StepsLeft)
1085 return false;
1086
1087 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001088 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001089 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001090 case EM_ConstantFold:
1091 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +00001092 return checkingPotentialConstantExpression() ||
1093 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001094 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001095 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001096 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001097
George Burgess IV8c892b52016-05-25 22:31:54 +00001098 /// Notes that we failed to evaluate an expression that other expressions
1099 /// directly depend on, and determine if we should keep evaluating. This
1100 /// should only be called if we actually intend to keep evaluating.
1101 ///
1102 /// Call noteSideEffect() instead if we may be able to ignore the value that
1103 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1104 ///
1105 /// (Foo(), 1) // use noteSideEffect
1106 /// (Foo() || true) // use noteSideEffect
1107 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001108 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001109 // Failure when evaluating some expression often means there is some
1110 // subexpression whose evaluation was skipped. Therefore, (because we
1111 // don't track whether we skipped an expression when unwinding after an
1112 // evaluation failure) every evaluation failure that bubbles up from a
1113 // subexpression implies that a side-effect has potentially happened. We
1114 // skip setting the HasSideEffects flag to true until we decide to
1115 // continue evaluating after that point, which happens here.
1116 bool KeepGoing = keepEvaluatingAfterFailure();
1117 EvalStatus.HasSideEffects |= KeepGoing;
1118 return KeepGoing;
1119 }
1120
Richard Smith410306b2016-12-12 02:53:20 +00001121 class ArrayInitLoopIndex {
1122 EvalInfo &Info;
1123 uint64_t OuterIndex;
1124
1125 public:
1126 ArrayInitLoopIndex(EvalInfo &Info)
1127 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1128 Info.ArrayInitIndex = 0;
1129 }
1130 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1131
1132 operator uint64_t&() { return Info.ArrayInitIndex; }
1133 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001134 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001135
1136 /// Object used to treat all foldable expressions as constant expressions.
1137 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001138 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001139 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001140 bool HadNoPriorDiags;
1141 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001142
Richard Smith6d4c6582013-11-05 22:18:15 +00001143 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1144 : Info(Info),
1145 Enabled(Enabled),
1146 HadNoPriorDiags(Info.EvalStatus.Diag &&
1147 Info.EvalStatus.Diag->empty() &&
1148 !Info.EvalStatus.HasSideEffects),
1149 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001150 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001151 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001152 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001153 void keepDiagnostics() { Enabled = false; }
1154 ~FoldConstant() {
1155 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001156 !Info.EvalStatus.HasSideEffects)
1157 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001158 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001159 }
1160 };
Richard Smith17100ba2012-02-16 02:46:34 +00001161
James Y Knight892b09b2018-10-10 02:53:43 +00001162 /// RAII object used to set the current evaluation mode to ignore
1163 /// side-effects.
1164 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001165 EvalInfo &Info;
1166 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001167 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001168 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001169 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001170 }
1171
James Y Knight892b09b2018-10-10 02:53:43 +00001172 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001173 };
1174
George Burgess IV8c892b52016-05-25 22:31:54 +00001175 /// RAII object used to optionally suppress diagnostics and side-effects from
1176 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001177 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001178 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001179 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001180 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001181
George Burgess IV8c892b52016-05-25 22:31:54 +00001182 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001183 Info = Other.Info;
1184 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001185 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001186 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001187 }
1188
1189 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001190 if (!Info)
1191 return;
1192
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001193 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001194 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001195 }
1196
Richard Smith17100ba2012-02-16 02:46:34 +00001197 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001198 SpeculativeEvaluationRAII() = default;
1199
1200 SpeculativeEvaluationRAII(
1201 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001202 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001203 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001204 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001205 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001206 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001207
1208 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1209 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1210 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001211 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001212
1213 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1214 maybeRestoreState();
1215 moveFromAndCancel(std::move(Other));
1216 return *this;
1217 }
1218
1219 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001220 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001221
1222 /// RAII object wrapping a full-expression or block scope, and handling
1223 /// the ending of the lifetime of temporaries created within it.
1224 template<bool IsFullExpression>
1225 class ScopeRAII {
1226 EvalInfo &Info;
1227 unsigned OldStackSize;
1228 public:
1229 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001230 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1231 // Push a new temporary version. This is needed to distinguish between
1232 // temporaries created in different iterations of a loop.
1233 Info.CurrentCall->pushTempVersion();
1234 }
Richard Smith457226e2019-09-23 03:48:44 +00001235 bool destroy(bool RunDestructors = true) {
1236 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1237 OldStackSize = -1U;
1238 return OK;
1239 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001240 ~ScopeRAII() {
Richard Smith457226e2019-09-23 03:48:44 +00001241 if (OldStackSize != -1U)
1242 destroy(false);
Richard Smith08d6a2c2013-07-24 07:11:57 +00001243 // Body moved to a static method to encourage the compiler to inline away
1244 // instances of this class.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001245 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001246 }
1247 private:
Richard Smithda1b4342019-09-27 01:26:47 +00001248 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1249 unsigned OldStackSize) {
1250 assert(OldStackSize <= Info.CleanupStack.size() &&
1251 "running cleanups out of order?");
1252
Richard Smith457226e2019-09-23 03:48:44 +00001253 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1254 // for a full-expression scope.
Richard Smith49494732019-09-27 05:36:16 +00001255 bool Success = true;
Richard Smith457226e2019-09-23 03:48:44 +00001256 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
Richard Smithda1b4342019-09-27 01:26:47 +00001257 if (!(IsFullExpression &&
1258 Info.CleanupStack[I - 1].isLifetimeExtended())) {
Richard Smith49494732019-09-27 05:36:16 +00001259 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1260 Success = false;
1261 break;
1262 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001263 }
1264 }
Richard Smith457226e2019-09-23 03:48:44 +00001265
1266 // Compact lifetime-extended cleanups.
1267 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1268 if (IsFullExpression)
1269 NewEnd =
1270 std::remove_if(NewEnd, Info.CleanupStack.end(),
1271 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1272 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
Richard Smith49494732019-09-27 05:36:16 +00001273 return Success;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001274 }
1275 };
1276 typedef ScopeRAII<false> BlockScopeRAII;
1277 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001278}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001279
Richard Smitha8105bc2012-01-06 16:39:00 +00001280bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1281 CheckSubobjectKind CSK) {
1282 if (Invalid)
1283 return false;
1284 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001285 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001286 << CSK;
1287 setInvalid();
1288 return false;
1289 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001290 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1291 // must actually be at least one array element; even a VLA cannot have a
1292 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001293 return true;
1294}
1295
Richard Smith6f4f0f12017-10-20 22:56:25 +00001296void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1297 const Expr *E) {
1298 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1299 // Do not set the designator as invalid: we can represent this situation,
1300 // and correct handling of __builtin_object_size requires us to do so.
1301}
1302
Richard Smitha8105bc2012-01-06 16:39:00 +00001303void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001304 const Expr *E,
1305 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001306 // If we're complaining, we must be able to statically determine the size of
1307 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001308 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001309 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001310 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001311 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001312 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001313 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001314 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001315 setInvalid();
1316}
1317
Richard Smithf6f003a2011-12-16 19:06:07 +00001318CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1319 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001320 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001321 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1322 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001323 Info.CurrentCall = this;
1324 ++Info.CallStackDepth;
1325}
1326
1327CallStackFrame::~CallStackFrame() {
1328 assert(Info.CurrentCall == this && "calls retired out of order");
1329 --Info.CallStackDepth;
1330 Info.CurrentCall = Caller;
1331}
1332
Richard Smithc667cdc2019-09-18 17:37:44 +00001333static bool isRead(AccessKinds AK) {
1334 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1335}
1336
Richard Smithdebad642019-05-12 09:39:08 +00001337static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001338 switch (AK) {
1339 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001340 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001341 case AK_MemberCall:
1342 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001343 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001344 return false;
1345 case AK_Assign:
1346 case AK_Increment:
1347 case AK_Decrement:
Richard Smith61422f92019-09-27 20:24:36 +00001348 case AK_Destroy:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001349 return true;
1350 }
1351 llvm_unreachable("unknown access kind");
1352}
1353
Richard Smith61422f92019-09-27 20:24:36 +00001354static bool isAnyAccess(AccessKinds AK) {
1355 return isRead(AK) || isModification(AK);
1356}
1357
Richard Smith7bd54ab2019-05-15 20:22:21 +00001358/// Is this an access per the C++ definition?
1359static bool isFormalAccess(AccessKinds AK) {
Richard Smith61422f92019-09-27 20:24:36 +00001360 return isAnyAccess(AK) && AK != AK_Destroy;
Richard Smithdebad642019-05-12 09:39:08 +00001361}
1362
Richard Smithf6f003a2011-12-16 19:06:07 +00001363namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001364 struct ComplexValue {
1365 private:
1366 bool IsInt;
1367
1368 public:
1369 APSInt IntReal, IntImag;
1370 APFloat FloatReal, FloatImag;
1371
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001372 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001373
1374 void makeComplexFloat() { IsInt = false; }
1375 bool isComplexFloat() const { return !IsInt; }
1376 APFloat &getComplexFloatReal() { return FloatReal; }
1377 APFloat &getComplexFloatImag() { return FloatImag; }
1378
1379 void makeComplexInt() { IsInt = true; }
1380 bool isComplexInt() const { return IsInt; }
1381 APSInt &getComplexIntReal() { return IntReal; }
1382 APSInt &getComplexIntImag() { return IntImag; }
1383
Richard Smith2e312c82012-03-03 22:46:17 +00001384 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001385 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001386 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001387 else
Richard Smith2e312c82012-03-03 22:46:17 +00001388 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001389 }
Richard Smith2e312c82012-03-03 22:46:17 +00001390 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001391 assert(v.isComplexFloat() || v.isComplexInt());
1392 if (v.isComplexFloat()) {
1393 makeComplexFloat();
1394 FloatReal = v.getComplexFloatReal();
1395 FloatImag = v.getComplexFloatImag();
1396 } else {
1397 makeComplexInt();
1398 IntReal = v.getComplexIntReal();
1399 IntImag = v.getComplexIntImag();
1400 }
1401 }
John McCall93d91dc2010-05-07 17:22:02 +00001402 };
John McCall45d55e42010-05-07 21:00:08 +00001403
1404 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001405 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001406 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001407 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001408 bool IsNullPtr : 1;
1409 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001410
Richard Smithce40ad62011-11-12 22:28:03 +00001411 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001412 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001413 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001414 SubobjectDesignator &getLValueDesignator() { return Designator; }
1415 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001416 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001417
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001418 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1419 unsigned getLValueVersion() const { return Base.getVersion(); }
1420
Richard Smith2e312c82012-03-03 22:46:17 +00001421 void moveInto(APValue &V) const {
1422 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001423 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001424 else {
1425 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001426 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001427 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001428 }
John McCall45d55e42010-05-07 21:00:08 +00001429 }
Richard Smith2e312c82012-03-03 22:46:17 +00001430 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001431 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001432 Base = V.getLValueBase();
1433 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001434 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001435 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001436 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001437 }
1438
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001439 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001440#ifndef NDEBUG
1441 // We only allow a few types of invalid bases. Enforce that here.
1442 if (BInvalid) {
1443 const auto *E = B.get<const Expr *>();
1444 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1445 "Unexpected type of invalid base");
1446 }
1447#endif
1448
Richard Smithce40ad62011-11-12 22:28:03 +00001449 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001450 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001451 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001452 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001453 IsNullPtr = false;
1454 }
1455
1456 void setNull(QualType PointerTy, uint64_t TargetVal) {
1457 Base = (Expr *)nullptr;
1458 Offset = CharUnits::fromQuantity(TargetVal);
1459 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001460 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1461 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001462 }
1463
George Burgess IV3a03fab2015-09-04 21:28:13 +00001464 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001465 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001466 }
1467
Hubert Tong147b7432018-12-12 16:53:43 +00001468 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001469 // Check that this LValue is not based on a null pointer. If it is, produce
1470 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001471 template <typename GenDiagType>
1472 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001473 if (Designator.Invalid)
1474 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001475 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001476 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001477 Designator.setInvalid();
1478 return false;
1479 }
1480 return true;
1481 }
1482
Hubert Tong147b7432018-12-12 16:53:43 +00001483 public:
1484 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1485 CheckSubobjectKind CSK) {
1486 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1487 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1488 });
1489 }
1490
1491 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1492 AccessKinds AK) {
1493 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1494 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1495 });
1496 }
1497
Richard Smitha8105bc2012-01-06 16:39:00 +00001498 // Check this LValue refers to an object. If not, set the designator to be
1499 // invalid and emit a diagnostic.
1500 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001501 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001502 Designator.checkSubobject(Info, E, CSK);
1503 }
1504
1505 void addDecl(EvalInfo &Info, const Expr *E,
1506 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001507 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1508 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001509 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001510 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1511 if (!Designator.Entries.empty()) {
1512 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1513 Designator.setInvalid();
1514 return;
1515 }
Richard Smithefdb5032017-11-15 03:03:56 +00001516 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1517 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1518 Designator.FirstEntryIsAnUnsizedArray = true;
1519 Designator.addUnsizedArrayUnchecked(ElemTy);
1520 }
George Burgess IVe3763372016-12-22 02:50:20 +00001521 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001522 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001523 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1524 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001525 }
Richard Smith66c96992012-02-18 22:04:06 +00001526 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001527 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1528 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001529 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001530 void clearIsNullPointer() {
1531 IsNullPtr = false;
1532 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001533 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1534 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001535 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1536 // but we're not required to diagnose it and it's valid in C++.)
1537 if (!Index)
1538 return;
1539
1540 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1541 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1542 // offsets.
1543 uint64_t Offset64 = Offset.getQuantity();
1544 uint64_t ElemSize64 = ElementSize.getQuantity();
1545 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1546 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1547
1548 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001549 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001550 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001551 }
1552 void adjustOffset(CharUnits N) {
1553 Offset += N;
1554 if (N.getQuantity())
1555 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001556 }
John McCall45d55e42010-05-07 21:00:08 +00001557 };
Richard Smith027bf112011-11-17 22:56:20 +00001558
1559 struct MemberPtr {
1560 MemberPtr() {}
1561 explicit MemberPtr(const ValueDecl *Decl) :
1562 DeclAndIsDerivedMember(Decl, false), Path() {}
1563
1564 /// The member or (direct or indirect) field referred to by this member
1565 /// pointer, or 0 if this is a null member pointer.
1566 const ValueDecl *getDecl() const {
1567 return DeclAndIsDerivedMember.getPointer();
1568 }
1569 /// Is this actually a member of some type derived from the relevant class?
1570 bool isDerivedMember() const {
1571 return DeclAndIsDerivedMember.getInt();
1572 }
1573 /// Get the class which the declaration actually lives in.
1574 const CXXRecordDecl *getContainingRecord() const {
1575 return cast<CXXRecordDecl>(
1576 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1577 }
1578
Richard Smith2e312c82012-03-03 22:46:17 +00001579 void moveInto(APValue &V) const {
1580 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001581 }
Richard Smith2e312c82012-03-03 22:46:17 +00001582 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001583 assert(V.isMemberPointer());
1584 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1585 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1586 Path.clear();
1587 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1588 Path.insert(Path.end(), P.begin(), P.end());
1589 }
1590
1591 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1592 /// whether the member is a member of some class derived from the class type
1593 /// of the member pointer.
1594 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1595 /// Path - The path of base/derived classes from the member declaration's
1596 /// class (exclusive) to the class type of the member pointer (inclusive).
1597 SmallVector<const CXXRecordDecl*, 4> Path;
1598
1599 /// Perform a cast towards the class of the Decl (either up or down the
1600 /// hierarchy).
1601 bool castBack(const CXXRecordDecl *Class) {
1602 assert(!Path.empty());
1603 const CXXRecordDecl *Expected;
1604 if (Path.size() >= 2)
1605 Expected = Path[Path.size() - 2];
1606 else
1607 Expected = getContainingRecord();
1608 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1609 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1610 // if B does not contain the original member and is not a base or
1611 // derived class of the class containing the original member, the result
1612 // of the cast is undefined.
1613 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1614 // (D::*). We consider that to be a language defect.
1615 return false;
1616 }
1617 Path.pop_back();
1618 return true;
1619 }
1620 /// Perform a base-to-derived member pointer cast.
1621 bool castToDerived(const CXXRecordDecl *Derived) {
1622 if (!getDecl())
1623 return true;
1624 if (!isDerivedMember()) {
1625 Path.push_back(Derived);
1626 return true;
1627 }
1628 if (!castBack(Derived))
1629 return false;
1630 if (Path.empty())
1631 DeclAndIsDerivedMember.setInt(false);
1632 return true;
1633 }
1634 /// Perform a derived-to-base member pointer cast.
1635 bool castToBase(const CXXRecordDecl *Base) {
1636 if (!getDecl())
1637 return true;
1638 if (Path.empty())
1639 DeclAndIsDerivedMember.setInt(true);
1640 if (isDerivedMember()) {
1641 Path.push_back(Base);
1642 return true;
1643 }
1644 return castBack(Base);
1645 }
1646 };
Richard Smith357362d2011-12-13 06:39:58 +00001647
Richard Smith7bb00672012-02-01 01:42:44 +00001648 /// Compare two member pointers, which are assumed to be of the same type.
1649 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1650 if (!LHS.getDecl() || !RHS.getDecl())
1651 return !LHS.getDecl() && !RHS.getDecl();
1652 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1653 return false;
1654 return LHS.Path == RHS.Path;
1655 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001656}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001657
Richard Smith2e312c82012-03-03 22:46:17 +00001658static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001659static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1660 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001661 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001662static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1663 bool InvalidBaseOK = false);
1664static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1665 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001666static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1667 EvalInfo &Info);
1668static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001669static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001670static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001671 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001672static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001673static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001674static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1675 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001676static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001677
Leonard Chand3f3e162019-01-18 21:04:25 +00001678/// Evaluate an integer or fixed point expression into an APResult.
1679static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1680 EvalInfo &Info);
1681
1682/// Evaluate only a fixed point expression into an APResult.
1683static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1684 EvalInfo &Info);
1685
Chris Lattner05706e882008-07-11 18:11:29 +00001686//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001687// Misc utilities
1688//===----------------------------------------------------------------------===//
1689
Richard Smithd6cc1982017-01-31 02:23:02 +00001690/// Negate an APSInt in place, converting it to a signed form if necessary, and
1691/// preserving its value (by extending by up to one bit as needed).
1692static void negateAsSigned(APSInt &Int) {
1693 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1694 Int = Int.extend(Int.getBitWidth() + 1);
1695 Int.setIsSigned(true);
1696 }
1697 Int = -Int;
1698}
1699
Richard Smith457226e2019-09-23 03:48:44 +00001700template<typename KeyT>
1701APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1702 bool IsLifetimeExtended, LValue &LV) {
Richard Smithda1b4342019-09-27 01:26:47 +00001703 unsigned Version = getTempVersion();
Richard Smith457226e2019-09-23 03:48:44 +00001704 APValue::LValueBase Base(Key, Index, Version);
1705 LV.set(Base);
1706 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1707 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smithda1b4342019-09-27 01:26:47 +00001708
1709 // If we're creating a temporary immediately in the operand of a speculative
1710 // evaluation, don't register a cleanup to be run outside the speculative
1711 // evaluation context, since we won't actually be able to initialize this
1712 // object.
1713 if (Index <= Info.SpeculativeEvaluationDepth) {
1714 if (T.isDestructedType())
1715 Info.noteSideEffect();
1716 } else {
1717 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1718 }
Richard Smith457226e2019-09-23 03:48:44 +00001719 return Result;
1720}
1721
Richard Smithda1b4342019-09-27 01:26:47 +00001722APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1723 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1724 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1725 return nullptr;
1726 }
1727
1728 DynamicAllocLValue DA(NumHeapAllocs++);
1729 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1730 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1731 std::forward_as_tuple(DA), std::tuple<>());
1732 assert(Result.second && "reused a heap alloc index?");
1733 Result.first->second.AllocExpr = E;
1734 return &Result.first->second.Value;
1735}
1736
Richard Smith84401042013-06-03 05:03:02 +00001737/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001738void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001739 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001740 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1741 !isa<CXXConstructorDecl>(Callee) &&
1742 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001743
1744 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001745 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001746
Nandor Licker950b70d2019-09-13 09:46:16 +00001747 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001748 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001749 This->moveInto(Val);
1750 Val.printPretty(Out, Info.Ctx,
1751 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001752 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001753 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001754 IsMemberCall = false;
1755 }
1756
Nandor Licker950b70d2019-09-13 09:46:16 +00001757 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1758 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001759 if (ArgIndex > (unsigned)IsMemberCall)
1760 Out << ", ";
1761
1762 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001763 const APValue &Arg = Arguments[ArgIndex];
1764 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001765
1766 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001767 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001768 }
1769
1770 Out << ')';
1771}
1772
Richard Smithd9f663b2013-04-22 15:31:51 +00001773/// Evaluate an expression to see if it had side-effects, and discard its
1774/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001775/// \return \c true if the caller should keep evaluating.
1776static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001777 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001778 if (!Evaluate(Scratch, Info, E))
1779 // We don't need the value, but we might have skipped a side effect here.
1780 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001781 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001782}
1783
Richard Smithd62306a2011-11-10 06:34:14 +00001784/// Should this call expression be treated as a string literal?
1785static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001786 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001787 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1788 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1789}
1790
Richard Smithce40ad62011-11-12 22:28:03 +00001791static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001792 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1793 // constant expression of pointer type that evaluates to...
1794
1795 // ... a null pointer value, or a prvalue core constant expression of type
1796 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001797 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001798
Richard Smithce40ad62011-11-12 22:28:03 +00001799 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1800 // ... the address of an object with static storage duration,
1801 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1802 return VD->hasGlobalStorage();
1803 // ... the address of a function,
1804 return isa<FunctionDecl>(D);
1805 }
1806
Richard Smithda1b4342019-09-27 01:26:47 +00001807 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +00001808 return true;
1809
Richard Smithce40ad62011-11-12 22:28:03 +00001810 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001811 switch (E->getStmtClass()) {
1812 default:
1813 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001814 case Expr::CompoundLiteralExprClass: {
1815 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1816 return CLE->isFileScope() && CLE->isLValue();
1817 }
Richard Smithe6c01442013-06-05 00:46:14 +00001818 case Expr::MaterializeTemporaryExprClass:
1819 // A materialized temporary might have been lifetime-extended to static
1820 // storage duration.
1821 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001822 // A string literal has static storage duration.
1823 case Expr::StringLiteralClass:
1824 case Expr::PredefinedExprClass:
1825 case Expr::ObjCStringLiteralClass:
1826 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001827 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001828 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001829 case Expr::ObjCBoxedExprClass:
1830 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001831 case Expr::CallExprClass:
1832 return IsStringLiteralCall(cast<CallExpr>(E));
1833 // For GCC compatibility, &&label has static storage duration.
1834 case Expr::AddrLabelExprClass:
1835 return true;
1836 // A Block literal expression may be used as the initialization value for
1837 // Block variables at global or local static scope.
1838 case Expr::BlockExprClass:
1839 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001840 case Expr::ImplicitValueInitExprClass:
1841 // FIXME:
1842 // We can never form an lvalue with an implicit value initialization as its
1843 // base through expression evaluation, so these only appear in one case: the
1844 // implicit variable declaration we invent when checking whether a constexpr
1845 // constructor can produce a constant expression. We must assume that such
1846 // an expression might be a global lvalue.
1847 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001848 }
John McCall95007602010-05-10 23:27:23 +00001849}
1850
Richard Smith06f71b52018-08-04 00:57:17 +00001851static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1852 return LVal.Base.dyn_cast<const ValueDecl*>();
1853}
1854
1855static bool IsLiteralLValue(const LValue &Value) {
1856 if (Value.getLValueCallIndex())
1857 return false;
1858 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1859 return E && !isa<MaterializeTemporaryExpr>(E);
1860}
1861
1862static bool IsWeakLValue(const LValue &Value) {
1863 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1864 return Decl && Decl->isWeak();
1865}
1866
1867static bool isZeroSized(const LValue &Value) {
1868 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1869 if (Decl && isa<VarDecl>(Decl)) {
1870 QualType Ty = Decl->getType();
1871 if (Ty->isArrayType())
1872 return Ty->isIncompleteType() ||
1873 Decl->getASTContext().getTypeSize(Ty) == 0;
1874 }
1875 return false;
1876}
1877
1878static bool HasSameBase(const LValue &A, const LValue &B) {
1879 if (!A.getLValueBase())
1880 return !B.getLValueBase();
1881 if (!B.getLValueBase())
1882 return false;
1883
1884 if (A.getLValueBase().getOpaqueValue() !=
1885 B.getLValueBase().getOpaqueValue()) {
1886 const Decl *ADecl = GetLValueBaseDecl(A);
1887 if (!ADecl)
1888 return false;
1889 const Decl *BDecl = GetLValueBaseDecl(B);
1890 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1891 return false;
1892 }
1893
1894 return IsGlobalLValue(A.getLValueBase()) ||
1895 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1896 A.getLValueVersion() == B.getLValueVersion());
1897}
1898
Richard Smithb228a862012-02-15 02:18:13 +00001899static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1900 assert(Base && "no location for a null lvalue");
1901 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1902 if (VD)
1903 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001904 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1905 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
Richard Smithda1b4342019-09-27 01:26:47 +00001906 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1907 // FIXME: Produce a note for dangling pointers too.
1908 if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1909 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1910 diag::note_constexpr_dynamic_alloc_here);
1911 }
Richard Smithee0ce3022019-05-17 07:06:46 +00001912 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001913}
1914
Richard Smith80815602011-11-07 05:07:52 +00001915/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001916/// value for an address or reference constant expression. Return true if we
1917/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001918static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 QualType Type, const LValue &LVal,
1920 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001921 bool IsReferenceType = Type->isReferenceType();
1922
Richard Smith357362d2011-12-13 06:39:58 +00001923 APValue::LValueBase Base = LVal.getLValueBase();
1924 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1925
Richard Smith0dea49e2012-02-18 04:58:18 +00001926 // Check that the object is a global. Note that the fake 'this' object we
1927 // manufacture when checking potential constant expressions is conservatively
1928 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001929 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001930 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001931 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001932 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001933 << IsReferenceType << !Designator.Entries.empty()
1934 << !!VD << VD;
1935 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001936 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001937 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001938 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001939 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001940 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001941 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001942 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001943 LVal.getLValueCallIndex() == 0) &&
1944 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001945
Richard Smithda1b4342019-09-27 01:26:47 +00001946 if (Base.is<DynamicAllocLValue>()) {
1947 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
1948 << IsReferenceType << !Designator.Entries.empty();
1949 NoteLValueLocation(Info, Base);
1950 return false;
1951 }
1952
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001953 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1954 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001955 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001956 if (Var->getTLSKind())
Richard Smithda1b4342019-09-27 01:26:47 +00001957 // FIXME: Diagnostic!
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001958 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001959
Hans Wennborg82dd8772014-06-25 22:19:48 +00001960 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001961 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00001962 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00001963 return false;
1964 }
1965 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1966 // __declspec(dllimport) must be handled very carefully:
1967 // We must never initialize an expression with the thunk in C++.
1968 // Doing otherwise would allow the same id-expression to yield
1969 // different addresses for the same function in different translation
1970 // units. However, this means that we must dynamically initialize the
1971 // expression with the contents of the import address table at runtime.
1972 //
1973 // The C language has no notion of ODR; furthermore, it has no notion of
1974 // dynamic initialization. This means that we are permitted to
1975 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001976 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1977 FD->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00001978 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00001979 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001980 }
1981 }
1982
Richard Smitha8105bc2012-01-06 16:39:00 +00001983 // Allow address constant expressions to be past-the-end pointers. This is
1984 // an extension: the standard requires them to point to an object.
1985 if (!IsReferenceType)
1986 return true;
1987
1988 // A reference constant expression must refer to an object.
1989 if (!Base) {
1990 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001991 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001992 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001993 }
1994
Richard Smith357362d2011-12-13 06:39:58 +00001995 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001996 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001997 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001998 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001999 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00002000 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002001 }
2002
Richard Smith80815602011-11-07 05:07:52 +00002003 return true;
2004}
2005
Reid Klecknercd016d82017-07-07 22:04:29 +00002006/// Member pointers are constant expressions unless they point to a
2007/// non-virtual dllimport member function.
2008static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2009 SourceLocation Loc,
2010 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002011 const APValue &Value,
2012 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002013 const ValueDecl *Member = Value.getMemberPointerDecl();
2014 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2015 if (!FD)
2016 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002017 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2018 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002019}
2020
Richard Smithfddd3842011-12-30 21:15:51 +00002021/// Check that this core constant expression is of literal type, and if not,
2022/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002023static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002024 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002025 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002026 return true;
2027
Richard Smith7525ff62013-05-09 07:14:00 +00002028 // C++1y: A constant initializer for an object o [...] may also invoke
2029 // constexpr constructors for o and its subobjects even if those objects
2030 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002031 //
2032 // C++11 missed this detail for aggregates, so classes like this:
2033 // struct foo_t { union { int i; volatile int j; } u; };
2034 // are not (obviously) initializable like so:
2035 // __attribute__((__require_constant_initialization__))
2036 // static const foo_t x = {{0}};
2037 // because "i" is a subobject with non-literal initialization (due to the
2038 // volatile member of the union). See:
2039 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2040 // Therefore, we use the C++1y behavior.
2041 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002042 return true;
2043
Richard Smithfddd3842011-12-30 21:15:51 +00002044 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002045 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002046 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002047 << E->getType();
2048 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002049 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002050 return false;
2051}
2052
Richard Smithc667cdc2019-09-18 17:37:44 +00002053enum class CheckEvaluationResultKind {
2054 ConstantExpression,
2055 FullyInitialized,
2056};
2057
Reid Kleckner1a840d22018-05-10 18:57:35 +00002058static bool
Richard Smithc667cdc2019-09-18 17:37:44 +00002059CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
2060 SourceLocation DiagLoc, QualType Type,
2061 const APValue &Value, Expr::ConstExprUsage Usage,
2062 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002063 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002064 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002065 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002066 if (SubobjectLoc.isValid())
2067 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002068 return false;
2069 }
2070
Richard Smith77be48a2014-07-31 06:31:19 +00002071 // We allow _Atomic(T) to be initialized from anything that T can be
2072 // initialized from.
2073 if (const AtomicType *AT = Type->getAs<AtomicType>())
2074 Type = AT->getValueType();
2075
Richard Smithb228a862012-02-15 02:18:13 +00002076 // Core issue 1454: For a literal constant expression of array or class type,
2077 // each subobject of its value shall have been initialized by a constant
2078 // expression.
2079 if (Value.isArray()) {
2080 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2081 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002082 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2083 Value.getArrayInitializedElt(I), Usage,
2084 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00002085 return false;
2086 }
2087 if (!Value.hasArrayFiller())
2088 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00002089 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2090 Value.getArrayFiller(), Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00002091 }
Richard Smithb228a862012-02-15 02:18:13 +00002092 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002093 return CheckEvaluationResult(
2094 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2095 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00002096 }
2097 if (Value.isStruct()) {
2098 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2099 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2100 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002101 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002102 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2103 Value.getStructBase(BaseIndex), Usage,
2104 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00002105 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002106 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002107 }
2108 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002109 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002110 if (I->isUnnamedBitfield())
2111 continue;
2112
Richard Smithc667cdc2019-09-18 17:37:44 +00002113 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2114 Value.getStructField(I->getFieldIndex()),
2115 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00002116 return false;
2117 }
2118 }
2119
Richard Smithc667cdc2019-09-18 17:37:44 +00002120 if (Value.isLValue() &&
2121 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00002122 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002123 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002124 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002125 }
2126
Richard Smithc667cdc2019-09-18 17:37:44 +00002127 if (Value.isMemberPointer() &&
2128 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00002129 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002130
Richard Smithb228a862012-02-15 02:18:13 +00002131 // Everything else is fine.
2132 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002133}
2134
Richard Smithc667cdc2019-09-18 17:37:44 +00002135/// Check that this core constant expression value is a valid value for a
2136/// constant expression. If not, report an appropriate diagnostic. Does not
2137/// check that the expression is of literal type.
2138static bool
2139CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2140 const APValue &Value,
2141 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2142 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2143 Info, DiagLoc, Type, Value, Usage);
2144}
2145
2146/// Check that this evaluated value is fully-initialized and can be loaded by
2147/// an lvalue-to-rvalue conversion.
2148static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2149 QualType Type, const APValue &Value) {
2150 return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
2151 Info, DiagLoc, Type, Value,
2152 Expr::EvaluateForCodeGen);
2153}
2154
Richard Smithda1b4342019-09-27 01:26:47 +00002155/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2156/// "the allocated storage is deallocated within the evaluation".
2157static bool CheckMemoryLeaks(EvalInfo &Info) {
2158 if (!Info.HeapAllocs.empty()) {
2159 // We can still fold to a constant despite a compile-time memory leak,
2160 // so long as the heap allocation isn't referenced in the result (we check
2161 // that in CheckConstantExpression).
2162 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2163 diag::note_constexpr_memory_leak)
2164 << unsigned(Info.HeapAllocs.size() - 1);
2165 }
2166 return true;
2167}
2168
Richard Smith2e312c82012-03-03 22:46:17 +00002169static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002170 // A null base expression indicates a null pointer. These are always
2171 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002172 if (!Value.getLValueBase()) {
2173 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002174 return true;
2175 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002176
Richard Smith027bf112011-11-17 22:56:20 +00002177 // We have a non-null base. These are generally known to be true, but if it's
2178 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002179 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002180 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002181 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002182}
2183
Richard Smith2e312c82012-03-03 22:46:17 +00002184static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002185 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002186 case APValue::None:
2187 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002188 return false;
2189 case APValue::Int:
2190 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002191 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002192 case APValue::FixedPoint:
2193 Result = Val.getFixedPoint().getBoolValue();
2194 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002195 case APValue::Float:
2196 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002197 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002198 case APValue::ComplexInt:
2199 Result = Val.getComplexIntReal().getBoolValue() ||
2200 Val.getComplexIntImag().getBoolValue();
2201 return true;
2202 case APValue::ComplexFloat:
2203 Result = !Val.getComplexFloatReal().isZero() ||
2204 !Val.getComplexFloatImag().isZero();
2205 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002206 case APValue::LValue:
2207 return EvalPointerValueAsBool(Val, Result);
2208 case APValue::MemberPointer:
2209 Result = Val.getMemberPointerDecl();
2210 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002211 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002212 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002213 case APValue::Struct:
2214 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002215 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002216 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002217 }
2218
Richard Smith11562c52011-10-28 17:51:58 +00002219 llvm_unreachable("unknown APValue kind");
2220}
2221
2222static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2223 EvalInfo &Info) {
2224 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002225 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002226 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002227 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002228 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002229}
2230
Richard Smith357362d2011-12-13 06:39:58 +00002231template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002232static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002233 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002234 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002235 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002236 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002237}
2238
2239static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2240 QualType SrcType, const APFloat &Value,
2241 QualType DestType, APSInt &Result) {
2242 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002243 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002244 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002245
Richard Smith357362d2011-12-13 06:39:58 +00002246 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002247 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002248 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2249 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002250 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002251 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002252}
2253
Richard Smith357362d2011-12-13 06:39:58 +00002254static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2255 QualType SrcType, QualType DestType,
2256 APFloat &Result) {
2257 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002258 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002259 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2260 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002261 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002262}
2263
Richard Smith911e1422012-01-30 22:27:01 +00002264static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2265 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002266 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002267 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002268 // Figure out if this is a truncate, extend or noop cast.
2269 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002270 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002271 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002272 if (DestType->isBooleanType())
2273 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002274 return Result;
2275}
2276
Richard Smith357362d2011-12-13 06:39:58 +00002277static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2278 QualType SrcType, const APSInt &Value,
2279 QualType DestType, APFloat &Result) {
2280 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002281 Result.convertFromAPInt(Value, Value.isSigned(),
2282 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002283 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002284}
2285
Richard Smith49ca8aa2013-08-06 07:09:20 +00002286static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2287 APValue &Value, const FieldDecl *FD) {
2288 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2289
2290 if (!Value.isInt()) {
2291 // Trying to store a pointer-cast-to-integer into a bitfield.
2292 // FIXME: In this case, we should provide the diagnostic for casting
2293 // a pointer to an integer.
2294 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002295 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002296 return false;
2297 }
2298
2299 APSInt &Int = Value.getInt();
2300 unsigned OldBitWidth = Int.getBitWidth();
2301 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2302 if (NewBitWidth < OldBitWidth)
2303 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2304 return true;
2305}
2306
Eli Friedman803acb32011-12-22 03:51:45 +00002307static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2308 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002309 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002310 if (!Evaluate(SVal, Info, E))
2311 return false;
2312 if (SVal.isInt()) {
2313 Res = SVal.getInt();
2314 return true;
2315 }
2316 if (SVal.isFloat()) {
2317 Res = SVal.getFloat().bitcastToAPInt();
2318 return true;
2319 }
2320 if (SVal.isVector()) {
2321 QualType VecTy = E->getType();
2322 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2323 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2324 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2325 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2326 Res = llvm::APInt::getNullValue(VecSize);
2327 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2328 APValue &Elt = SVal.getVectorElt(i);
2329 llvm::APInt EltAsInt;
2330 if (Elt.isInt()) {
2331 EltAsInt = Elt.getInt();
2332 } else if (Elt.isFloat()) {
2333 EltAsInt = Elt.getFloat().bitcastToAPInt();
2334 } else {
2335 // Don't try to handle vectors of anything other than int or float
2336 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002337 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002338 return false;
2339 }
2340 unsigned BaseEltSize = EltAsInt.getBitWidth();
2341 if (BigEndian)
2342 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2343 else
2344 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2345 }
2346 return true;
2347 }
2348 // Give up if the input isn't an int, float, or vector. For example, we
2349 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002350 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002351 return false;
2352}
2353
Richard Smith43e77732013-05-07 04:50:00 +00002354/// Perform the given integer operation, which is known to need at most BitWidth
2355/// bits, and check for overflow in the original type (if that type was not an
2356/// unsigned type).
2357template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002358static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2359 const APSInt &LHS, const APSInt &RHS,
2360 unsigned BitWidth, Operation Op,
2361 APSInt &Result) {
2362 if (LHS.isUnsigned()) {
2363 Result = Op(LHS, RHS);
2364 return true;
2365 }
Richard Smith43e77732013-05-07 04:50:00 +00002366
2367 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002368 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002369 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002370 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002371 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002372 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002373 << Result.toString(10) << E->getType();
2374 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002375 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002376 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002377 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002378}
2379
2380/// Perform the given binary integer operation.
2381static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2382 BinaryOperatorKind Opcode, APSInt RHS,
2383 APSInt &Result) {
2384 switch (Opcode) {
2385 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002386 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002387 return false;
2388 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002389 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2390 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002391 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002392 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2393 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002394 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002395 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2396 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002397 case BO_And: Result = LHS & RHS; return true;
2398 case BO_Xor: Result = LHS ^ RHS; return true;
2399 case BO_Or: Result = LHS | RHS; return true;
2400 case BO_Div:
2401 case BO_Rem:
2402 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002403 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002404 return false;
2405 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002406 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2407 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2408 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002409 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2410 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002411 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2412 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002413 return true;
2414 case BO_Shl: {
2415 if (Info.getLangOpts().OpenCL)
2416 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2417 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2418 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2419 RHS.isUnsigned());
2420 else if (RHS.isSigned() && RHS.isNegative()) {
2421 // During constant-folding, a negative shift is an opposite shift. Such
2422 // a shift is not a constant expression.
2423 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2424 RHS = -RHS;
2425 goto shift_right;
2426 }
2427 shift_left:
2428 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2429 // the shifted type.
2430 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2431 if (SA != RHS) {
2432 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2433 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002434 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002435 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2436 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002437 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2438 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002439 if (LHS.isNegative())
2440 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2441 else if (LHS.countLeadingZeros() < SA)
2442 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2443 }
2444 Result = LHS << SA;
2445 return true;
2446 }
2447 case BO_Shr: {
2448 if (Info.getLangOpts().OpenCL)
2449 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2450 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2451 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2452 RHS.isUnsigned());
2453 else if (RHS.isSigned() && RHS.isNegative()) {
2454 // During constant-folding, a negative shift is an opposite shift. Such a
2455 // shift is not a constant expression.
2456 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2457 RHS = -RHS;
2458 goto shift_left;
2459 }
2460 shift_right:
2461 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2462 // shifted type.
2463 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2464 if (SA != RHS)
2465 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2466 << RHS << E->getType() << LHS.getBitWidth();
2467 Result = LHS >> SA;
2468 return true;
2469 }
2470
2471 case BO_LT: Result = LHS < RHS; return true;
2472 case BO_GT: Result = LHS > RHS; return true;
2473 case BO_LE: Result = LHS <= RHS; return true;
2474 case BO_GE: Result = LHS >= RHS; return true;
2475 case BO_EQ: Result = LHS == RHS; return true;
2476 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002477 case BO_Cmp:
2478 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002479 }
2480}
2481
Richard Smith861b5b52013-05-07 23:34:45 +00002482/// Perform the given binary floating-point operation, in-place, on LHS.
2483static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2484 APFloat &LHS, BinaryOperatorKind Opcode,
2485 const APFloat &RHS) {
2486 switch (Opcode) {
2487 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002488 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002489 return false;
2490 case BO_Mul:
2491 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2492 break;
2493 case BO_Add:
2494 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2495 break;
2496 case BO_Sub:
2497 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2498 break;
2499 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002500 // [expr.mul]p4:
2501 // If the second operand of / or % is zero the behavior is undefined.
2502 if (RHS.isZero())
2503 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002504 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2505 break;
2506 }
2507
Richard Smith9e52c432019-07-06 21:05:52 +00002508 // [expr.pre]p4:
2509 // If during the evaluation of an expression, the result is not
2510 // mathematically defined [...], the behavior is undefined.
2511 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2512 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002513 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002514 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002515 }
Richard Smith861b5b52013-05-07 23:34:45 +00002516 return true;
2517}
2518
Richard Smitha8105bc2012-01-06 16:39:00 +00002519/// Cast an lvalue referring to a base subobject to a derived class, by
2520/// truncating the lvalue's path to the given length.
2521static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2522 const RecordDecl *TruncatedType,
2523 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002524 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002525
2526 // Check we actually point to a derived class object.
2527 if (TruncatedElements == D.Entries.size())
2528 return true;
2529 assert(TruncatedElements >= D.MostDerivedPathLength &&
2530 "not casting to a derived class");
2531 if (!Result.checkSubobject(Info, E, CSK_Derived))
2532 return false;
2533
2534 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002535 const RecordDecl *RD = TruncatedType;
2536 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002537 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002538 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2539 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002540 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002541 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002542 else
Richard Smithd62306a2011-11-10 06:34:14 +00002543 Result.Offset -= Layout.getBaseClassOffset(Base);
2544 RD = Base;
2545 }
Richard Smith027bf112011-11-17 22:56:20 +00002546 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002547 return true;
2548}
2549
John McCalld7bca762012-05-01 00:38:49 +00002550static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002551 const CXXRecordDecl *Derived,
2552 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002553 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002554 if (!RL) {
2555 if (Derived->isInvalidDecl()) return false;
2556 RL = &Info.Ctx.getASTRecordLayout(Derived);
2557 }
2558
Richard Smithd62306a2011-11-10 06:34:14 +00002559 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002560 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002561 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002562}
2563
Richard Smitha8105bc2012-01-06 16:39:00 +00002564static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002565 const CXXRecordDecl *DerivedDecl,
2566 const CXXBaseSpecifier *Base) {
2567 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2568
John McCalld7bca762012-05-01 00:38:49 +00002569 if (!Base->isVirtual())
2570 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002571
Richard Smitha8105bc2012-01-06 16:39:00 +00002572 SubobjectDesignator &D = Obj.Designator;
2573 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002574 return false;
2575
Richard Smitha8105bc2012-01-06 16:39:00 +00002576 // Extract most-derived object and corresponding type.
2577 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2578 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2579 return false;
2580
2581 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002582 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002583 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2584 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002585 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002586 return true;
2587}
2588
Richard Smith84401042013-06-03 05:03:02 +00002589static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2590 QualType Type, LValue &Result) {
2591 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2592 PathE = E->path_end();
2593 PathI != PathE; ++PathI) {
2594 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2595 *PathI))
2596 return false;
2597 Type = (*PathI)->getType();
2598 }
2599 return true;
2600}
2601
Richard Smith921f1322019-05-13 23:35:21 +00002602/// Cast an lvalue referring to a derived class to a known base subobject.
2603static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2604 const CXXRecordDecl *DerivedRD,
2605 const CXXRecordDecl *BaseRD) {
2606 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2607 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2608 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2609 llvm_unreachable("Class must be derived from the passed in base class!");
2610
2611 for (CXXBasePathElement &Elem : Paths.front())
2612 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2613 return false;
2614 return true;
2615}
2616
Richard Smithd62306a2011-11-10 06:34:14 +00002617/// Update LVal to refer to the given field, which must be a member of the type
2618/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002619static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002620 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002621 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002622 if (!RL) {
2623 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002624 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002625 }
Richard Smithd62306a2011-11-10 06:34:14 +00002626
2627 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002628 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002629 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002630 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002631}
2632
Richard Smith1b78b3d2012-01-25 22:15:11 +00002633/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002634static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002635 LValue &LVal,
2636 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002637 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002638 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002639 return false;
2640 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002641}
2642
Richard Smithd62306a2011-11-10 06:34:14 +00002643/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002644static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2645 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002646 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2647 // extension.
2648 if (Type->isVoidType() || Type->isFunctionType()) {
2649 Size = CharUnits::One();
2650 return true;
2651 }
2652
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002653 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002654 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002655 return false;
2656 }
2657
Richard Smithd62306a2011-11-10 06:34:14 +00002658 if (!Type->isConstantSizeType()) {
2659 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002660 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002661 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002662 return false;
2663 }
2664
2665 Size = Info.Ctx.getTypeSizeInChars(Type);
2666 return true;
2667}
2668
2669/// Update a pointer value to model pointer arithmetic.
2670/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002671/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002672/// \param LVal - The pointer value to be updated.
2673/// \param EltTy - The pointee type represented by LVal.
2674/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002675static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2676 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002677 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002678 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002679 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002680 return false;
2681
Yaxun Liu402804b2016-12-15 08:09:08 +00002682 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002683 return true;
2684}
2685
Richard Smithd6cc1982017-01-31 02:23:02 +00002686static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2687 LValue &LVal, QualType EltTy,
2688 int64_t Adjustment) {
2689 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2690 APSInt::get(Adjustment));
2691}
2692
Richard Smith66c96992012-02-18 22:04:06 +00002693/// Update an lvalue to refer to a component of a complex number.
2694/// \param Info - Information about the ongoing evaluation.
2695/// \param LVal - The lvalue to be updated.
2696/// \param EltTy - The complex number's component type.
2697/// \param Imag - False for the real component, true for the imaginary.
2698static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2699 LValue &LVal, QualType EltTy,
2700 bool Imag) {
2701 if (Imag) {
2702 CharUnits SizeOfComponent;
2703 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2704 return false;
2705 LVal.Offset += SizeOfComponent;
2706 }
2707 LVal.addComplex(Info, E, EltTy, Imag);
2708 return true;
2709}
2710
Richard Smith27908702011-10-24 17:54:18 +00002711/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002712///
2713/// \param Info Information about the ongoing evaluation.
2714/// \param E An expression to be used when printing diagnostics.
2715/// \param VD The variable whose initializer should be obtained.
2716/// \param Frame The frame in which the variable was created. Must be null
2717/// if this variable is not local to the evaluation.
2718/// \param Result Filled in with a pointer to the value of the variable.
2719static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2720 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002721 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002722
Richard Smith254a73d2011-10-28 22:34:42 +00002723 // If this is a parameter to an active constexpr function call, perform
2724 // argument substitution.
2725 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002726 // Assume arguments of a potential constant expression are unknown
2727 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002728 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002729 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002730 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002731 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002732 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002733 }
Richard Smith3229b742013-05-05 21:17:10 +00002734 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002735 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002736 }
Richard Smith27908702011-10-24 17:54:18 +00002737
Richard Smithd9f663b2013-04-22 15:31:51 +00002738 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002739 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002740 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2741 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002742 if (!Result) {
2743 // Assume variables referenced within a lambda's call operator that were
2744 // not declared within the call operator are captures and during checking
2745 // of a potential constant expression, assume they are unknown constant
2746 // expressions.
2747 assert(isLambdaCallOperator(Frame->Callee) &&
2748 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2749 "missing value for local variable");
2750 if (Info.checkingPotentialConstantExpression())
2751 return false;
2752 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002753 Info.FFDiag(E->getBeginLoc(),
2754 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002755 << "captures not currently allowed";
2756 return false;
2757 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002758 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002759 }
2760
Richard Smithd0b4dd62011-12-19 06:19:21 +00002761 // Dig out the initializer, and use the declaration which it's attached to.
2762 const Expr *Init = VD->getAnyInitializer(VD);
2763 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002764 // If we're checking a potential constant expression, the variable could be
2765 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002766 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002767 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002768 return false;
2769 }
2770
Richard Smithd62306a2011-11-10 06:34:14 +00002771 // If we're currently evaluating the initializer of this declaration, use that
2772 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002773 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002774 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002775 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002776 }
2777
Richard Smithcecf1842011-11-01 21:06:14 +00002778 // Never evaluate the initializer of a weak variable. We can't be sure that
2779 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002780 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002781 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002782 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002783 }
Richard Smithcecf1842011-11-01 21:06:14 +00002784
Richard Smithd0b4dd62011-12-19 06:19:21 +00002785 // Check that we can fold the initializer. In C++, we will have already done
2786 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002787 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002788 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002789 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002790 Notes.size() + 1) << VD;
2791 Info.Note(VD->getLocation(), diag::note_declared_at);
2792 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002793 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002794 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002795 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002796 Notes.size() + 1) << VD;
2797 Info.Note(VD->getLocation(), diag::note_declared_at);
2798 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002799 }
Richard Smith27908702011-10-24 17:54:18 +00002800
Richard Smith3229b742013-05-05 21:17:10 +00002801 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002802 return true;
Richard Smith27908702011-10-24 17:54:18 +00002803}
2804
Richard Smith11562c52011-10-28 17:51:58 +00002805static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002806 Qualifiers Quals = T.getQualifiers();
2807 return Quals.hasConst() && !Quals.hasVolatile();
2808}
2809
Richard Smithe97cbd72011-11-11 04:05:33 +00002810/// Get the base index of the given base class within an APValue representing
2811/// the given derived class.
2812static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2813 const CXXRecordDecl *Base) {
2814 Base = Base->getCanonicalDecl();
2815 unsigned Index = 0;
2816 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2817 E = Derived->bases_end(); I != E; ++I, ++Index) {
2818 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2819 return Index;
2820 }
2821
2822 llvm_unreachable("base class missing from derived class's bases list");
2823}
2824
Richard Smith3da88fa2013-04-26 14:36:30 +00002825/// Extract the value of a character from a string literal.
2826static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2827 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002828 assert(!isa<SourceLocExpr>(Lit) &&
2829 "SourceLocExpr should have already been converted to a StringLiteral");
2830
Akira Hatanakabc332642017-01-31 02:31:39 +00002831 // FIXME: Support MakeStringConstant
2832 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2833 std::string Str;
2834 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2835 assert(Index <= Str.size() && "Index too large");
2836 return APSInt::getUnsigned(Str.c_str()[Index]);
2837 }
2838
Alexey Bataevec474782014-10-09 08:45:04 +00002839 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2840 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 const StringLiteral *S = cast<StringLiteral>(Lit);
2842 const ConstantArrayType *CAT =
2843 Info.Ctx.getAsConstantArrayType(S->getType());
2844 assert(CAT && "string literal isn't an array");
2845 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002846 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002847
2848 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002849 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002850 if (Index < S->getLength())
2851 Value = S->getCodeUnit(Index);
2852 return Value;
2853}
2854
Richard Smith3da88fa2013-04-26 14:36:30 +00002855// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002856//
2857// FIXME: This is inefficient; we should probably introduce something similar
2858// to the LLVM ConstantDataArray to make this cheaper.
2859static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smithda1b4342019-09-27 01:26:47 +00002860 APValue &Result,
2861 QualType AllocType = QualType()) {
2862 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2863 AllocType.isNull() ? S->getType() : AllocType);
Richard Smith3da88fa2013-04-26 14:36:30 +00002864 assert(CAT && "string literal isn't an array");
2865 QualType CharType = CAT->getElementType();
2866 assert(CharType->isIntegerType() && "unexpected character type");
2867
2868 unsigned Elts = CAT->getSize().getZExtValue();
2869 Result = APValue(APValue::UninitArray(),
2870 std::min(S->getLength(), Elts), Elts);
2871 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2872 CharType->isUnsignedIntegerType());
2873 if (Result.hasArrayFiller())
2874 Result.getArrayFiller() = APValue(Value);
2875 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2876 Value = S->getCodeUnit(I);
2877 Result.getArrayInitializedElt(I) = APValue(Value);
2878 }
2879}
2880
2881// Expand an array so that it has more than Index filled elements.
2882static void expandArray(APValue &Array, unsigned Index) {
2883 unsigned Size = Array.getArraySize();
2884 assert(Index < Size);
2885
2886 // Always at least double the number of elements for which we store a value.
2887 unsigned OldElts = Array.getArrayInitializedElts();
2888 unsigned NewElts = std::max(Index+1, OldElts * 2);
2889 NewElts = std::min(Size, std::max(NewElts, 8u));
2890
2891 // Copy the data across.
2892 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2893 for (unsigned I = 0; I != OldElts; ++I)
2894 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2895 for (unsigned I = OldElts; I != NewElts; ++I)
2896 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2897 if (NewValue.hasArrayFiller())
2898 NewValue.getArrayFiller() = Array.getArrayFiller();
2899 Array.swap(NewValue);
2900}
2901
Richard Smithb01fe402014-09-16 01:24:02 +00002902/// Determine whether a type would actually be read by an lvalue-to-rvalue
2903/// conversion. If it's of class type, we may assume that the copy operation
2904/// is trivial. Note that this is never true for a union type with fields
2905/// (because the copy always "reads" the active member) and always true for
2906/// a non-class type.
2907static bool isReadByLvalueToRvalueConversion(QualType T) {
2908 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2909 if (!RD || (RD->isUnion() && !RD->field_empty()))
2910 return true;
2911 if (RD->isEmpty())
2912 return false;
2913
2914 for (auto *Field : RD->fields())
2915 if (isReadByLvalueToRvalueConversion(Field->getType()))
2916 return true;
2917
2918 for (auto &BaseSpec : RD->bases())
2919 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2920 return true;
2921
2922 return false;
2923}
2924
2925/// Diagnose an attempt to read from any unreadable field within the specified
2926/// type, which might be a class type.
Richard Smith2b4fa532019-09-29 05:08:46 +00002927static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
2928 QualType T) {
Richard Smithb01fe402014-09-16 01:24:02 +00002929 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2930 if (!RD)
2931 return false;
2932
2933 if (!RD->hasMutableFields())
2934 return false;
2935
2936 for (auto *Field : RD->fields()) {
2937 // If we're actually going to read this field in some way, then it can't
2938 // be mutable. If we're in a union, then assigning to a mutable field
2939 // (even an empty one) can change the active member, so that's not OK.
2940 // FIXME: Add core issue number for the union case.
2941 if (Field->isMutable() &&
2942 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Richard Smith2b4fa532019-09-29 05:08:46 +00002943 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002944 Info.Note(Field->getLocation(), diag::note_declared_at);
2945 return true;
2946 }
2947
Richard Smith2b4fa532019-09-29 05:08:46 +00002948 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00002949 return true;
2950 }
2951
2952 for (auto &BaseSpec : RD->bases())
Richard Smith2b4fa532019-09-29 05:08:46 +00002953 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00002954 return true;
2955
2956 // All mutable fields were empty, and thus not actually read.
2957 return false;
2958}
2959
Richard Smithdebad642019-05-12 09:39:08 +00002960static bool lifetimeStartedInEvaluation(EvalInfo &Info,
Richard Smith2b4fa532019-09-29 05:08:46 +00002961 APValue::LValueBase Base,
2962 bool MutableSubobject = false) {
Richard Smithdebad642019-05-12 09:39:08 +00002963 // A temporary we created.
2964 if (Base.getCallIndex())
2965 return true;
2966
2967 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2968 if (!Evaluating)
2969 return false;
2970
Richard Smith2b4fa532019-09-29 05:08:46 +00002971 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
Richard Smithdebad642019-05-12 09:39:08 +00002972
Richard Smith2b4fa532019-09-29 05:08:46 +00002973 switch (Info.IsEvaluatingDecl) {
2974 case EvalInfo::EvaluatingDeclKind::None:
2975 return false;
Richard Smithdebad642019-05-12 09:39:08 +00002976
Richard Smith2b4fa532019-09-29 05:08:46 +00002977 case EvalInfo::EvaluatingDeclKind::Ctor:
2978 // The variable whose initializer we're evaluating.
2979 if (BaseD)
2980 return declaresSameEntity(Evaluating, BaseD);
2981
2982 // A temporary lifetime-extended by the variable whose initializer we're
2983 // evaluating.
2984 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2985 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2986 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
2987 return false;
2988
2989 case EvalInfo::EvaluatingDeclKind::Dtor:
2990 // C++2a [expr.const]p6:
2991 // [during constant destruction] the lifetime of a and its non-mutable
2992 // subobjects (but not its mutable subobjects) [are] considered to start
2993 // within e.
2994 //
2995 // FIXME: We can meaningfully extend this to cover non-const objects, but
2996 // we will need special handling: we should be able to access only
2997 // subobjects of such objects that are themselves declared const.
2998 if (!BaseD ||
2999 !(BaseD->getType().isConstQualified() ||
3000 BaseD->getType()->isReferenceType()) ||
3001 MutableSubobject)
3002 return false;
3003 return declaresSameEntity(Evaluating, BaseD);
3004 }
3005
3006 llvm_unreachable("unknown evaluating decl kind");
Richard Smithdebad642019-05-12 09:39:08 +00003007}
3008
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003009namespace {
Richard Smith3229b742013-05-05 21:17:10 +00003010/// A handle to a complete object (an object that is not a subobject of
3011/// another object).
3012struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003013 /// The identity of the object.
3014 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00003015 /// The value of the complete object.
3016 APValue *Value;
3017 /// The type of the complete object.
3018 QualType Type;
3019
Craig Topper36250ad2014-05-12 05:36:57 +00003020 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00003021 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3022 : Base(Base), Value(Value), Type(Type) {}
3023
Richard Smith2b4fa532019-09-29 05:08:46 +00003024 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
Richard Smithdebad642019-05-12 09:39:08 +00003025 // In C++14 onwards, it is permitted to read a mutable member whose
3026 // lifetime began within the evaluation.
3027 // FIXME: Should we also allow this in C++11?
3028 if (!Info.getLangOpts().CPlusPlus14)
3029 return false;
Richard Smith2b4fa532019-09-29 05:08:46 +00003030 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
Richard Smith3229b742013-05-05 21:17:10 +00003031 }
3032
Richard Smithdebad642019-05-12 09:39:08 +00003033 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00003034};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003035} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00003036
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003037static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3038 bool IsMutable = false) {
3039 // C++ [basic.type.qualifier]p1:
3040 // - A const object is an object of type const T or a non-mutable subobject
3041 // of a const object.
3042 if (ObjType.isConstQualified() && !IsMutable)
3043 SubobjType.addConst();
3044 // - A volatile object is an object of type const T or a subobject of a
3045 // volatile object.
3046 if (ObjType.isVolatileQualified())
3047 SubobjType.addVolatile();
3048 return SubobjType;
3049}
3050
Richard Smith3da88fa2013-04-26 14:36:30 +00003051/// Find the designated sub-object of an rvalue.
3052template<typename SubobjectHandler>
3053typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00003054findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003055 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003056 if (Sub.Invalid)
3057 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00003058 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00003059 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003060 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00003061 Info.FFDiag(E, Sub.isOnePastTheEnd()
3062 ? diag::note_constexpr_access_past_end
3063 : diag::note_constexpr_access_unsized_array)
3064 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003065 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003066 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003067 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00003068 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003069
Richard Smith3229b742013-05-05 21:17:10 +00003070 APValue *O = Obj.Value;
3071 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00003072 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003073 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003074
Richard Smithd62306a2011-11-10 06:34:14 +00003075 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003076 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003077 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithc667cdc2019-09-18 17:37:44 +00003078 if (O->isAbsent() ||
3079 (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
3080 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003081 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003082 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003083 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003084 return handler.failed();
3085 }
3086
Richard Smith457226e2019-09-23 03:48:44 +00003087 // C++ [class.ctor]p5, C++ [class.dtor]p5:
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003088 // const and volatile semantics are not applied on an object under
Richard Smith457226e2019-09-23 03:48:44 +00003089 // {con,de}struction.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003090 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3091 ObjType->isRecordType() &&
Richard Smith457226e2019-09-23 03:48:44 +00003092 Info.isEvaluatingCtorDtor(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003093 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3094 Sub.Entries.begin() + I)) !=
3095 ConstructionPhase::None) {
3096 ObjType = Info.Ctx.getCanonicalType(ObjType);
3097 ObjType.removeLocalConst();
3098 ObjType.removeLocalVolatile();
3099 }
3100
3101 // If this is our last pass, check that the final object type is OK.
3102 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3103 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003104 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003105 if (Info.getLangOpts().CPlusPlus) {
3106 int DiagKind;
3107 SourceLocation Loc;
3108 const NamedDecl *Decl = nullptr;
3109 if (VolatileField) {
3110 DiagKind = 2;
3111 Loc = VolatileField->getLocation();
3112 Decl = VolatileField;
3113 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3114 DiagKind = 1;
3115 Loc = VD->getLocation();
3116 Decl = VD;
3117 } else {
3118 DiagKind = 0;
3119 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3120 Loc = E->getExprLoc();
3121 }
3122 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3123 << handler.AccessKind << DiagKind << Decl;
3124 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3125 } else {
3126 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3127 }
3128 return handler.failed();
3129 }
3130
Richard Smithb01fe402014-09-16 01:24:02 +00003131 // If we are reading an object of class type, there may still be more
3132 // things we need to check: if there are any mutable subobjects, we
3133 // cannot perform this read. (This only happens when performing a trivial
3134 // copy or assignment.)
Richard Smith2b4fa532019-09-29 05:08:46 +00003135 if (ObjType->isRecordType() &&
3136 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3137 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003138 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003139 }
Richard Smithb01fe402014-09-16 01:24:02 +00003140
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003141 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003142 if (!handler.found(*O, ObjType))
3143 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003144
Richard Smith49ca8aa2013-08-06 07:09:20 +00003145 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003146 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003147 LastField && LastField->isBitField() &&
3148 !truncateBitfieldValue(Info, E, *O, LastField))
3149 return false;
3150
3151 return true;
3152 }
3153
Craig Topper36250ad2014-05-12 05:36:57 +00003154 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003155 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003156 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003157 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003158 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003159 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003160 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003161 // Note, it should not be possible to form a pointer with a valid
3162 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003163 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003164 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003165 << handler.AccessKind;
3166 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003167 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003168 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003169 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003170
3171 ObjType = CAT->getElementType();
3172
Richard Smith3da88fa2013-04-26 14:36:30 +00003173 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003174 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00003175 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003176 expandArray(*O, Index);
3177 O = &O->getArrayInitializedElt(Index);
3178 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003179 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003180 } else if (ObjType->isAnyComplexType()) {
3181 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003182 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003183 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003184 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003185 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003186 << handler.AccessKind;
3187 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003188 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003189 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003190 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003191
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003192 ObjType = getSubobjectType(
3193 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003194
Richard Smith66c96992012-02-18 22:04:06 +00003195 assert(I == N - 1 && "extracting subobject of scalar?");
3196 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003197 return handler.found(Index ? O->getComplexIntImag()
3198 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003199 } else {
3200 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003201 return handler.found(Index ? O->getComplexFloatImag()
3202 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003203 }
Richard Smithd62306a2011-11-10 06:34:14 +00003204 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003205 if (Field->isMutable() &&
3206 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3207 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3208 << handler.AccessKind << Field;
Richard Smith5a294e62012-02-09 03:29:58 +00003209 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003210 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003211 }
3212
Richard Smithd62306a2011-11-10 06:34:14 +00003213 // Next subobject is a class, struct or union field.
3214 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3215 if (RD->isUnion()) {
3216 const FieldDecl *UnionField = O->getUnionField();
3217 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003218 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith61422f92019-09-27 20:24:36 +00003219 // FIXME: If O->getUnionValue() is absent, report that there's no
3220 // active union member rather than reporting the prior active union
3221 // member. We'll need to fix nullptr_t to not use APValue() as its
3222 // representation first.
Faisal Valie690b7a2016-07-02 22:34:24 +00003223 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003224 << handler.AccessKind << Field << !UnionField << UnionField;
3225 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003226 }
Richard Smithd62306a2011-11-10 06:34:14 +00003227 O = &O->getUnionValue();
3228 } else
3229 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003230
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003231 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003232 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003233 if (Field->getType().isVolatileQualified())
3234 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003235 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003236 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003237 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3238 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3239 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003240
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003241 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003242 }
3243 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003244}
3245
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003246namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003247struct ExtractSubobjectHandler {
3248 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003249 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003250 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003251 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003252
3253 typedef bool result_type;
3254 bool failed() { return false; }
3255 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003256 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003257 if (AccessKind == AK_ReadObjectRepresentation)
3258 return true;
3259 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003260 }
3261 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003262 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003263 return true;
3264 }
3265 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003266 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003267 return true;
3268 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003269};
Richard Smith3229b742013-05-05 21:17:10 +00003270} // end anonymous namespace
3271
Richard Smith3da88fa2013-04-26 14:36:30 +00003272/// Extract the designated sub-object of an rvalue.
3273static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003274 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003275 const SubobjectDesignator &Sub, APValue &Result,
3276 AccessKinds AK = AK_Read) {
3277 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3278 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003279 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003280}
3281
Richard Smith3229b742013-05-05 21:17:10 +00003282namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003283struct ModifySubobjectHandler {
3284 EvalInfo &Info;
3285 APValue &NewVal;
3286 const Expr *E;
3287
3288 typedef bool result_type;
3289 static const AccessKinds AccessKind = AK_Assign;
3290
3291 bool checkConst(QualType QT) {
3292 // Assigning to a const object has undefined behavior.
3293 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003294 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003295 return false;
3296 }
3297 return true;
3298 }
3299
3300 bool failed() { return false; }
3301 bool found(APValue &Subobj, QualType SubobjType) {
3302 if (!checkConst(SubobjType))
3303 return false;
3304 // We've been given ownership of NewVal, so just swap it in.
3305 Subobj.swap(NewVal);
3306 return true;
3307 }
3308 bool found(APSInt &Value, QualType SubobjType) {
3309 if (!checkConst(SubobjType))
3310 return false;
3311 if (!NewVal.isInt()) {
3312 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003313 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003314 return false;
3315 }
3316 Value = NewVal.getInt();
3317 return true;
3318 }
3319 bool found(APFloat &Value, QualType SubobjType) {
3320 if (!checkConst(SubobjType))
3321 return false;
3322 Value = NewVal.getFloat();
3323 return true;
3324 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003325};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003326} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003327
Richard Smith3229b742013-05-05 21:17:10 +00003328const AccessKinds ModifySubobjectHandler::AccessKind;
3329
Richard Smith3da88fa2013-04-26 14:36:30 +00003330/// Update the designated sub-object of an rvalue to the given value.
3331static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003332 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003333 const SubobjectDesignator &Sub,
3334 APValue &NewVal) {
3335 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003336 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003337}
3338
Richard Smith84f6dcf2012-02-02 01:16:57 +00003339/// Find the position where two subobject designators diverge, or equivalently
3340/// the length of the common initial subsequence.
3341static unsigned FindDesignatorMismatch(QualType ObjType,
3342 const SubobjectDesignator &A,
3343 const SubobjectDesignator &B,
3344 bool &WasArrayIndex) {
3345 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3346 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003347 if (!ObjType.isNull() &&
3348 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003349 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003350 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003351 WasArrayIndex = true;
3352 return I;
3353 }
Richard Smith66c96992012-02-18 22:04:06 +00003354 if (ObjType->isAnyComplexType())
3355 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3356 else
3357 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003358 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003359 if (A.Entries[I].getAsBaseOrMember() !=
3360 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003361 WasArrayIndex = false;
3362 return I;
3363 }
3364 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3365 // Next subobject is a field.
3366 ObjType = FD->getType();
3367 else
3368 // Next subobject is a base class.
3369 ObjType = QualType();
3370 }
3371 }
3372 WasArrayIndex = false;
3373 return I;
3374}
3375
3376/// Determine whether the given subobject designators refer to elements of the
3377/// same array object.
3378static bool AreElementsOfSameArray(QualType ObjType,
3379 const SubobjectDesignator &A,
3380 const SubobjectDesignator &B) {
3381 if (A.Entries.size() != B.Entries.size())
3382 return false;
3383
George Burgess IVa51c4072015-10-16 01:49:01 +00003384 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003385 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3386 // A is a subobject of the array element.
3387 return false;
3388
3389 // If A (and B) designates an array element, the last entry will be the array
3390 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3391 // of length 1' case, and the entire path must match.
3392 bool WasArrayIndex;
3393 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3394 return CommonLength >= A.Entries.size() - IsArray;
3395}
3396
Richard Smith3229b742013-05-05 21:17:10 +00003397/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003398static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3399 AccessKinds AK, const LValue &LVal,
3400 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003401 if (LVal.InvalidBase) {
3402 Info.FFDiag(E);
3403 return CompleteObject();
3404 }
3405
Richard Smith3229b742013-05-05 21:17:10 +00003406 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003407 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003408 return CompleteObject();
3409 }
3410
Craig Topper36250ad2014-05-12 05:36:57 +00003411 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003412 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003413 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003414 std::tie(Frame, Depth) =
3415 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003416 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003417 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003418 << AK << LVal.Base.is<const ValueDecl*>();
3419 NoteLValueLocation(Info, LVal.Base);
3420 return CompleteObject();
3421 }
Richard Smith3229b742013-05-05 21:17:10 +00003422 }
3423
Richard Smith61422f92019-09-27 20:24:36 +00003424 bool IsAccess = isAnyAccess(AK);
Richard Smith7bd54ab2019-05-15 20:22:21 +00003425
Richard Smith3229b742013-05-05 21:17:10 +00003426 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3427 // is not a constant expression (even if the object is non-volatile). We also
3428 // apply this rule to C++98, in order to conform to the expected 'volatile'
3429 // semantics.
Richard Smith61422f92019-09-27 20:24:36 +00003430 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003431 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003432 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003433 << AK << LValType;
3434 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003435 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003436 return CompleteObject();
3437 }
3438
3439 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003440 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003441 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003442
3443 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3444 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3445 // In C++11, constexpr, non-volatile variables initialized with constant
3446 // expressions are constant expressions too. Inside constexpr functions,
3447 // parameters are constant expressions even if they're non-const.
3448 // In C++1y, objects local to a constant expression (those with a Frame) are
3449 // both readable and writable inside constant expressions.
3450 // In C, such things can also be folded, although they are not ICEs.
3451 const VarDecl *VD = dyn_cast<VarDecl>(D);
3452 if (VD) {
3453 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3454 VD = VDef;
3455 }
3456 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003457 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003458 return CompleteObject();
3459 }
3460
Richard Smith3229b742013-05-05 21:17:10 +00003461 // Unless we're looking at a local variable or argument in a constexpr call,
3462 // the variable we're reading must be const.
3463 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003464 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003465 lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003466 // OK, we can read and modify an object if we're in the process of
3467 // evaluating its initializer, because its lifetime began in this
3468 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003469 } else if (isModification(AK)) {
3470 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003471 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003472 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003473 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003474 // OK, we can read this variable.
3475 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003476 // In OpenCL if a variable is in constant address space it is a const
3477 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003478 if (!(BaseType.isConstQualified() ||
3479 (Info.getLangOpts().OpenCL &&
3480 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003481 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003482 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003483 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003484 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003485 Info.Note(VD->getLocation(), diag::note_declared_at);
3486 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003487 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003488 }
3489 return CompleteObject();
3490 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003491 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003492 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003493 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3494 // We support folding of const floating-point types, in order to make
3495 // static const data members of such types (supported as an extension)
3496 // more useful.
3497 if (Info.getLangOpts().CPlusPlus11) {
3498 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3499 Info.Note(VD->getLocation(), diag::note_declared_at);
3500 } else {
3501 Info.CCEDiag(E);
3502 }
George Burgess IVb5316982016-12-27 05:33:20 +00003503 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3504 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3505 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003506 } else {
3507 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003508 if (Info.checkingPotentialConstantExpression() &&
3509 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3510 // The definition of this variable could be constexpr. We can't
3511 // access it right now, but may be able to in future.
3512 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003513 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003514 Info.Note(VD->getLocation(), diag::note_declared_at);
3515 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003516 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003517 }
3518 return CompleteObject();
3519 }
3520 }
3521
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003522 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003523 return CompleteObject();
Richard Smithda1b4342019-09-27 01:26:47 +00003524 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3525 Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3526 if (!Alloc) {
3527 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3528 return CompleteObject();
3529 }
3530 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3531 LVal.Base.getDynamicAllocType());
Richard Smith3229b742013-05-05 21:17:10 +00003532 } else {
3533 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3534
3535 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003536 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003537 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003538 assert(MTE->getStorageDuration() == SD_Static &&
3539 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003540
Richard Smithe6c01442013-06-05 00:46:14 +00003541 // Per C++1y [expr.const]p2:
3542 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3543 // - a [...] glvalue of integral or enumeration type that refers to
3544 // a non-volatile const object [...]
3545 // [...]
3546 // - a [...] glvalue of literal type that refers to a non-volatile
3547 // object whose lifetime began within the evaluation of e.
3548 //
3549 // C++11 misses the 'began within the evaluation of e' check and
3550 // instead allows all temporaries, including things like:
3551 // int &&r = 1;
3552 // int x = ++r;
3553 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003554 // Therefore we use the C++14 rules in C++11 too.
Richard Smith2b4fa532019-09-29 05:08:46 +00003555 //
3556 // Note that temporaries whose lifetimes began while evaluating a
3557 // variable's constructor are not usable while evaluating the
3558 // corresponding destructor, not even if they're of const-qualified
3559 // types.
Richard Smithe6c01442013-06-05 00:46:14 +00003560 if (!(BaseType.isConstQualified() &&
3561 BaseType->isIntegralOrEnumerationType()) &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003562 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003563 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003564 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003565 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003566 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3567 return CompleteObject();
3568 }
3569
3570 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3571 assert(BaseVal && "got reference to unevaluated temporary");
3572 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003573 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003574 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003575 APValue Val;
3576 LVal.moveInto(Val);
3577 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3578 << AK
3579 << Val.getAsString(Info.Ctx,
3580 Info.Ctx.getLValueReferenceType(LValType));
3581 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003582 return CompleteObject();
3583 }
3584 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003585 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003586 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003587 }
Richard Smith7525ff62013-05-09 07:14:00 +00003588 }
3589
Richard Smith9defb7d2018-02-21 03:38:30 +00003590 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003591 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003592 //
3593 // FIXME: Not all local state is mutable. Allow local constant subobjects
3594 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003595 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3596 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003597 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003598 return CompleteObject();
3599
Richard Smithdebad642019-05-12 09:39:08 +00003600 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003601}
3602
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003603/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003604/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3605/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003606///
3607/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003608/// \param Conv - The expression for which we are performing the conversion.
3609/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003610/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3611/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003612/// \param LVal - The glvalue on which we are attempting to perform this action.
3613/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003614/// \param WantObjectRepresentation - If true, we're looking for the object
3615/// representation rather than the value, and in particular,
3616/// there is no requirement that the result be fully initialized.
3617static bool
3618handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3619 const LValue &LVal, APValue &RVal,
3620 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003621 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003622 return false;
3623
Richard Smith3229b742013-05-05 21:17:10 +00003624 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003625 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003626
Richard Smithc667cdc2019-09-18 17:37:44 +00003627 AccessKinds AK =
3628 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3629
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003630 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003631 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3632 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3633 // initializer until now for such expressions. Such an expression can't be
3634 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003635 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003636 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003637 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003638 }
Richard Smith3229b742013-05-05 21:17:10 +00003639 APValue Lit;
3640 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3641 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003642 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003643 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003644 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003645 // Special-case character extraction so we don't have to construct an
3646 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003647 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003648 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003649 if (LVal.Designator.Entries.empty()) {
3650 // Fail for now for LValue to RValue conversion of an array.
3651 // (This shouldn't show up in C/C++, but it could be triggered by a
3652 // weird EvaluateAsRValue call from a tool.)
3653 Info.FFDiag(Conv);
3654 return false;
3655 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003656 if (LVal.Designator.isOnePastTheEnd()) {
3657 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003658 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003659 else
3660 Info.FFDiag(Conv);
3661 return false;
3662 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003663 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003664 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3665 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003666 }
Richard Smith11562c52011-10-28 17:51:58 +00003667 }
3668
Richard Smithc667cdc2019-09-18 17:37:44 +00003669 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3670 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003671}
3672
3673/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003674static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003675 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003676 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003677 return false;
3678
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003679 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003680 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003681 return false;
3682 }
3683
Richard Smith3229b742013-05-05 21:17:10 +00003684 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003685 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3686}
3687
3688namespace {
3689struct CompoundAssignSubobjectHandler {
3690 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003691 const Expr *E;
3692 QualType PromotedLHSType;
3693 BinaryOperatorKind Opcode;
3694 const APValue &RHS;
3695
3696 static const AccessKinds AccessKind = AK_Assign;
3697
3698 typedef bool result_type;
3699
3700 bool checkConst(QualType QT) {
3701 // Assigning to a const object has undefined behavior.
3702 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003703 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003704 return false;
3705 }
3706 return true;
3707 }
3708
3709 bool failed() { return false; }
3710 bool found(APValue &Subobj, QualType SubobjType) {
3711 switch (Subobj.getKind()) {
3712 case APValue::Int:
3713 return found(Subobj.getInt(), SubobjType);
3714 case APValue::Float:
3715 return found(Subobj.getFloat(), SubobjType);
3716 case APValue::ComplexInt:
3717 case APValue::ComplexFloat:
3718 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003719 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003720 return false;
3721 case APValue::LValue:
3722 return foundPointer(Subobj, SubobjType);
3723 default:
3724 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003725 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003726 return false;
3727 }
3728 }
3729 bool found(APSInt &Value, QualType SubobjType) {
3730 if (!checkConst(SubobjType))
3731 return false;
3732
Tan S. B.9f935e82018-12-18 07:38:06 +00003733 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003734 // We don't support compound assignment on integer-cast-to-pointer
3735 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003736 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003737 return false;
3738 }
3739
Tan S. B.9f935e82018-12-18 07:38:06 +00003740 if (RHS.isInt()) {
3741 APSInt LHS =
3742 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3743 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3744 return false;
3745 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3746 return true;
3747 } else if (RHS.isFloat()) {
3748 APFloat FValue(0.0);
3749 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3750 FValue) &&
3751 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3752 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3753 Value);
3754 }
3755
3756 Info.FFDiag(E);
3757 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003758 }
3759 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003760 return checkConst(SubobjType) &&
3761 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3762 Value) &&
3763 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3764 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003765 }
3766 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3767 if (!checkConst(SubobjType))
3768 return false;
3769
3770 QualType PointeeType;
3771 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3772 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003773
3774 if (PointeeType.isNull() || !RHS.isInt() ||
3775 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003776 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003777 return false;
3778 }
3779
Richard Smithd6cc1982017-01-31 02:23:02 +00003780 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003781 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003782 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003783
3784 LValue LVal;
3785 LVal.setFrom(Info.Ctx, Subobj);
3786 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3787 return false;
3788 LVal.moveInto(Subobj);
3789 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003790 }
Richard Smith43e77732013-05-07 04:50:00 +00003791};
3792} // end anonymous namespace
3793
3794const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3795
3796/// Perform a compound assignment of LVal <op>= RVal.
3797static bool handleCompoundAssignment(
3798 EvalInfo &Info, const Expr *E,
3799 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3800 BinaryOperatorKind Opcode, const APValue &RVal) {
3801 if (LVal.Designator.Invalid)
3802 return false;
3803
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003804 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003805 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003806 return false;
3807 }
3808
3809 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3810 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3811 RVal };
3812 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3813}
3814
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003815namespace {
3816struct IncDecSubobjectHandler {
3817 EvalInfo &Info;
3818 const UnaryOperator *E;
3819 AccessKinds AccessKind;
3820 APValue *Old;
3821
Richard Smith243ef902013-05-05 23:31:59 +00003822 typedef bool result_type;
3823
3824 bool checkConst(QualType QT) {
3825 // Assigning to a const object has undefined behavior.
3826 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003827 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003828 return false;
3829 }
3830 return true;
3831 }
3832
3833 bool failed() { return false; }
3834 bool found(APValue &Subobj, QualType SubobjType) {
3835 // Stash the old value. Also clear Old, so we don't clobber it later
3836 // if we're post-incrementing a complex.
3837 if (Old) {
3838 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003839 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003840 }
3841
3842 switch (Subobj.getKind()) {
3843 case APValue::Int:
3844 return found(Subobj.getInt(), SubobjType);
3845 case APValue::Float:
3846 return found(Subobj.getFloat(), SubobjType);
3847 case APValue::ComplexInt:
3848 return found(Subobj.getComplexIntReal(),
3849 SubobjType->castAs<ComplexType>()->getElementType()
3850 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3851 case APValue::ComplexFloat:
3852 return found(Subobj.getComplexFloatReal(),
3853 SubobjType->castAs<ComplexType>()->getElementType()
3854 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3855 case APValue::LValue:
3856 return foundPointer(Subobj, SubobjType);
3857 default:
3858 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003859 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003860 return false;
3861 }
3862 }
3863 bool found(APSInt &Value, QualType SubobjType) {
3864 if (!checkConst(SubobjType))
3865 return false;
3866
3867 if (!SubobjType->isIntegerType()) {
3868 // We don't support increment / decrement on integer-cast-to-pointer
3869 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003870 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003871 return false;
3872 }
3873
3874 if (Old) *Old = APValue(Value);
3875
3876 // bool arithmetic promotes to int, and the conversion back to bool
3877 // doesn't reduce mod 2^n, so special-case it.
3878 if (SubobjType->isBooleanType()) {
3879 if (AccessKind == AK_Increment)
3880 Value = 1;
3881 else
3882 Value = !Value;
3883 return true;
3884 }
3885
3886 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003887 if (AccessKind == AK_Increment) {
3888 ++Value;
3889
3890 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3891 APSInt ActualValue(Value, /*IsUnsigned*/true);
3892 return HandleOverflow(Info, E, ActualValue, SubobjType);
3893 }
3894 } else {
3895 --Value;
3896
3897 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3898 unsigned BitWidth = Value.getBitWidth();
3899 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3900 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003901 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003902 }
3903 }
3904 return true;
3905 }
3906 bool found(APFloat &Value, QualType SubobjType) {
3907 if (!checkConst(SubobjType))
3908 return false;
3909
3910 if (Old) *Old = APValue(Value);
3911
3912 APFloat One(Value.getSemantics(), 1);
3913 if (AccessKind == AK_Increment)
3914 Value.add(One, APFloat::rmNearestTiesToEven);
3915 else
3916 Value.subtract(One, APFloat::rmNearestTiesToEven);
3917 return true;
3918 }
3919 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3920 if (!checkConst(SubobjType))
3921 return false;
3922
3923 QualType PointeeType;
3924 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3925 PointeeType = PT->getPointeeType();
3926 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003927 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003928 return false;
3929 }
3930
3931 LValue LVal;
3932 LVal.setFrom(Info.Ctx, Subobj);
3933 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3934 AccessKind == AK_Increment ? 1 : -1))
3935 return false;
3936 LVal.moveInto(Subobj);
3937 return true;
3938 }
Richard Smith243ef902013-05-05 23:31:59 +00003939};
3940} // end anonymous namespace
3941
3942/// Perform an increment or decrement on LVal.
3943static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3944 QualType LValType, bool IsIncrement, APValue *Old) {
3945 if (LVal.Designator.Invalid)
3946 return false;
3947
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003948 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003949 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003950 return false;
3951 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003952
3953 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3954 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3955 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3956 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3957}
3958
Richard Smithe97cbd72011-11-11 04:05:33 +00003959/// Build an lvalue for the object argument of a member function call.
3960static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3961 LValue &This) {
3962 if (Object->getType()->isPointerType())
3963 return EvaluatePointer(Object, This, Info);
3964
3965 if (Object->isGLValue())
3966 return EvaluateLValue(Object, This, Info);
3967
Richard Smithd9f663b2013-04-22 15:31:51 +00003968 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003969 return EvaluateTemporary(Object, This, Info);
3970
Faisal Valie690b7a2016-07-02 22:34:24 +00003971 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003972 return false;
3973}
3974
3975/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3976/// lvalue referring to the result.
3977///
3978/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003979/// \param LV - An lvalue referring to the base of the member pointer.
3980/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003981/// \param IncludeMember - Specifies whether the member itself is included in
3982/// the resulting LValue subobject designator. This is not possible when
3983/// creating a bound member function.
3984/// \return The field or method declaration to which the member pointer refers,
3985/// or 0 if evaluation fails.
3986static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003987 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003988 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003989 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003990 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003991 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003992 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003993 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003994
3995 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3996 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003997 if (!MemPtr.getDecl()) {
3998 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003999 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004000 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004001 }
Richard Smith253c2a32012-01-27 01:14:48 +00004002
Richard Smith027bf112011-11-17 22:56:20 +00004003 if (MemPtr.isDerivedMember()) {
4004 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00004005 // The end of the derived-to-base path for the base object must match the
4006 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00004007 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00004008 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004009 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004010 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004011 }
Richard Smith027bf112011-11-17 22:56:20 +00004012 unsigned PathLengthToMember =
4013 LV.Designator.Entries.size() - MemPtr.Path.size();
4014 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4015 const CXXRecordDecl *LVDecl = getAsBaseClass(
4016 LV.Designator.Entries[PathLengthToMember + I]);
4017 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00004018 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004019 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004020 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004021 }
Richard Smith027bf112011-11-17 22:56:20 +00004022 }
4023
4024 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00004025 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004026 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00004027 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004028 } else if (!MemPtr.Path.empty()) {
4029 // Extend the LValue path with the member pointer's path.
4030 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4031 MemPtr.Path.size() + IncludeMember);
4032
4033 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00004034 if (const PointerType *PT = LVType->getAs<PointerType>())
4035 LVType = PT->getPointeeType();
4036 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4037 assert(RD && "member pointer access on non-class-type expression");
4038 // The first class in the path is that of the lvalue.
4039 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4040 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00004041 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00004042 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004043 RD = Base;
4044 }
4045 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00004046 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4047 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00004048 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004049 }
4050
4051 // Add the member. Note that we cannot build bound member functions here.
4052 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00004053 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004054 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00004055 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004056 } else if (const IndirectFieldDecl *IFD =
4057 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004058 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00004059 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004060 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004061 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00004062 }
Richard Smith027bf112011-11-17 22:56:20 +00004063 }
4064
4065 return MemPtr.getDecl();
4066}
4067
Richard Smith84401042013-06-03 05:03:02 +00004068static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4069 const BinaryOperator *BO,
4070 LValue &LV,
4071 bool IncludeMember = true) {
4072 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4073
4074 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00004075 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00004076 MemberPtr MemPtr;
4077 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4078 }
Craig Topper36250ad2014-05-12 05:36:57 +00004079 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004080 }
4081
4082 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4083 BO->getRHS(), IncludeMember);
4084}
4085
Richard Smith027bf112011-11-17 22:56:20 +00004086/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4087/// the provided lvalue, which currently refers to the base object.
4088static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4089 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00004090 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00004091 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00004092 return false;
4093
Richard Smitha8105bc2012-01-06 16:39:00 +00004094 QualType TargetQT = E->getType();
4095 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4096 TargetQT = PT->getPointeeType();
4097
4098 // Check this cast lands within the final derived-to-base subobject path.
4099 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004100 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004101 << D.MostDerivedType << TargetQT;
4102 return false;
4103 }
4104
Richard Smith027bf112011-11-17 22:56:20 +00004105 // Check the type of the final cast. We don't need to check the path,
4106 // since a cast can only be formed if the path is unique.
4107 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004108 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4109 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004110 if (NewEntriesSize == D.MostDerivedPathLength)
4111 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4112 else
Richard Smith027bf112011-11-17 22:56:20 +00004113 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004114 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004115 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004116 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004117 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004118 }
Richard Smith027bf112011-11-17 22:56:20 +00004119
4120 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004121 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004122}
4123
Richard Smithc667cdc2019-09-18 17:37:44 +00004124/// Get the value to use for a default-initialized object of type T.
4125static APValue getDefaultInitValue(QualType T) {
4126 if (auto *RD = T->getAsCXXRecordDecl()) {
4127 if (RD->isUnion())
4128 return APValue((const FieldDecl*)nullptr);
4129
4130 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4131 std::distance(RD->field_begin(), RD->field_end()));
4132
4133 unsigned Index = 0;
4134 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4135 End = RD->bases_end(); I != End; ++I, ++Index)
4136 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4137
4138 for (const auto *I : RD->fields()) {
4139 if (I->isUnnamedBitfield())
4140 continue;
4141 Struct.getStructField(I->getFieldIndex()) =
4142 getDefaultInitValue(I->getType());
4143 }
4144 return Struct;
4145 }
4146
4147 if (auto *AT =
4148 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4149 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4150 if (Array.hasArrayFiller())
4151 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4152 return Array;
4153 }
4154
4155 return APValue::IndeterminateValue();
4156}
4157
Mike Stump876387b2009-10-27 22:09:17 +00004158namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004159enum EvalStmtResult {
4160 /// Evaluation failed.
4161 ESR_Failed,
4162 /// Hit a 'return' statement.
4163 ESR_Returned,
4164 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004165 ESR_Succeeded,
4166 /// Hit a 'continue' statement.
4167 ESR_Continue,
4168 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004169 ESR_Break,
4170 /// Still scanning for 'case' or 'default' statement.
4171 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004172};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004173}
Richard Smith254a73d2011-10-28 22:34:42 +00004174
Richard Smith97fcf4b2016-08-14 23:15:52 +00004175static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4176 // We don't need to evaluate the initializer for a static local.
4177 if (!VD->hasLocalStorage())
4178 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004179
Richard Smith97fcf4b2016-08-14 23:15:52 +00004180 LValue Result;
Richard Smith457226e2019-09-23 03:48:44 +00004181 APValue &Val =
4182 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
Richard Smithd9f663b2013-04-22 15:31:51 +00004183
Richard Smith97fcf4b2016-08-14 23:15:52 +00004184 const Expr *InitE = VD->getInit();
4185 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00004186 Val = getDefaultInitValue(VD->getType());
4187 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00004188 }
Richard Smith51f03172013-06-20 03:00:05 +00004189
Richard Smith97fcf4b2016-08-14 23:15:52 +00004190 if (InitE->isValueDependent())
4191 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004192
Richard Smith97fcf4b2016-08-14 23:15:52 +00004193 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4194 // Wipe out any partially-computed value, to allow tracking that this
4195 // evaluation failed.
4196 Val = APValue();
4197 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004198 }
4199
4200 return true;
4201}
4202
Richard Smith97fcf4b2016-08-14 23:15:52 +00004203static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4204 bool OK = true;
4205
4206 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4207 OK &= EvaluateVarDecl(Info, VD);
4208
4209 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4210 for (auto *BD : DD->bindings())
4211 if (auto *VD = BD->getHoldingVar())
4212 OK &= EvaluateDecl(Info, VD);
4213
4214 return OK;
4215}
4216
4217
Richard Smith4e18ca52013-05-06 05:56:11 +00004218/// Evaluate a condition (either a variable declaration or an expression).
4219static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4220 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004221 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004222 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4223 return false;
Richard Smith457226e2019-09-23 03:48:44 +00004224 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4225 return false;
4226 return Scope.destroy();
Richard Smith4e18ca52013-05-06 05:56:11 +00004227}
4228
Richard Smith89210072016-04-04 23:29:43 +00004229namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004230/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004231/// statement should be stored.
4232struct StmtResult {
4233 /// The APValue that should be filled in with the returned value.
4234 APValue &Value;
4235 /// The location containing the result, if any (used to support RVO).
4236 const LValue *Slot;
4237};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004238
4239struct TempVersionRAII {
4240 CallStackFrame &Frame;
4241
4242 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4243 Frame.pushTempVersion();
4244 }
4245
4246 ~TempVersionRAII() {
4247 Frame.popTempVersion();
4248 }
4249};
4250
Richard Smith89210072016-04-04 23:29:43 +00004251}
Richard Smith52a980a2015-08-28 02:43:42 +00004252
4253static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004254 const Stmt *S,
4255 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004256
4257/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004258static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004259 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004260 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004261 BlockScopeRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004262
4263 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4264 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4265 ESR = ESR_Failed;
4266
4267 switch (ESR) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004268 case ESR_Break:
4269 return ESR_Succeeded;
4270 case ESR_Succeeded:
4271 case ESR_Continue:
4272 return ESR_Continue;
4273 case ESR_Failed:
4274 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004275 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004276 return ESR;
4277 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004278 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004279}
4280
Richard Smith496ddcf2013-05-12 17:32:42 +00004281/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004282static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004283 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004284 BlockScopeRAII Scope(Info);
4285
Richard Smith496ddcf2013-05-12 17:32:42 +00004286 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004287 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004288 {
Richard Smitha547eb22016-07-14 00:11:03 +00004289 if (const Stmt *Init = SS->getInit()) {
4290 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004291 if (ESR != ESR_Succeeded) {
4292 if (ESR != ESR_Failed && !Scope.destroy())
4293 ESR = ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004294 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004295 }
Richard Smitha547eb22016-07-14 00:11:03 +00004296 }
Richard Smith457226e2019-09-23 03:48:44 +00004297
4298 FullExpressionRAII CondScope(Info);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004299 if (SS->getConditionVariable() &&
4300 !EvaluateDecl(Info, SS->getConditionVariable()))
4301 return ESR_Failed;
4302 if (!EvaluateInteger(SS->getCond(), Value, Info))
4303 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004304 if (!CondScope.destroy())
4305 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004306 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004307
4308 // Find the switch case corresponding to the value of the condition.
4309 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004310 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004311 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4312 SC = SC->getNextSwitchCase()) {
4313 if (isa<DefaultStmt>(SC)) {
4314 Found = SC;
4315 continue;
4316 }
4317
4318 const CaseStmt *CS = cast<CaseStmt>(SC);
4319 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4320 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4321 : LHS;
4322 if (LHS <= Value && Value <= RHS) {
4323 Found = SC;
4324 break;
4325 }
4326 }
4327
4328 if (!Found)
Richard Smith457226e2019-09-23 03:48:44 +00004329 return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
Richard Smith496ddcf2013-05-12 17:32:42 +00004330
4331 // Search the switch body for the switch case and evaluate it from there.
Richard Smith457226e2019-09-23 03:48:44 +00004332 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4333 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4334 return ESR_Failed;
4335
4336 switch (ESR) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004337 case ESR_Break:
4338 return ESR_Succeeded;
4339 case ESR_Succeeded:
4340 case ESR_Continue:
4341 case ESR_Failed:
4342 case ESR_Returned:
4343 return ESR;
4344 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004345 // This can only happen if the switch case is nested within a statement
4346 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004347 Info.FFDiag(Found->getBeginLoc(),
4348 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004349 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004350 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004351 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004352}
4353
Richard Smith254a73d2011-10-28 22:34:42 +00004354// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004355static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004356 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004357 if (!Info.nextStep(S))
4358 return ESR_Failed;
4359
Richard Smith496ddcf2013-05-12 17:32:42 +00004360 // If we're hunting down a 'case' or 'default' label, recurse through
4361 // substatements until we hit the label.
4362 if (Case) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004363 switch (S->getStmtClass()) {
4364 case Stmt::CompoundStmtClass:
4365 // FIXME: Precompute which substatement of a compound statement we
4366 // would jump to, and go straight there rather than performing a
4367 // linear scan each time.
4368 case Stmt::LabelStmtClass:
4369 case Stmt::AttributedStmtClass:
4370 case Stmt::DoStmtClass:
4371 break;
4372
4373 case Stmt::CaseStmtClass:
4374 case Stmt::DefaultStmtClass:
4375 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004376 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004377 break;
4378
4379 case Stmt::IfStmtClass: {
4380 // FIXME: Precompute which side of an 'if' we would jump to, and go
4381 // straight there rather than scanning both sides.
4382 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004383
4384 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4385 // preceded by our switch label.
4386 BlockScopeRAII Scope(Info);
4387
Richard Smith397a6862019-09-20 23:08:59 +00004388 // Step into the init statement in case it brings an (uninitialized)
4389 // variable into scope.
4390 if (const Stmt *Init = IS->getInit()) {
4391 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4392 if (ESR != ESR_CaseNotFound) {
4393 assert(ESR != ESR_Succeeded);
4394 return ESR;
4395 }
4396 }
4397
4398 // Condition variable must be initialized if it exists.
4399 // FIXME: We can skip evaluating the body if there's a condition
4400 // variable, as there can't be any case labels within it.
4401 // (The same is true for 'for' statements.)
4402
Richard Smith496ddcf2013-05-12 17:32:42 +00004403 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
Richard Smith457226e2019-09-23 03:48:44 +00004404 if (ESR == ESR_Failed)
Richard Smith496ddcf2013-05-12 17:32:42 +00004405 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004406 if (ESR != ESR_CaseNotFound)
4407 return Scope.destroy() ? ESR : ESR_Failed;
4408 if (!IS->getElse())
4409 return ESR_CaseNotFound;
4410
4411 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4412 if (ESR == ESR_Failed)
4413 return ESR;
4414 if (ESR != ESR_CaseNotFound)
4415 return Scope.destroy() ? ESR : ESR_Failed;
4416 return ESR_CaseNotFound;
Richard Smith496ddcf2013-05-12 17:32:42 +00004417 }
4418
4419 case Stmt::WhileStmtClass: {
4420 EvalStmtResult ESR =
4421 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4422 if (ESR != ESR_Continue)
4423 return ESR;
4424 break;
4425 }
4426
4427 case Stmt::ForStmtClass: {
4428 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith397a6862019-09-20 23:08:59 +00004429 BlockScopeRAII Scope(Info);
4430
4431 // Step into the init statement in case it brings an (uninitialized)
4432 // variable into scope.
4433 if (const Stmt *Init = FS->getInit()) {
4434 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4435 if (ESR != ESR_CaseNotFound) {
4436 assert(ESR != ESR_Succeeded);
4437 return ESR;
4438 }
4439 }
4440
Richard Smith496ddcf2013-05-12 17:32:42 +00004441 EvalStmtResult ESR =
4442 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4443 if (ESR != ESR_Continue)
4444 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004445 if (FS->getInc()) {
4446 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004447 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004448 return ESR_Failed;
4449 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004450 break;
4451 }
4452
Richard Smithc667cdc2019-09-18 17:37:44 +00004453 case Stmt::DeclStmtClass: {
4454 // Start the lifetime of any uninitialized variables we encounter. They
4455 // might be used by the selected branch of the switch.
4456 const DeclStmt *DS = cast<DeclStmt>(S);
4457 for (const auto *D : DS->decls()) {
4458 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4459 if (VD->hasLocalStorage() && !VD->getInit())
4460 if (!EvaluateVarDecl(Info, VD))
4461 return ESR_Failed;
4462 // FIXME: If the variable has initialization that can't be jumped
4463 // over, bail out of any immediately-surrounding compound-statement
4464 // too. There can't be any case labels here.
4465 }
4466 }
4467 return ESR_CaseNotFound;
4468 }
4469
Richard Smith496ddcf2013-05-12 17:32:42 +00004470 default:
4471 return ESR_CaseNotFound;
4472 }
4473 }
4474
Richard Smith254a73d2011-10-28 22:34:42 +00004475 switch (S->getStmtClass()) {
4476 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004477 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004478 // Don't bother evaluating beyond an expression-statement which couldn't
4479 // be evaluated.
Richard Smith457226e2019-09-23 03:48:44 +00004480 // FIXME: Do we need the FullExpressionRAII object here?
4481 // VisitExprWithCleanups should create one when necessary.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004482 FullExpressionRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004483 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
Richard Smithd9f663b2013-04-22 15:31:51 +00004484 return ESR_Failed;
4485 return ESR_Succeeded;
4486 }
4487
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004488 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004489 return ESR_Failed;
4490
4491 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004492 return ESR_Succeeded;
4493
Richard Smithd9f663b2013-04-22 15:31:51 +00004494 case Stmt::DeclStmtClass: {
4495 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004496 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004497 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004498 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004499 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004500 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004501 if (!Scope.destroy())
4502 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004503 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004504 return ESR_Succeeded;
4505 }
4506
Richard Smith357362d2011-12-13 06:39:58 +00004507 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004508 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004509 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004510 if (RetExpr &&
4511 !(Result.Slot
4512 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4513 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004514 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004515 return Scope.destroy() ? ESR_Returned : ESR_Failed;
Richard Smith357362d2011-12-13 06:39:58 +00004516 }
Richard Smith254a73d2011-10-28 22:34:42 +00004517
4518 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004519 BlockScopeRAII Scope(Info);
4520
Richard Smith254a73d2011-10-28 22:34:42 +00004521 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004522 for (const auto *BI : CS->body()) {
4523 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004524 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004525 Case = nullptr;
Richard Smith457226e2019-09-23 03:48:44 +00004526 else if (ESR != ESR_CaseNotFound) {
4527 if (ESR != ESR_Failed && !Scope.destroy())
4528 return ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004529 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004530 }
Richard Smith254a73d2011-10-28 22:34:42 +00004531 }
Richard Smith457226e2019-09-23 03:48:44 +00004532 if (Case)
4533 return ESR_CaseNotFound;
4534 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004535 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004536
4537 case Stmt::IfStmtClass: {
4538 const IfStmt *IS = cast<IfStmt>(S);
4539
4540 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004541 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004542 if (const Stmt *Init = IS->getInit()) {
4543 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004544 if (ESR != ESR_Succeeded) {
4545 if (ESR != ESR_Failed && !Scope.destroy())
4546 return ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004547 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004548 }
Richard Smitha547eb22016-07-14 00:11:03 +00004549 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004550 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004551 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004552 return ESR_Failed;
4553
4554 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4555 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
Richard Smith457226e2019-09-23 03:48:44 +00004556 if (ESR != ESR_Succeeded) {
4557 if (ESR != ESR_Failed && !Scope.destroy())
4558 return ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004559 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004560 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004561 }
Richard Smith457226e2019-09-23 03:48:44 +00004562 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004563 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004564
4565 case Stmt::WhileStmtClass: {
4566 const WhileStmt *WS = cast<WhileStmt>(S);
4567 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004568 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004569 bool Continue;
4570 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4571 Continue))
4572 return ESR_Failed;
4573 if (!Continue)
4574 break;
4575
4576 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004577 if (ESR != ESR_Continue) {
4578 if (ESR != ESR_Failed && !Scope.destroy())
4579 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004580 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004581 }
4582 if (!Scope.destroy())
4583 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004584 }
4585 return ESR_Succeeded;
4586 }
4587
4588 case Stmt::DoStmtClass: {
4589 const DoStmt *DS = cast<DoStmt>(S);
4590 bool Continue;
4591 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004592 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004593 if (ESR != ESR_Continue)
4594 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004595 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004596
Richard Smith08d6a2c2013-07-24 07:11:57 +00004597 FullExpressionRAII CondScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004598 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4599 !CondScope.destroy())
Richard Smith4e18ca52013-05-06 05:56:11 +00004600 return ESR_Failed;
4601 } while (Continue);
4602 return ESR_Succeeded;
4603 }
4604
4605 case Stmt::ForStmtClass: {
4606 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith457226e2019-09-23 03:48:44 +00004607 BlockScopeRAII ForScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004608 if (FS->getInit()) {
4609 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004610 if (ESR != ESR_Succeeded) {
4611 if (ESR != ESR_Failed && !ForScope.destroy())
4612 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004613 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004614 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004615 }
4616 while (true) {
Richard Smith457226e2019-09-23 03:48:44 +00004617 BlockScopeRAII IterScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004618 bool Continue = true;
4619 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4620 FS->getCond(), Continue))
4621 return ESR_Failed;
4622 if (!Continue)
4623 break;
4624
4625 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004626 if (ESR != ESR_Continue) {
4627 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4628 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004629 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004630 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004631
Richard Smith08d6a2c2013-07-24 07:11:57 +00004632 if (FS->getInc()) {
4633 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004634 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004635 return ESR_Failed;
4636 }
Richard Smith457226e2019-09-23 03:48:44 +00004637
4638 if (!IterScope.destroy())
4639 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004640 }
Richard Smith457226e2019-09-23 03:48:44 +00004641 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004642 }
4643
Richard Smith896e0d72013-05-06 06:51:17 +00004644 case Stmt::CXXForRangeStmtClass: {
4645 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004646 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004647
Richard Smith8baa5002018-09-28 18:44:09 +00004648 // Evaluate the init-statement if present.
4649 if (FS->getInit()) {
4650 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004651 if (ESR != ESR_Succeeded) {
4652 if (ESR != ESR_Failed && !Scope.destroy())
4653 return ESR_Failed;
Richard Smith8baa5002018-09-28 18:44:09 +00004654 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004655 }
Richard Smith8baa5002018-09-28 18:44:09 +00004656 }
4657
Richard Smith896e0d72013-05-06 06:51:17 +00004658 // Initialize the __range variable.
4659 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004660 if (ESR != ESR_Succeeded) {
4661 if (ESR != ESR_Failed && !Scope.destroy())
4662 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004663 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004664 }
Richard Smith896e0d72013-05-06 06:51:17 +00004665
4666 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004667 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004668 if (ESR != ESR_Succeeded) {
4669 if (ESR != ESR_Failed && !Scope.destroy())
4670 return ESR_Failed;
Richard Smith01694c32016-03-20 10:33:40 +00004671 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004672 }
Richard Smith01694c32016-03-20 10:33:40 +00004673 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004674 if (ESR != ESR_Succeeded) {
4675 if (ESR != ESR_Failed && !Scope.destroy())
4676 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004677 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004678 }
Richard Smith896e0d72013-05-06 06:51:17 +00004679
4680 while (true) {
4681 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004682 {
4683 bool Continue = true;
4684 FullExpressionRAII CondExpr(Info);
4685 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4686 return ESR_Failed;
4687 if (!Continue)
4688 break;
4689 }
Richard Smith896e0d72013-05-06 06:51:17 +00004690
4691 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004692 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004693 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004694 if (ESR != ESR_Succeeded) {
4695 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4696 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004697 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004698 }
Richard Smith896e0d72013-05-06 06:51:17 +00004699
4700 // Loop body.
4701 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004702 if (ESR != ESR_Continue) {
4703 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4704 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004705 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004706 }
Richard Smith896e0d72013-05-06 06:51:17 +00004707
4708 // Increment: ++__begin
4709 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4710 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004711
4712 if (!InnerScope.destroy())
4713 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004714 }
4715
Richard Smith457226e2019-09-23 03:48:44 +00004716 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004717 }
4718
Richard Smith496ddcf2013-05-12 17:32:42 +00004719 case Stmt::SwitchStmtClass:
4720 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4721
Richard Smith4e18ca52013-05-06 05:56:11 +00004722 case Stmt::ContinueStmtClass:
4723 return ESR_Continue;
4724
4725 case Stmt::BreakStmtClass:
4726 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004727
4728 case Stmt::LabelStmtClass:
4729 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4730
4731 case Stmt::AttributedStmtClass:
4732 // As a general principle, C++11 attributes can be ignored without
4733 // any semantic impact.
4734 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4735 Case);
4736
4737 case Stmt::CaseStmtClass:
4738 case Stmt::DefaultStmtClass:
4739 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004740 case Stmt::CXXTryStmtClass:
4741 // Evaluate try blocks by evaluating all sub statements.
4742 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004743 }
4744}
4745
Richard Smithcc36f692011-12-22 02:22:31 +00004746/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4747/// default constructor. If so, we'll fold it whether or not it's marked as
4748/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4749/// so we need special handling.
4750static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004751 const CXXConstructorDecl *CD,
4752 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004753 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4754 return false;
4755
Richard Smith66e05fe2012-01-18 05:21:49 +00004756 // Value-initialization does not call a trivial default constructor, so such a
4757 // call is a core constant expression whether or not the constructor is
4758 // constexpr.
4759 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004760 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004761 // FIXME: If DiagDecl is an implicitly-declared special member function,
4762 // we should be much more explicit about why it's not constexpr.
4763 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4764 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4765 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004766 } else {
4767 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4768 }
4769 }
4770 return true;
4771}
4772
Richard Smith357362d2011-12-13 06:39:58 +00004773/// CheckConstexprFunction - Check that a function can be called in a constant
4774/// expression.
4775static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4776 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004777 const FunctionDecl *Definition,
4778 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004779 // Potential constant expressions can contain calls to declared, but not yet
4780 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004781 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004782 Declaration->isConstexpr())
4783 return false;
4784
James Y Knightc7d3e602018-10-05 17:49:48 +00004785 // Bail out if the function declaration itself is invalid. We will
4786 // have produced a relevant diagnostic while parsing it, so just
4787 // note the problematic sub-expression.
4788 if (Declaration->isInvalidDecl()) {
4789 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004790 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004791 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004792
Richard Smithd9c6b032019-05-09 19:45:49 +00004793 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004794 // constant expression (prior to C++20). We can still constant-fold such a
4795 // call.
4796 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4797 cast<CXXMethodDecl>(Declaration)->isVirtual())
4798 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4799
4800 if (Definition && Definition->isInvalidDecl()) {
4801 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004802 return false;
4803 }
4804
Richard Smith357362d2011-12-13 06:39:58 +00004805 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004806 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004807 return true;
4808
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004809 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004810 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004811
Richard Smith5179eb72016-06-28 19:03:57 +00004812 // If this function is not constexpr because it is an inherited
4813 // non-constexpr constructor, diagnose that directly.
4814 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4815 if (CD && CD->isInheritingConstructor()) {
4816 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004817 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004818 DiagDecl = CD = Inherited;
4819 }
4820
4821 // FIXME: If DiagDecl is an implicitly-declared special member function
4822 // or an inheriting constructor, we should be much more explicit about why
4823 // it's not constexpr.
4824 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004825 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004826 << CD->getInheritedConstructor().getConstructor()->getParent();
4827 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004828 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004829 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004830 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4831 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004832 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004833 }
4834 return false;
4835}
4836
Richard Smithdebad642019-05-12 09:39:08 +00004837namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004838struct CheckDynamicTypeHandler {
4839 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004840 typedef bool result_type;
4841 bool failed() { return false; }
4842 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4843 bool found(APSInt &Value, QualType SubobjType) { return true; }
4844 bool found(APFloat &Value, QualType SubobjType) { return true; }
4845};
4846} // end anonymous namespace
4847
Richard Smith7bd54ab2019-05-15 20:22:21 +00004848/// Check that we can access the notional vptr of an object / determine its
4849/// dynamic type.
4850static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4851 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004852 if (This.Designator.Invalid)
4853 return false;
4854
Richard Smith7bd54ab2019-05-15 20:22:21 +00004855 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004856
4857 if (!Obj)
4858 return false;
4859
4860 if (!Obj.Value) {
4861 // The object is not usable in constant expressions, so we can't inspect
4862 // its value to see if it's in-lifetime or what the active union members
4863 // are. We can still check for a one-past-the-end lvalue.
4864 if (This.Designator.isOnePastTheEnd() ||
4865 This.Designator.isMostDerivedAnUnsizedArray()) {
4866 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4867 ? diag::note_constexpr_access_past_end
4868 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004869 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004870 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004871 } else if (Polymorphic) {
4872 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004873 // not be able to read a notional 'vptr' value.
4874 APValue Val;
4875 This.moveInto(Val);
4876 QualType StarThisType =
4877 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004878 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4879 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004880 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004881 }
4882 return true;
4883 }
4884
Richard Smith7bd54ab2019-05-15 20:22:21 +00004885 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004886 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4887}
4888
Richard Smith7bd54ab2019-05-15 20:22:21 +00004889/// Check that the pointee of the 'this' pointer in a member function call is
4890/// either within its lifetime or in its period of construction or destruction.
Richard Smith61422f92019-09-27 20:24:36 +00004891static bool
4892checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4893 const LValue &This,
4894 const CXXMethodDecl *NamedMember) {
4895 return checkDynamicType(
4896 Info, E, This,
4897 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
Richard Smith7bd54ab2019-05-15 20:22:21 +00004898}
4899
Richard Smith921f1322019-05-13 23:35:21 +00004900struct DynamicType {
4901 /// The dynamic class type of the object.
4902 const CXXRecordDecl *Type;
4903 /// The corresponding path length in the lvalue.
4904 unsigned PathLength;
4905};
4906
4907static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4908 unsigned PathLength) {
4909 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4910 Designator.Entries.size() && "invalid path length");
4911 return (PathLength == Designator.MostDerivedPathLength)
4912 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4913 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4914}
4915
4916/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004917static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4918 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004919 // If we don't have an lvalue denoting an object of class type, there is no
4920 // meaningful dynamic type. (We consider objects of non-class type to have no
4921 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004922 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004923 return None;
4924
Richard Smith7bd54ab2019-05-15 20:22:21 +00004925 // Refuse to compute a dynamic type in the presence of virtual bases. This
4926 // shouldn't happen other than in constant-folding situations, since literal
4927 // types can't have virtual bases.
4928 //
4929 // Note that consumers of DynamicType assume that the type has no virtual
4930 // bases, and will need modifications if this restriction is relaxed.
4931 const CXXRecordDecl *Class =
4932 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4933 if (!Class || Class->getNumVBases()) {
4934 Info.FFDiag(E);
4935 return None;
4936 }
4937
Richard Smith921f1322019-05-13 23:35:21 +00004938 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4939 // binary search here instead. But the overwhelmingly common case is that
4940 // we're not in the middle of a constructor, so it probably doesn't matter
4941 // in practice.
4942 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4943 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4944 PathLength <= Path.size(); ++PathLength) {
Richard Smith457226e2019-09-23 03:48:44 +00004945 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
4946 Path.slice(0, PathLength))) {
Richard Smith921f1322019-05-13 23:35:21 +00004947 case ConstructionPhase::Bases:
Richard Smith457226e2019-09-23 03:48:44 +00004948 case ConstructionPhase::DestroyingBases:
4949 // We're constructing or destroying a base class. This is not the dynamic
4950 // type.
Richard Smith921f1322019-05-13 23:35:21 +00004951 break;
4952
4953 case ConstructionPhase::None:
4954 case ConstructionPhase::AfterBases:
Richard Smith457226e2019-09-23 03:48:44 +00004955 case ConstructionPhase::Destroying:
4956 // We've finished constructing the base classes and not yet started
4957 // destroying them again, so this is the dynamic type.
Richard Smith921f1322019-05-13 23:35:21 +00004958 return DynamicType{getBaseClassType(This.Designator, PathLength),
4959 PathLength};
4960 }
4961 }
4962
4963 // CWG issue 1517: we're constructing a base class of the object described by
4964 // 'This', so that object has not yet begun its period of construction and
4965 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004966 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004967 return None;
4968}
4969
4970/// Perform virtual dispatch.
4971static const CXXMethodDecl *HandleVirtualDispatch(
4972 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4973 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith61422f92019-09-27 20:24:36 +00004974 Optional<DynamicType> DynType = ComputeDynamicType(
4975 Info, E, This,
4976 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
Richard Smith7bd54ab2019-05-15 20:22:21 +00004977 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004978 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004979
4980 // Find the final overrider. It must be declared in one of the classes on the
4981 // path from the dynamic type to the static type.
4982 // FIXME: If we ever allow literal types to have virtual base classes, that
4983 // won't be true.
4984 const CXXMethodDecl *Callee = Found;
4985 unsigned PathLength = DynType->PathLength;
4986 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4987 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004988 const CXXMethodDecl *Overrider =
4989 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4990 if (Overrider) {
4991 Callee = Overrider;
4992 break;
4993 }
4994 }
4995
4996 // C++2a [class.abstract]p6:
4997 // the effect of making a virtual call to a pure virtual function [...] is
4998 // undefined
4999 if (Callee->isPure()) {
5000 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5001 Info.Note(Callee->getLocation(), diag::note_declared_at);
5002 return nullptr;
5003 }
5004
5005 // If necessary, walk the rest of the path to determine the sequence of
5006 // covariant adjustment steps to apply.
5007 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5008 Found->getReturnType())) {
5009 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5010 for (unsigned CovariantPathLength = PathLength + 1;
5011 CovariantPathLength != This.Designator.Entries.size();
5012 ++CovariantPathLength) {
5013 const CXXRecordDecl *NextClass =
5014 getBaseClassType(This.Designator, CovariantPathLength);
5015 const CXXMethodDecl *Next =
5016 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5017 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5018 Next->getReturnType(), CovariantAdjustmentPath.back()))
5019 CovariantAdjustmentPath.push_back(Next->getReturnType());
5020 }
5021 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5022 CovariantAdjustmentPath.back()))
5023 CovariantAdjustmentPath.push_back(Found->getReturnType());
5024 }
5025
5026 // Perform 'this' adjustment.
5027 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5028 return nullptr;
5029
5030 return Callee;
5031}
5032
5033/// Perform the adjustment from a value returned by a virtual function to
5034/// a value of the statically expected type, which may be a pointer or
5035/// reference to a base class of the returned type.
5036static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5037 APValue &Result,
5038 ArrayRef<QualType> Path) {
5039 assert(Result.isLValue() &&
5040 "unexpected kind of APValue for covariant return");
5041 if (Result.isNullPointer())
5042 return true;
5043
5044 LValue LVal;
5045 LVal.setFrom(Info.Ctx, Result);
5046
5047 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5048 for (unsigned I = 1; I != Path.size(); ++I) {
5049 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5050 assert(OldClass && NewClass && "unexpected kind of covariant return");
5051 if (OldClass != NewClass &&
5052 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5053 return false;
5054 OldClass = NewClass;
5055 }
5056
5057 LVal.moveInto(Result);
5058 return true;
5059}
5060
Richard Smith7bd54ab2019-05-15 20:22:21 +00005061/// Determine whether \p Base, which is known to be a direct base class of
5062/// \p Derived, is a public base class.
5063static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5064 const CXXRecordDecl *Base) {
5065 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5066 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5067 if (BaseClass && declaresSameEntity(BaseClass, Base))
5068 return BaseSpec.getAccessSpecifier() == AS_public;
5069 }
5070 llvm_unreachable("Base is not a direct base of Derived");
5071}
5072
5073/// Apply the given dynamic cast operation on the provided lvalue.
5074///
5075/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5076/// to find a suitable target subobject.
5077static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5078 LValue &Ptr) {
5079 // We can't do anything with a non-symbolic pointer value.
5080 SubobjectDesignator &D = Ptr.Designator;
5081 if (D.Invalid)
5082 return false;
5083
5084 // C++ [expr.dynamic.cast]p6:
5085 // If v is a null pointer value, the result is a null pointer value.
5086 if (Ptr.isNullPointer() && !E->isGLValue())
5087 return true;
5088
5089 // For all the other cases, we need the pointer to point to an object within
5090 // its lifetime / period of construction / destruction, and we need to know
5091 // its dynamic type.
5092 Optional<DynamicType> DynType =
5093 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5094 if (!DynType)
5095 return false;
5096
5097 // C++ [expr.dynamic.cast]p7:
5098 // If T is "pointer to cv void", then the result is a pointer to the most
5099 // derived object
5100 if (E->getType()->isVoidPointerType())
5101 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5102
5103 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5104 assert(C && "dynamic_cast target is not void pointer nor class");
5105 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5106
5107 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5108 // C++ [expr.dynamic.cast]p9:
5109 if (!E->isGLValue()) {
5110 // The value of a failed cast to pointer type is the null pointer value
5111 // of the required result type.
5112 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5113 Ptr.setNull(E->getType(), TargetVal);
5114 return true;
5115 }
5116
5117 // A failed cast to reference type throws [...] std::bad_cast.
5118 unsigned DiagKind;
5119 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5120 DynType->Type->isDerivedFrom(C)))
5121 DiagKind = 0;
5122 else if (!Paths || Paths->begin() == Paths->end())
5123 DiagKind = 1;
5124 else if (Paths->isAmbiguous(CQT))
5125 DiagKind = 2;
5126 else {
5127 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5128 DiagKind = 3;
5129 }
5130 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5131 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5132 << Info.Ctx.getRecordType(DynType->Type)
5133 << E->getType().getUnqualifiedType();
5134 return false;
5135 };
5136
5137 // Runtime check, phase 1:
5138 // Walk from the base subobject towards the derived object looking for the
5139 // target type.
5140 for (int PathLength = Ptr.Designator.Entries.size();
5141 PathLength >= (int)DynType->PathLength; --PathLength) {
5142 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5143 if (declaresSameEntity(Class, C))
5144 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5145 // We can only walk across public inheritance edges.
5146 if (PathLength > (int)DynType->PathLength &&
5147 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5148 Class))
5149 return RuntimeCheckFailed(nullptr);
5150 }
5151
5152 // Runtime check, phase 2:
5153 // Search the dynamic type for an unambiguous public base of type C.
5154 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5155 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5156 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5157 Paths.front().Access == AS_public) {
5158 // Downcast to the dynamic type...
5159 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5160 return false;
5161 // ... then upcast to the chosen base class subobject.
5162 for (CXXBasePathElement &Elem : Paths.front())
5163 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5164 return false;
5165 return true;
5166 }
5167
5168 // Otherwise, the runtime check fails.
5169 return RuntimeCheckFailed(&Paths);
5170}
5171
Richard Smith31c69a32019-05-21 23:15:20 +00005172namespace {
5173struct StartLifetimeOfUnionMemberHandler {
5174 const FieldDecl *Field;
5175
5176 static const AccessKinds AccessKind = AK_Assign;
5177
Richard Smith31c69a32019-05-21 23:15:20 +00005178 typedef bool result_type;
5179 bool failed() { return false; }
5180 bool found(APValue &Subobj, QualType SubobjType) {
5181 // We are supposed to perform no initialization but begin the lifetime of
5182 // the object. We interpret that as meaning to do what default
5183 // initialization of the object would do if all constructors involved were
5184 // trivial:
5185 // * All base, non-variant member, and array element subobjects' lifetimes
5186 // begin
5187 // * No variant members' lifetimes begin
5188 // * All scalar subobjects whose lifetimes begin have indeterminate values
5189 assert(SubobjType->isUnionType());
Richard Smith61422f92019-09-27 20:24:36 +00005190 if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5191 !Subobj.getUnionValue().hasValue())
Richard Smith31c69a32019-05-21 23:15:20 +00005192 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5193 return true;
5194 }
5195 bool found(APSInt &Value, QualType SubobjType) {
5196 llvm_unreachable("wrong value kind for union object");
5197 }
5198 bool found(APFloat &Value, QualType SubobjType) {
5199 llvm_unreachable("wrong value kind for union object");
5200 }
5201};
5202} // end anonymous namespace
5203
5204const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5205
5206/// Handle a builtin simple-assignment or a call to a trivial assignment
5207/// operator whose left-hand side might involve a union member access. If it
5208/// does, implicitly start the lifetime of any accessed union elements per
5209/// C++20 [class.union]5.
5210static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5211 const LValue &LHS) {
5212 if (LHS.InvalidBase || LHS.Designator.Invalid)
5213 return false;
5214
5215 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5216 // C++ [class.union]p5:
5217 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00005218 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005219 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005220 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5221 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5222 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5223 if (!FD)
5224 break;
5225
5226 // ... and also contains A.B if B names a union member
5227 if (FD->getParent()->isUnion())
5228 UnionPathLengths.push_back({PathLength - 1, FD});
5229
5230 E = ME->getBase();
5231 --PathLength;
5232 assert(declaresSameEntity(FD,
5233 LHS.Designator.Entries[PathLength]
5234 .getAsBaseOrMember().getPointer()));
5235
5236 // -- If E is of the form A[B] and is interpreted as a built-in array
5237 // subscripting operator, S(E) is [S(the array operand, if any)].
5238 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5239 // Step over an ArrayToPointerDecay implicit cast.
5240 auto *Base = ASE->getBase()->IgnoreImplicit();
5241 if (!Base->getType()->isArrayType())
5242 break;
5243
5244 E = Base;
5245 --PathLength;
5246
5247 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5248 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005249 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005250 if (ICE->getCastKind() == CK_NoOp)
5251 continue;
5252 if (ICE->getCastKind() != CK_DerivedToBase &&
5253 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5254 break;
Richard Smitha481b012019-05-30 20:45:12 +00005255 // Walk path backwards as we walk up from the base to the derived class.
5256 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005257 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005258 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005259 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5260 LHS.Designator.Entries[PathLength]
5261 .getAsBaseOrMember().getPointer()));
5262 }
Richard Smith31c69a32019-05-21 23:15:20 +00005263
5264 // -- Otherwise, S(E) is empty.
5265 } else {
5266 break;
5267 }
5268 }
5269
5270 // Common case: no unions' lifetimes are started.
5271 if (UnionPathLengths.empty())
5272 return true;
5273
5274 // if modification of X [would access an inactive union member], an object
5275 // of the type of X is implicitly created
5276 CompleteObject Obj =
5277 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5278 if (!Obj)
5279 return false;
5280 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5281 llvm::reverse(UnionPathLengths)) {
5282 // Form a designator for the union object.
5283 SubobjectDesignator D = LHS.Designator;
5284 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5285
5286 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5287 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5288 return false;
5289 }
5290
5291 return true;
5292}
5293
Richard Smithbe6dd812014-11-19 21:27:17 +00005294/// Determine if a class has any fields that might need to be copied by a
5295/// trivial copy or move operation.
5296static bool hasFields(const CXXRecordDecl *RD) {
5297 if (!RD || RD->isEmpty())
5298 return false;
5299 for (auto *FD : RD->fields()) {
5300 if (FD->isUnnamedBitfield())
5301 continue;
5302 return true;
5303 }
5304 for (auto &Base : RD->bases())
5305 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5306 return true;
5307 return false;
5308}
5309
Richard Smithd62306a2011-11-10 06:34:14 +00005310namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005311typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005312}
5313
5314/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005315static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5316 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005317 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005318 llvm::SmallBitVector ForbiddenNullArgs;
5319 if (Callee->hasAttr<NonNullAttr>()) {
5320 ForbiddenNullArgs.resize(Args.size());
5321 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5322 if (!Attr->args_size()) {
5323 ForbiddenNullArgs.set();
5324 break;
5325 } else
5326 for (auto Idx : Attr->args()) {
5327 unsigned ASTIdx = Idx.getASTIndex();
5328 if (ASTIdx >= Args.size())
5329 continue;
5330 ForbiddenNullArgs[ASTIdx] = 1;
5331 }
5332 }
5333 }
Richard Smithd62306a2011-11-10 06:34:14 +00005334 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005335 I != E; ++I) {
5336 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5337 // If we're checking for a potential constant expression, evaluate all
5338 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005339 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005340 return false;
5341 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005342 } else if (!ForbiddenNullArgs.empty() &&
5343 ForbiddenNullArgs[I - Args.begin()] &&
5344 ArgValues[I - Args.begin()].isNullPointer()) {
5345 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5346 if (!Info.noteFailure())
5347 return false;
5348 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005349 }
5350 }
5351 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005352}
5353
Richard Smith254a73d2011-10-28 22:34:42 +00005354/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005355static bool HandleFunctionCall(SourceLocation CallLoc,
5356 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005357 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005358 EvalInfo &Info, APValue &Result,
5359 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005360 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005361 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005362 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005363
Richard Smith253c2a32012-01-27 01:14:48 +00005364 if (!Info.CheckCallLimit(CallLoc))
5365 return false;
5366
5367 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005368
5369 // For a trivial copy or move assignment, perform an APValue copy. This is
5370 // essential for unions, where the operations performed by the assignment
5371 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005372 //
5373 // Skip this for non-union classes with no fields; in that case, the defaulted
5374 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005375 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005376 if (MD && MD->isDefaulted() &&
5377 (MD->getParent()->isUnion() ||
5378 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005379 assert(This &&
5380 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5381 LValue RHS;
5382 RHS.setFrom(Info.Ctx, ArgValues[0]);
5383 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005384 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5385 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005386 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005387 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5388 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5389 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005390 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005391 RHSValue))
5392 return false;
5393 This->moveInto(Result);
5394 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005395 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005396 // We're in a lambda; determine the lambda capture field maps unless we're
5397 // just constexpr checking a lambda's call operator. constexpr checking is
5398 // done before the captures have been added to the closure object (unless
5399 // we're inferring constexpr-ness), so we don't have access to them in this
5400 // case. But since we don't need the captures to constexpr check, we can
5401 // just ignore them.
5402 if (!Info.checkingPotentialConstantExpression())
5403 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5404 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005405 }
5406
Richard Smith52a980a2015-08-28 02:43:42 +00005407 StmtResult Ret = {Result, ResultSlot};
5408 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005409 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005410 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005411 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005412 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005413 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005414 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005415}
5416
Richard Smithd62306a2011-11-10 06:34:14 +00005417/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005418static bool HandleConstructorCall(const Expr *E, const LValue &This,
5419 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005420 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005421 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005422 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005423 if (!Info.CheckCallLimit(CallLoc))
5424 return false;
5425
Richard Smith3607ffe2012-02-13 03:54:03 +00005426 const CXXRecordDecl *RD = Definition->getParent();
5427 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005428 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005429 return false;
5430 }
5431
Erik Pilkington42925492017-10-04 00:18:55 +00005432 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005433 Info,
5434 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5435 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005436 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005437
Richard Smith52a980a2015-08-28 02:43:42 +00005438 // FIXME: Creating an APValue just to hold a nonexistent return value is
5439 // wasteful.
5440 APValue RetVal;
5441 StmtResult Ret = {RetVal, nullptr};
5442
Richard Smith5179eb72016-06-28 19:03:57 +00005443 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005444 if (Definition->isDelegatingConstructor()) {
5445 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005446 {
5447 FullExpressionRAII InitScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00005448 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5449 !InitScope.destroy())
Richard Smith9ff62af2013-11-07 18:45:03 +00005450 return false;
5451 }
Richard Smith52a980a2015-08-28 02:43:42 +00005452 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005453 }
5454
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005455 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005456 // essential for unions (or classes with anonymous union members), where the
5457 // operations performed by the constructor cannot be represented by
5458 // ctor-initializers.
5459 //
5460 // Skip this for empty non-union classes; we should not perform an
5461 // lvalue-to-rvalue conversion on them because their copy constructor does not
5462 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005463 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005464 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005465 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005466 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005467 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005468 return handleLValueToRValueConversion(
5469 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005470 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005471 }
5472
5473 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005474 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005475 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005476 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005477
John McCalld7bca762012-05-01 00:38:49 +00005478 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005479 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5480
Richard Smith08d6a2c2013-07-24 07:11:57 +00005481 // A scope for temporaries lifetime-extended by reference members.
5482 BlockScopeRAII LifetimeExtendedScope(Info);
5483
Richard Smith253c2a32012-01-27 01:14:48 +00005484 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005485 unsigned BasesSeen = 0;
5486#ifndef NDEBUG
5487 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5488#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005489 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5490 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5491 // We might be initializing the same field again if this is an indirect
5492 // field initialization.
5493 if (FieldIt == RD->field_end() ||
5494 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5495 assert(Indirect && "fields out of order?");
5496 return;
5497 }
5498
5499 // Default-initialize any fields with no explicit initializer.
5500 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5501 assert(FieldIt != RD->field_end() && "missing field?");
5502 if (!FieldIt->isUnnamedBitfield())
5503 Result.getStructField(FieldIt->getFieldIndex()) =
5504 getDefaultInitValue(FieldIt->getType());
5505 }
5506 ++FieldIt;
5507 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005508 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005509 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005510 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005511 APValue *Value = &Result;
5512
5513 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005514 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005515 if (I->isBaseInitializer()) {
5516 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005517#ifndef NDEBUG
5518 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005519 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005520 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5521 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5522 "base class initializers not in expected order");
5523 ++BaseIt;
5524#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005525 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005526 BaseType->getAsCXXRecordDecl(), &Layout))
5527 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005528 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005529 } else if ((FD = I->getMember())) {
5530 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005531 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005532 if (RD->isUnion()) {
5533 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005534 Value = &Result.getUnionValue();
5535 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005536 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005537 Value = &Result.getStructField(FD->getFieldIndex());
5538 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005539 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005540 // Walk the indirect field decl's chain to find the object to initialize,
5541 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005542 auto IndirectFieldChain = IFD->chain();
5543 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005544 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005545 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5546 // Switch the union field if it differs. This happens if we had
5547 // preceding zero-initialization, and we're now initializing a union
5548 // subobject other than the first.
5549 // FIXME: In this case, the values of the other subobjects are
5550 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005551 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005552 (Value->isUnion() && Value->getUnionField() != FD)) {
5553 if (CD->isUnion())
5554 *Value = APValue(FD);
5555 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005556 // FIXME: This immediately starts the lifetime of all members of an
5557 // anonymous struct. It would be preferable to strictly start member
5558 // lifetime in initialization order.
5559 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005560 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005561 // Store Subobject as its parent before updating it for the last element
5562 // in the chain.
5563 if (C == IndirectFieldChain.back())
5564 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005565 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005566 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005567 if (CD->isUnion())
5568 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005569 else {
5570 if (C == IndirectFieldChain.front() && !RD->isUnion())
5571 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005572 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005573 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005574 }
Richard Smithd62306a2011-11-10 06:34:14 +00005575 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005576 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005577 }
Richard Smith253c2a32012-01-27 01:14:48 +00005578
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005579 // Need to override This for implicit field initializers as in this case
5580 // This refers to innermost anonymous struct/union containing initializer,
5581 // not to currently constructed class.
5582 const Expr *Init = I->getInit();
5583 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5584 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005585 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005586 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5587 (FD && FD->isBitField() &&
5588 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005589 // If we're checking for a potential constant expression, evaluate all
5590 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005591 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005592 return false;
5593 Success = false;
5594 }
Richard Smith921f1322019-05-13 23:35:21 +00005595
5596 // This is the point at which the dynamic type of the object becomes this
5597 // class type.
5598 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5599 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005600 }
5601
Richard Smithc667cdc2019-09-18 17:37:44 +00005602 // Default-initialize any remaining fields.
5603 if (!RD->isUnion()) {
5604 for (; FieldIt != RD->field_end(); ++FieldIt) {
5605 if (!FieldIt->isUnnamedBitfield())
5606 Result.getStructField(FieldIt->getFieldIndex()) =
5607 getDefaultInitValue(FieldIt->getType());
5608 }
5609 }
5610
Richard Smithd9f663b2013-04-22 15:31:51 +00005611 return Success &&
Richard Smith457226e2019-09-23 03:48:44 +00005612 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5613 LifetimeExtendedScope.destroy();
Richard Smithd62306a2011-11-10 06:34:14 +00005614}
5615
Richard Smith5179eb72016-06-28 19:03:57 +00005616static bool HandleConstructorCall(const Expr *E, const LValue &This,
5617 ArrayRef<const Expr*> Args,
5618 const CXXConstructorDecl *Definition,
5619 EvalInfo &Info, APValue &Result) {
5620 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005621 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005622 return false;
5623
5624 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5625 Info, Result);
5626}
5627
Richard Smith61422f92019-09-27 20:24:36 +00005628static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5629 const LValue &This, APValue &Value,
5630 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005631 // Objects can only be destroyed while they're within their lifetimes.
5632 // FIXME: We have no representation for whether an object of type nullptr_t
5633 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5634 // as indeterminate instead?
5635 if (Value.isAbsent() && !T->isNullPtrType()) {
5636 APValue Printable;
5637 This.moveInto(Printable);
5638 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5639 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5640 return false;
5641 }
5642
Richard Smith457226e2019-09-23 03:48:44 +00005643 // Invent an expression for location purposes.
5644 // FIXME: We shouldn't need to do this.
5645 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5646
5647 // For arrays, destroy elements right-to-left.
5648 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5649 uint64_t Size = CAT->getSize().getZExtValue();
5650 QualType ElemT = CAT->getElementType();
5651
5652 LValue ElemLV = This;
5653 ElemLV.addArray(Info, &LocE, CAT);
5654 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5655 return false;
5656
Richard Smithda1b4342019-09-27 01:26:47 +00005657 // Ensure that we have actual array elements available to destroy; the
5658 // destructors might mutate the value, so we can't run them on the array
5659 // filler.
5660 if (Size && Size > Value.getArrayInitializedElts())
5661 expandArray(Value, Value.getArraySize() - 1);
5662
Richard Smith457226e2019-09-23 03:48:44 +00005663 for (; Size != 0; --Size) {
5664 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
Richard Smithda1b4342019-09-27 01:26:47 +00005665 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
Richard Smith61422f92019-09-27 20:24:36 +00005666 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
Richard Smith457226e2019-09-23 03:48:44 +00005667 return false;
5668 }
5669
5670 // End the lifetime of this array now.
5671 Value = APValue();
5672 return true;
5673 }
5674
5675 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5676 if (!RD) {
5677 if (T.isDestructedType()) {
5678 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5679 return false;
5680 }
5681
5682 Value = APValue();
5683 return true;
5684 }
5685
5686 if (RD->getNumVBases()) {
5687 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5688 return false;
5689 }
5690
5691 const CXXDestructorDecl *DD = RD->getDestructor();
Richard Smithda1b4342019-09-27 01:26:47 +00005692 if (!DD && !RD->hasTrivialDestructor()) {
Richard Smith457226e2019-09-23 03:48:44 +00005693 Info.FFDiag(CallLoc);
5694 return false;
5695 }
5696
Richard Smithda1b4342019-09-27 01:26:47 +00005697 if (!DD || DD->isTrivial() ||
Richard Smith457226e2019-09-23 03:48:44 +00005698 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5699 // A trivial destructor just ends the lifetime of the object. Check for
5700 // this case before checking for a body, because we might not bother
5701 // building a body for a trivial destructor. Note that it doesn't matter
5702 // whether the destructor is constexpr in this case; all trivial
5703 // destructors are constexpr.
5704 //
5705 // If an anonymous union would be destroyed, some enclosing destructor must
5706 // have been explicitly defined, and the anonymous union destruction should
5707 // have no effect.
5708 Value = APValue();
5709 return true;
5710 }
5711
5712 if (!Info.CheckCallLimit(CallLoc))
5713 return false;
5714
Richard Smithda1b4342019-09-27 01:26:47 +00005715 const FunctionDecl *Definition = nullptr;
5716 const Stmt *Body = DD->getBody(Definition);
5717
Richard Smith457226e2019-09-23 03:48:44 +00005718 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5719 return false;
5720
5721 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5722
5723 // We're now in the period of destruction of this object.
5724 unsigned BasesLeft = RD->getNumBases();
5725 EvalInfo::EvaluatingDestructorRAII EvalObj(
5726 Info,
5727 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
Richard Smithda1b4342019-09-27 01:26:47 +00005728 if (!EvalObj.DidInsert) {
5729 // C++2a [class.dtor]p19:
5730 // the behavior is undefined if the destructor is invoked for an object
5731 // whose lifetime has ended
5732 // (Note that formally the lifetime ends when the period of destruction
5733 // begins, even though certain uses of the object remain valid until the
5734 // period of destruction ends.)
5735 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5736 return false;
5737 }
Richard Smith457226e2019-09-23 03:48:44 +00005738
5739 // FIXME: Creating an APValue just to hold a nonexistent return value is
5740 // wasteful.
5741 APValue RetVal;
5742 StmtResult Ret = {RetVal, nullptr};
5743 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5744 return false;
5745
5746 // A union destructor does not implicitly destroy its members.
5747 if (RD->isUnion())
5748 return true;
5749
5750 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5751
5752 // We don't have a good way to iterate fields in reverse, so collect all the
5753 // fields first and then walk them backwards.
5754 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5755 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5756 if (FD->isUnnamedBitfield())
5757 continue;
5758
5759 LValue Subobject = This;
5760 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5761 return false;
5762
5763 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
Richard Smith61422f92019-09-27 20:24:36 +00005764 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5765 FD->getType()))
Richard Smith457226e2019-09-23 03:48:44 +00005766 return false;
5767 }
5768
5769 if (BasesLeft != 0)
5770 EvalObj.startedDestroyingBases();
5771
5772 // Destroy base classes in reverse order.
5773 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5774 --BasesLeft;
5775
5776 QualType BaseType = Base.getType();
5777 LValue Subobject = This;
5778 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5779 BaseType->getAsCXXRecordDecl(), &Layout))
5780 return false;
5781
5782 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
Richard Smith61422f92019-09-27 20:24:36 +00005783 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5784 BaseType))
Richard Smith457226e2019-09-23 03:48:44 +00005785 return false;
5786 }
5787 assert(BasesLeft == 0 && "NumBases was wrong?");
5788
5789 // The period of destruction ends now. The object is gone.
5790 Value = APValue();
5791 return true;
5792}
5793
Richard Smith61422f92019-09-27 20:24:36 +00005794namespace {
5795struct DestroyObjectHandler {
5796 EvalInfo &Info;
5797 const Expr *E;
5798 const LValue &This;
5799 const AccessKinds AccessKind;
5800
5801 typedef bool result_type;
5802 bool failed() { return false; }
5803 bool found(APValue &Subobj, QualType SubobjType) {
5804 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5805 SubobjType);
5806 }
5807 bool found(APSInt &Value, QualType SubobjType) {
5808 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5809 return false;
5810 }
5811 bool found(APFloat &Value, QualType SubobjType) {
5812 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5813 return false;
5814 }
5815};
5816}
5817
5818/// Perform a destructor or pseudo-destructor call on the given object, which
5819/// might in general not be a complete object.
5820static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5821 const LValue &This, QualType ThisType) {
5822 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5823 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5824 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5825}
5826
5827/// Destroy and end the lifetime of the given complete object.
5828static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5829 APValue::LValueBase LVBase, APValue &Value,
5830 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005831 // If we've had an unmodeled side-effect, we can't rely on mutable state
5832 // (such as the object we're about to destroy) being correct.
5833 if (Info.EvalStatus.HasSideEffects)
5834 return false;
Richard Smith457226e2019-09-23 03:48:44 +00005835
5836 LValue LV;
5837 LV.set({LVBase});
Richard Smith61422f92019-09-27 20:24:36 +00005838 return HandleDestructionImpl(Info, Loc, LV, Value, T);
Richard Smith457226e2019-09-23 03:48:44 +00005839}
5840
Eli Friedman9a156e52008-11-12 09:44:48 +00005841//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005842// Generic Evaluation
5843//===----------------------------------------------------------------------===//
5844namespace {
5845
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005846class BitCastBuffer {
5847 // FIXME: We're going to need bit-level granularity when we support
5848 // bit-fields.
5849 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5850 // we don't support a host or target where that is the case. Still, we should
5851 // use a more generic type in case we ever do.
5852 SmallVector<Optional<unsigned char>, 32> Bytes;
5853
5854 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5855 "Need at least 8 bit unsigned char");
5856
5857 bool TargetIsLittleEndian;
5858
5859public:
5860 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5861 : Bytes(Width.getQuantity()),
5862 TargetIsLittleEndian(TargetIsLittleEndian) {}
5863
5864 LLVM_NODISCARD
5865 bool readObject(CharUnits Offset, CharUnits Width,
5866 SmallVectorImpl<unsigned char> &Output) const {
5867 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5868 // If a byte of an integer is uninitialized, then the whole integer is
5869 // uninitalized.
5870 if (!Bytes[I.getQuantity()])
5871 return false;
5872 Output.push_back(*Bytes[I.getQuantity()]);
5873 }
5874 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5875 std::reverse(Output.begin(), Output.end());
5876 return true;
5877 }
5878
5879 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5880 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5881 std::reverse(Input.begin(), Input.end());
5882
5883 size_t Index = 0;
5884 for (unsigned char Byte : Input) {
5885 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5886 Bytes[Offset.getQuantity() + Index] = Byte;
5887 ++Index;
5888 }
5889 }
5890
5891 size_t size() { return Bytes.size(); }
5892};
5893
5894/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5895/// target would represent the value at runtime.
5896class APValueToBufferConverter {
5897 EvalInfo &Info;
5898 BitCastBuffer Buffer;
5899 const CastExpr *BCE;
5900
5901 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5902 const CastExpr *BCE)
5903 : Info(Info),
5904 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5905 BCE(BCE) {}
5906
5907 bool visit(const APValue &Val, QualType Ty) {
5908 return visit(Val, Ty, CharUnits::fromQuantity(0));
5909 }
5910
5911 // Write out Val with type Ty into Buffer starting at Offset.
5912 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5913 assert((size_t)Offset.getQuantity() <= Buffer.size());
5914
5915 // As a special case, nullptr_t has an indeterminate value.
5916 if (Ty->isNullPtrType())
5917 return true;
5918
5919 // Dig through Src to find the byte at SrcOffset.
5920 switch (Val.getKind()) {
5921 case APValue::Indeterminate:
5922 case APValue::None:
5923 return true;
5924
5925 case APValue::Int:
5926 return visitInt(Val.getInt(), Ty, Offset);
5927 case APValue::Float:
5928 return visitFloat(Val.getFloat(), Ty, Offset);
5929 case APValue::Array:
5930 return visitArray(Val, Ty, Offset);
5931 case APValue::Struct:
5932 return visitRecord(Val, Ty, Offset);
5933
5934 case APValue::ComplexInt:
5935 case APValue::ComplexFloat:
5936 case APValue::Vector:
5937 case APValue::FixedPoint:
5938 // FIXME: We should support these.
5939
5940 case APValue::Union:
5941 case APValue::MemberPointer:
5942 case APValue::AddrLabelDiff: {
5943 Info.FFDiag(BCE->getBeginLoc(),
5944 diag::note_constexpr_bit_cast_unsupported_type)
5945 << Ty;
5946 return false;
5947 }
5948
5949 case APValue::LValue:
5950 llvm_unreachable("LValue subobject in bit_cast?");
5951 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005952 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005953 }
5954
5955 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5956 const RecordDecl *RD = Ty->getAsRecordDecl();
5957 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5958
5959 // Visit the base classes.
5960 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5961 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5962 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5963 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5964
5965 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5966 Layout.getBaseClassOffset(BaseDecl) + Offset))
5967 return false;
5968 }
5969 }
5970
5971 // Visit the fields.
5972 unsigned FieldIdx = 0;
5973 for (FieldDecl *FD : RD->fields()) {
5974 if (FD->isBitField()) {
5975 Info.FFDiag(BCE->getBeginLoc(),
5976 diag::note_constexpr_bit_cast_unsupported_bitfield);
5977 return false;
5978 }
5979
5980 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5981
5982 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5983 "only bit-fields can have sub-char alignment");
5984 CharUnits FieldOffset =
5985 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5986 QualType FieldTy = FD->getType();
5987 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5988 return false;
5989 ++FieldIdx;
5990 }
5991
5992 return true;
5993 }
5994
5995 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5996 const auto *CAT =
5997 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5998 if (!CAT)
5999 return false;
6000
6001 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6002 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6003 unsigned ArraySize = Val.getArraySize();
6004 // First, initialize the initialized elements.
6005 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6006 const APValue &SubObj = Val.getArrayInitializedElt(I);
6007 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6008 return false;
6009 }
6010
6011 // Next, initialize the rest of the array using the filler.
6012 if (Val.hasArrayFiller()) {
6013 const APValue &Filler = Val.getArrayFiller();
6014 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6015 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6016 return false;
6017 }
6018 }
6019
6020 return true;
6021 }
6022
6023 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6024 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6025 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6026 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6027 Buffer.writeObject(Offset, Bytes);
6028 return true;
6029 }
6030
6031 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6032 APSInt AsInt(Val.bitcastToAPInt());
6033 return visitInt(AsInt, Ty, Offset);
6034 }
6035
6036public:
6037 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6038 const CastExpr *BCE) {
6039 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6040 APValueToBufferConverter Converter(Info, DstSize, BCE);
6041 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6042 return None;
6043 return Converter.Buffer;
6044 }
6045};
6046
6047/// Write an BitCastBuffer into an APValue.
6048class BufferToAPValueConverter {
6049 EvalInfo &Info;
6050 const BitCastBuffer &Buffer;
6051 const CastExpr *BCE;
6052
6053 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6054 const CastExpr *BCE)
6055 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6056
6057 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6058 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6059 // Ideally this will be unreachable.
6060 llvm::NoneType unsupportedType(QualType Ty) {
6061 Info.FFDiag(BCE->getBeginLoc(),
6062 diag::note_constexpr_bit_cast_unsupported_type)
6063 << Ty;
6064 return None;
6065 }
6066
6067 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6068 const EnumType *EnumSugar = nullptr) {
6069 if (T->isNullPtrType()) {
6070 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6071 return APValue((Expr *)nullptr,
6072 /*Offset=*/CharUnits::fromQuantity(NullValue),
6073 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6074 }
6075
6076 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6077 SmallVector<uint8_t, 8> Bytes;
6078 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6079 // If this is std::byte or unsigned char, then its okay to store an
6080 // indeterminate value.
6081 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6082 bool IsUChar =
6083 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6084 T->isSpecificBuiltinType(BuiltinType::Char_U));
6085 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00006086 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006087 Info.FFDiag(BCE->getExprLoc(),
6088 diag::note_constexpr_bit_cast_indet_dest)
6089 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6090 return None;
6091 }
6092
6093 return APValue::IndeterminateValue();
6094 }
6095
6096 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6097 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6098
6099 if (T->isIntegralOrEnumerationType()) {
6100 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6101 return APValue(Val);
6102 }
6103
6104 if (T->isRealFloatingType()) {
6105 const llvm::fltSemantics &Semantics =
6106 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6107 return APValue(APFloat(Semantics, Val));
6108 }
6109
6110 return unsupportedType(QualType(T, 0));
6111 }
6112
6113 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6114 const RecordDecl *RD = RTy->getAsRecordDecl();
6115 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6116
6117 unsigned NumBases = 0;
6118 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6119 NumBases = CXXRD->getNumBases();
6120
6121 APValue ResultVal(APValue::UninitStruct(), NumBases,
6122 std::distance(RD->field_begin(), RD->field_end()));
6123
6124 // Visit the base classes.
6125 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6126 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6127 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6128 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6129 if (BaseDecl->isEmpty() ||
6130 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6131 continue;
6132
6133 Optional<APValue> SubObj = visitType(
6134 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6135 if (!SubObj)
6136 return None;
6137 ResultVal.getStructBase(I) = *SubObj;
6138 }
6139 }
6140
6141 // Visit the fields.
6142 unsigned FieldIdx = 0;
6143 for (FieldDecl *FD : RD->fields()) {
6144 // FIXME: We don't currently support bit-fields. A lot of the logic for
6145 // this is in CodeGen, so we need to factor it around.
6146 if (FD->isBitField()) {
6147 Info.FFDiag(BCE->getBeginLoc(),
6148 diag::note_constexpr_bit_cast_unsupported_bitfield);
6149 return None;
6150 }
6151
6152 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6153 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6154
6155 CharUnits FieldOffset =
6156 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6157 Offset;
6158 QualType FieldTy = FD->getType();
6159 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6160 if (!SubObj)
6161 return None;
6162 ResultVal.getStructField(FieldIdx) = *SubObj;
6163 ++FieldIdx;
6164 }
6165
6166 return ResultVal;
6167 }
6168
6169 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6170 QualType RepresentationType = Ty->getDecl()->getIntegerType();
6171 assert(!RepresentationType.isNull() &&
6172 "enum forward decl should be caught by Sema");
6173 const BuiltinType *AsBuiltin =
6174 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
6175 assert(AsBuiltin && "non-integral enum underlying type?");
6176 // Recurse into the underlying type. Treat std::byte transparently as
6177 // unsigned char.
6178 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6179 }
6180
6181 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6182 size_t Size = Ty->getSize().getLimitedValue();
6183 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6184
6185 APValue ArrayValue(APValue::UninitArray(), Size, Size);
6186 for (size_t I = 0; I != Size; ++I) {
6187 Optional<APValue> ElementValue =
6188 visitType(Ty->getElementType(), Offset + I * ElementWidth);
6189 if (!ElementValue)
6190 return None;
6191 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6192 }
6193
6194 return ArrayValue;
6195 }
6196
6197 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6198 return unsupportedType(QualType(Ty, 0));
6199 }
6200
6201 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6202 QualType Can = Ty.getCanonicalType();
6203
6204 switch (Can->getTypeClass()) {
6205#define TYPE(Class, Base) \
6206 case Type::Class: \
6207 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6208#define ABSTRACT_TYPE(Class, Base)
6209#define NON_CANONICAL_TYPE(Class, Base) \
6210 case Type::Class: \
6211 llvm_unreachable("non-canonical type should be impossible!");
6212#define DEPENDENT_TYPE(Class, Base) \
6213 case Type::Class: \
6214 llvm_unreachable( \
6215 "dependent types aren't supported in the constant evaluator!");
6216#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
6217 case Type::Class: \
6218 llvm_unreachable("either dependent or not canonical!");
6219#include "clang/AST/TypeNodes.def"
6220 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006221 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006222 }
6223
6224public:
6225 // Pull out a full value of type DstType.
6226 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6227 const CastExpr *BCE) {
6228 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6229 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6230 }
6231};
6232
6233static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6234 QualType Ty, EvalInfo *Info,
6235 const ASTContext &Ctx,
6236 bool CheckingDest) {
6237 Ty = Ty.getCanonicalType();
6238
6239 auto diag = [&](int Reason) {
6240 if (Info)
6241 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6242 << CheckingDest << (Reason == 4) << Reason;
6243 return false;
6244 };
6245 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6246 if (Info)
6247 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6248 << NoteTy << Construct << Ty;
6249 return false;
6250 };
6251
6252 if (Ty->isUnionType())
6253 return diag(0);
6254 if (Ty->isPointerType())
6255 return diag(1);
6256 if (Ty->isMemberPointerType())
6257 return diag(2);
6258 if (Ty.isVolatileQualified())
6259 return diag(3);
6260
6261 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6262 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6263 for (CXXBaseSpecifier &BS : CXXRD->bases())
6264 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6265 CheckingDest))
6266 return note(1, BS.getType(), BS.getBeginLoc());
6267 }
6268 for (FieldDecl *FD : Record->fields()) {
6269 if (FD->getType()->isReferenceType())
6270 return diag(4);
6271 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6272 CheckingDest))
6273 return note(0, FD->getType(), FD->getBeginLoc());
6274 }
6275 }
6276
6277 if (Ty->isArrayType() &&
6278 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6279 Info, Ctx, CheckingDest))
6280 return false;
6281
6282 return true;
6283}
6284
6285static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6286 const ASTContext &Ctx,
6287 const CastExpr *BCE) {
6288 bool DestOK = checkBitCastConstexprEligibilityType(
6289 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6290 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6291 BCE->getBeginLoc(),
6292 BCE->getSubExpr()->getType(), Info, Ctx, false);
6293 return SourceOK;
6294}
6295
6296static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6297 APValue &SourceValue,
6298 const CastExpr *BCE) {
6299 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6300 "no host or target supports non 8-bit chars");
6301 assert(SourceValue.isLValue() &&
6302 "LValueToRValueBitcast requires an lvalue operand!");
6303
6304 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6305 return false;
6306
6307 LValue SourceLValue;
6308 APValue SourceRValue;
6309 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00006310 if (!handleLValueToRValueConversion(
6311 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6312 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006313 return false;
6314
6315 // Read out SourceValue into a char buffer.
6316 Optional<BitCastBuffer> Buffer =
6317 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6318 if (!Buffer)
6319 return false;
6320
6321 // Write out the buffer into a new APValue.
6322 Optional<APValue> MaybeDestValue =
6323 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6324 if (!MaybeDestValue)
6325 return false;
6326
6327 DestValue = std::move(*MaybeDestValue);
6328 return true;
6329}
6330
Aaron Ballman68af21c2014-01-03 19:26:43 +00006331template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00006332class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006333 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00006334private:
Richard Smith52a980a2015-08-28 02:43:42 +00006335 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006336 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006337 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006338 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006339 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006340 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006341 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006342
Richard Smith17100ba2012-02-16 02:46:34 +00006343 // Check whether a conditional operator with a non-constant condition is a
6344 // potential constant expression. If neither arm is a potential constant
6345 // expression, then the conditional operator is not either.
6346 template<typename ConditionalOperator>
6347 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00006348 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00006349
6350 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00006351 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00006352 {
Richard Smith17100ba2012-02-16 02:46:34 +00006353 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006354 StmtVisitorTy::Visit(E->getFalseExpr());
6355 if (Diag.empty())
6356 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00006357 }
Richard Smith17100ba2012-02-16 02:46:34 +00006358
George Burgess IV8c892b52016-05-25 22:31:54 +00006359 {
6360 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006361 Diag.clear();
6362 StmtVisitorTy::Visit(E->getTrueExpr());
6363 if (Diag.empty())
6364 return;
6365 }
6366
6367 Error(E, diag::note_constexpr_conditional_never_const);
6368 }
6369
6370
6371 template<typename ConditionalOperator>
6372 bool HandleConditionalOperator(const ConditionalOperator *E) {
6373 bool BoolResult;
6374 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00006375 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00006376 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00006377 return false;
6378 }
6379 if (Info.noteFailure()) {
6380 StmtVisitorTy::Visit(E->getTrueExpr());
6381 StmtVisitorTy::Visit(E->getFalseExpr());
6382 }
Richard Smith17100ba2012-02-16 02:46:34 +00006383 return false;
6384 }
6385
6386 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6387 return StmtVisitorTy::Visit(EvalExpr);
6388 }
6389
Peter Collingbournee9200682011-05-13 03:29:01 +00006390protected:
6391 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006392 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00006393 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6394
Richard Smith92b1ce02011-12-12 09:28:41 +00006395 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006396 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006397 }
6398
Aaron Ballman68af21c2014-01-03 19:26:43 +00006399 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006400
6401public:
6402 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6403
6404 EvalInfo &getEvalInfo() { return Info; }
6405
Richard Smithf57d8cb2011-12-09 22:58:01 +00006406 /// Report an evaluation error. This should only be called when an error is
6407 /// first discovered. When propagating an error, just return false.
6408 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006409 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006410 return false;
6411 }
6412 bool Error(const Expr *E) {
6413 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6414 }
6415
Aaron Ballman68af21c2014-01-03 19:26:43 +00006416 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00006417 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00006418 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006419 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006420 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006421 }
6422
Bill Wendling8003edc2018-11-09 00:41:36 +00006423 bool VisitConstantExpr(const ConstantExpr *E)
6424 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006425 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006426 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006427 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006428 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006429 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006430 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006431 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00006432 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006433 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006434 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006435 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00006436 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006437 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6438 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00006439 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006440 return StmtVisitorTy::Visit(E->getExpr());
6441 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006442 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006443 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00006444 // The initializer may not have been parsed yet, or might be erroneous.
6445 if (!E->getExpr())
6446 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00006447 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00006448 return StmtVisitorTy::Visit(E->getExpr());
6449 }
Eric Fiselier708afb52019-05-16 21:04:15 +00006450
Richard Smith457226e2019-09-23 03:48:44 +00006451 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6452 FullExpressionRAII Scope(Info);
6453 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6454 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006455
Aaron Ballman68af21c2014-01-03 19:26:43 +00006456 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006457 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6458 return static_cast<Derived*>(this)->VisitCastExpr(E);
6459 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006460 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00006461 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6462 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006463 return static_cast<Derived*>(this)->VisitCastExpr(E);
6464 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006465 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6466 return static_cast<Derived*>(this)->VisitCastExpr(E);
6467 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006468
Aaron Ballman68af21c2014-01-03 19:26:43 +00006469 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006470 switch (E->getOpcode()) {
6471 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006472 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006473
6474 case BO_Comma:
6475 VisitIgnoredValue(E->getLHS());
6476 return StmtVisitorTy::Visit(E->getRHS());
6477
6478 case BO_PtrMemD:
6479 case BO_PtrMemI: {
6480 LValue Obj;
6481 if (!HandleMemberPointerAccess(Info, E, Obj))
6482 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006483 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006484 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006485 return false;
6486 return DerivedSuccess(Result, E);
6487 }
6488 }
6489 }
6490
Aaron Ballman68af21c2014-01-03 19:26:43 +00006491 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006492 // Evaluate and cache the common expression. We treat it as a temporary,
6493 // even though it's not quite the same thing.
Richard Smith457226e2019-09-23 03:48:44 +00006494 LValue CommonLV;
6495 if (!Evaluate(Info.CurrentCall->createTemporary(
Richard Smith61422f92019-09-27 20:24:36 +00006496 E->getOpaqueValue(),
6497 getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6498 CommonLV),
Richard Smith26d4cc12012-06-26 08:12:11 +00006499 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006500 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006501
Richard Smith17100ba2012-02-16 02:46:34 +00006502 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006503 }
6504
Aaron Ballman68af21c2014-01-03 19:26:43 +00006505 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006506 bool IsBcpCall = false;
6507 // If the condition (ignoring parens) is a __builtin_constant_p call,
6508 // the result is a constant expression if it can be folded without
6509 // side-effects. This is an important GNU extension. See GCC PR38377
6510 // for discussion.
6511 if (const CallExpr *CallCE =
6512 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006513 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006514 IsBcpCall = true;
6515
6516 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6517 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00006518 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6519 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00006520 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006521 return false;
6522
Richard Smith6d4c6582013-11-05 22:18:15 +00006523 FoldConstant Fold(Info, IsBcpCall);
6524 if (!HandleConditionalOperator(E)) {
6525 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006526 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006527 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006528
6529 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006530 }
6531
Aaron Ballman68af21c2014-01-03 19:26:43 +00006532 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006533 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006534 return DerivedSuccess(*Value, E);
6535
6536 const Expr *Source = E->getSourceExpr();
6537 if (!Source)
6538 return Error(E);
6539 if (Source == E) { // sanity checking.
6540 assert(0 && "OpaqueValueExpr recursively refers to itself");
6541 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006542 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006543 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006544 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006545
Aaron Ballman68af21c2014-01-03 19:26:43 +00006546 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006547 APValue Result;
6548 if (!handleCallExpr(E, Result, nullptr))
6549 return false;
6550 return DerivedSuccess(Result, E);
6551 }
6552
6553 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006554 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006555 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006556 QualType CalleeType = Callee->getType();
6557
Craig Topper36250ad2014-05-12 05:36:57 +00006558 const FunctionDecl *FD = nullptr;
6559 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006560 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006561 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006562
Richard Smithe97cbd72011-11-11 04:05:33 +00006563 // Extract function decl and 'this' pointer from the callee.
6564 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006565 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006566 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6567 // Explicit bound member calls, such as x.f() or p->g();
6568 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006569 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006570 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6571 if (!Member)
6572 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006573 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006574 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006575 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6576 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006577 Member = dyn_cast_or_null<CXXMethodDecl>(
6578 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6579 if (!Member)
6580 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006581 This = &ThisVal;
Richard Smith61422f92019-09-27 20:24:36 +00006582 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6583 if (!Info.getLangOpts().CPlusPlus2a)
6584 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6585 // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6586 // their callee, we should start calling HandleDestruction here.
6587 // For now, we just evaluate the object argument and discard it.
6588 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
Richard Smith027bf112011-11-17 22:56:20 +00006589 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006590 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006591 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006592 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006593 LValue Call;
6594 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006595 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006596
Richard Smitha8105bc2012-01-06 16:39:00 +00006597 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006598 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006599 FD = dyn_cast_or_null<FunctionDecl>(
6600 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006601 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006602 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006603 // Don't call function pointers which have been cast to some other type.
6604 // Per DR (no number yet), the caller and callee can differ in noexcept.
6605 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6606 CalleeType->getPointeeType(), FD->getType())) {
6607 return Error(E);
6608 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006609
6610 // Overloaded operator calls to member functions are represented as normal
6611 // calls with '*this' as the first argument.
6612 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6613 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006614 // FIXME: When selecting an implicit conversion for an overloaded
6615 // operator delete, we sometimes try to evaluate calls to conversion
6616 // operators without a 'this' parameter!
6617 if (Args.empty())
6618 return Error(E);
6619
Nick Lewycky13073a62017-06-12 21:15:44 +00006620 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006621 return false;
6622 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006623 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006624 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006625 // Map the static invoker for the lambda back to the call operator.
6626 // Conveniently, we don't have to slice out the 'this' argument (as is
6627 // being done for the non-static case), since a static member function
6628 // doesn't have an implicit argument passed in.
6629 const CXXRecordDecl *ClosureClass = MD->getParent();
6630 assert(
6631 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6632 "Number of captures must be zero for conversion to function-ptr");
6633
6634 const CXXMethodDecl *LambdaCallOp =
6635 ClosureClass->getLambdaCallOperator();
6636
6637 // Set 'FD', the function that will be called below, to the call
6638 // operator. If the closure object represents a generic lambda, find
6639 // the corresponding specialization of the call operator.
6640
6641 if (ClosureClass->isGenericLambda()) {
6642 assert(MD->isFunctionTemplateSpecialization() &&
6643 "A generic lambda's static-invoker function must be a "
6644 "template specialization");
6645 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6646 FunctionTemplateDecl *CallOpTemplate =
6647 LambdaCallOp->getDescribedFunctionTemplate();
6648 void *InsertPos = nullptr;
6649 FunctionDecl *CorrespondingCallOpSpecialization =
6650 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6651 assert(CorrespondingCallOpSpecialization &&
6652 "We must always have a function call operator specialization "
6653 "that corresponds to our static invoker specialization");
6654 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6655 } else
6656 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00006657 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006658 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006659 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006660
Richard Smith921f1322019-05-13 23:35:21 +00006661 SmallVector<QualType, 4> CovariantAdjustmentPath;
6662 if (This) {
6663 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006664 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6665 // Perform virtual dispatch, if necessary.
6666 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6667 CovariantAdjustmentPath);
6668 if (!FD)
6669 return false;
6670 } else {
6671 // Check that the 'this' pointer points to an object of the right type.
Richard Smith61422f92019-09-27 20:24:36 +00006672 // FIXME: If this is an assignment operator call, we may need to change
6673 // the active union member before we check this.
6674 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
Richard Smith7bd54ab2019-05-15 20:22:21 +00006675 return false;
6676 }
Richard Smith921f1322019-05-13 23:35:21 +00006677 }
Richard Smith47b34932012-02-01 02:39:43 +00006678
Richard Smith61422f92019-09-27 20:24:36 +00006679 // Destructor calls are different enough that they have their own codepath.
6680 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
6681 assert(This && "no 'this' pointer for destructor call");
6682 return HandleDestruction(Info, E, *This,
6683 Info.Ctx.getRecordType(DD->getParent()));
6684 }
6685
Craig Topper36250ad2014-05-12 05:36:57 +00006686 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006687 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006688
Nick Lewycky13073a62017-06-12 21:15:44 +00006689 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6690 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006691 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006692 return false;
6693
Richard Smith921f1322019-05-13 23:35:21 +00006694 if (!CovariantAdjustmentPath.empty() &&
6695 !HandleCovariantReturnAdjustment(Info, E, Result,
6696 CovariantAdjustmentPath))
6697 return false;
6698
Richard Smith52a980a2015-08-28 02:43:42 +00006699 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006700 }
6701
Aaron Ballman68af21c2014-01-03 19:26:43 +00006702 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006703 return StmtVisitorTy::Visit(E->getInitializer());
6704 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006705 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006706 if (E->getNumInits() == 0)
6707 return DerivedZeroInitialization(E);
6708 if (E->getNumInits() == 1)
6709 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006710 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006711 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006712 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006713 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006714 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006715 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006716 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006717 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006718 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006719 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006720 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006721
Richard Smithd62306a2011-11-10 06:34:14 +00006722 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006723 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006724 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6725 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006726 assert(!E->isArrow() && "missing call to bound member function?");
6727
Richard Smith2e312c82012-03-03 22:46:17 +00006728 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006729 if (!Evaluate(Val, Info, E->getBase()))
6730 return false;
6731
6732 QualType BaseTy = E->getBase()->getType();
6733
6734 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00006735 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006736 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00006737 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00006738 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6739
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006740 // Note: there is no lvalue base here. But this case should only ever
6741 // happen in C or in C++98, where we cannot be evaluating a constexpr
6742 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00006743 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00006744 SubobjectDesignator Designator(BaseTy);
6745 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00006746
Richard Smith3229b742013-05-05 21:17:10 +00006747 APValue Result;
6748 return extractSubobject(Info, E, Obj, Designator, Result) &&
6749 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00006750 }
6751
Aaron Ballman68af21c2014-01-03 19:26:43 +00006752 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006753 switch (E->getCastKind()) {
6754 default:
6755 break;
6756
Richard Smitha23ab512013-05-23 00:30:41 +00006757 case CK_AtomicToNonAtomic: {
6758 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00006759 // This does not need to be done in place even for class/array types:
6760 // atomic-to-non-atomic conversion implies copying the object
6761 // representation.
6762 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00006763 return false;
6764 return DerivedSuccess(AtomicVal, E);
6765 }
6766
Richard Smith11562c52011-10-28 17:51:58 +00006767 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00006768 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00006769 return StmtVisitorTy::Visit(E->getSubExpr());
6770
6771 case CK_LValueToRValue: {
6772 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006773 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6774 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006775 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00006776 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00006777 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00006778 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006779 return false;
6780 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00006781 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006782 case CK_LValueToRValueBitCast: {
6783 APValue DestValue, SourceValue;
6784 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6785 return false;
6786 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6787 return false;
6788 return DerivedSuccess(DestValue, E);
6789 }
Richard Smith11562c52011-10-28 17:51:58 +00006790 }
6791
Richard Smithf57d8cb2011-12-09 22:58:01 +00006792 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006793 }
6794
Aaron Ballman68af21c2014-01-03 19:26:43 +00006795 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006796 return VisitUnaryPostIncDec(UO);
6797 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006798 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006799 return VisitUnaryPostIncDec(UO);
6800 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006801 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006802 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006803 return Error(UO);
6804
6805 LValue LVal;
6806 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6807 return false;
6808 APValue RVal;
6809 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6810 UO->isIncrementOp(), &RVal))
6811 return false;
6812 return DerivedSuccess(RVal, UO);
6813 }
6814
Aaron Ballman68af21c2014-01-03 19:26:43 +00006815 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00006816 // We will have checked the full-expressions inside the statement expression
6817 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00006818 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00006819 return Error(E);
6820
6821 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006822 if (CS->body_empty())
6823 return true;
6824
Richard Smith457226e2019-09-23 03:48:44 +00006825 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00006826 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6827 BE = CS->body_end();
6828 /**/; ++BI) {
6829 if (BI + 1 == BE) {
6830 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6831 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006832 Info.FFDiag((*BI)->getBeginLoc(),
6833 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006834 return false;
6835 }
Richard Smith457226e2019-09-23 03:48:44 +00006836 return this->Visit(FinalExpr) && Scope.destroy();
Richard Smith51f03172013-06-20 03:00:05 +00006837 }
6838
6839 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00006840 StmtResult Result = { ReturnValue, nullptr };
6841 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00006842 if (ESR != ESR_Succeeded) {
6843 // FIXME: If the statement-expression terminated due to 'return',
6844 // 'break', or 'continue', it would be nice to propagate that to
6845 // the outer statement evaluation rather than bailing out.
6846 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006847 Info.FFDiag((*BI)->getBeginLoc(),
6848 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006849 return false;
6850 }
6851 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006852
6853 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00006854 }
6855
Richard Smith4a678122011-10-24 18:44:57 +00006856 /// Visit a value which is evaluated, but whose value is ignored.
6857 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00006858 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00006859 }
David Majnemere9807b22016-02-26 04:23:19 +00006860
6861 /// Potentially visit a MemberExpr's base expression.
6862 void VisitIgnoredBaseExpression(const Expr *E) {
6863 // While MSVC doesn't evaluate the base expression, it does diagnose the
6864 // presence of side-effecting behavior.
6865 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6866 return;
6867 VisitIgnoredValue(E);
6868 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006869};
6870
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006871} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00006872
6873//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006874// Common base class for lvalue and temporary evaluation.
6875//===----------------------------------------------------------------------===//
6876namespace {
6877template<class Derived>
6878class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006879 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00006880protected:
6881 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006882 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00006883 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006884 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00006885
6886 bool Success(APValue::LValueBase B) {
6887 Result.set(B);
6888 return true;
6889 }
6890
George Burgess IVf9013bf2017-02-10 22:52:29 +00006891 bool evaluatePointer(const Expr *E, LValue &Result) {
6892 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6893 }
6894
Richard Smith027bf112011-11-17 22:56:20 +00006895public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006896 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6897 : ExprEvaluatorBaseTy(Info), Result(Result),
6898 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00006899
Richard Smith2e312c82012-03-03 22:46:17 +00006900 bool Success(const APValue &V, const Expr *E) {
6901 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00006902 return true;
6903 }
Richard Smith027bf112011-11-17 22:56:20 +00006904
Richard Smith027bf112011-11-17 22:56:20 +00006905 bool VisitMemberExpr(const MemberExpr *E) {
6906 // Handle non-static data members.
6907 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006908 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00006909 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006910 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00006911 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00006912 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006913 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00006914 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00006915 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00006916 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00006917 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00006918 BaseTy = E->getBase()->getType();
6919 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00006920 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006921 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006922 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006923 Result.setInvalid(E);
6924 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006925 }
Richard Smith027bf112011-11-17 22:56:20 +00006926
Richard Smith1b78b3d2012-01-25 22:15:11 +00006927 const ValueDecl *MD = E->getMemberDecl();
6928 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6929 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6930 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6931 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00006932 if (!HandleLValueMember(this->Info, E, Result, FD))
6933 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006934 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00006935 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6936 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006937 } else
6938 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006939
Richard Smith1b78b3d2012-01-25 22:15:11 +00006940 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00006941 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00006942 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00006943 RefValue))
6944 return false;
6945 return Success(RefValue, E);
6946 }
6947 return true;
6948 }
6949
6950 bool VisitBinaryOperator(const BinaryOperator *E) {
6951 switch (E->getOpcode()) {
6952 default:
6953 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6954
6955 case BO_PtrMemD:
6956 case BO_PtrMemI:
6957 return HandleMemberPointerAccess(this->Info, E, Result);
6958 }
6959 }
6960
6961 bool VisitCastExpr(const CastExpr *E) {
6962 switch (E->getCastKind()) {
6963 default:
6964 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6965
6966 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006967 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00006968 if (!this->Visit(E->getSubExpr()))
6969 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006970
6971 // Now figure out the necessary offset to add to the base LV to get from
6972 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006973 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6974 Result);
Richard Smith027bf112011-11-17 22:56:20 +00006975 }
6976 }
6977};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006978}
Richard Smith027bf112011-11-17 22:56:20 +00006979
6980//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00006981// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006982//
6983// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6984// function designators (in C), decl references to void objects (in C), and
6985// temporaries (if building with -Wno-address-of-temporary).
6986//
6987// LValue evaluation produces values comprising a base expression of one of the
6988// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006989// - Declarations
6990// * VarDecl
6991// * FunctionDecl
6992// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006993// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006994// * StringLiteral
6995// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006996// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006997// * ObjCEncodeExpr
6998// * AddrLabelExpr
6999// * BlockExpr
7000// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00007001// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00007002// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00007003// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00007004// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00007005// was evaluated, for cases where the MaterializeTemporaryExpr is missing
7006// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00007007// * A MaterializeTemporaryExpr that has static storage duration, with no
7008// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00007009// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00007010//===----------------------------------------------------------------------===//
7011namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007012class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00007013 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00007014public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007015 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7016 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00007017
Richard Smith11562c52011-10-28 17:51:58 +00007018 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00007019 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00007020
Peter Collingbournee9200682011-05-13 03:29:01 +00007021 bool VisitDeclRefExpr(const DeclRefExpr *E);
7022 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007023 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007024 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7025 bool VisitMemberExpr(const MemberExpr *E);
7026 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7027 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00007028 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00007029 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007030 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7031 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00007032 bool VisitUnaryReal(const UnaryOperator *E);
7033 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00007034 bool VisitUnaryPreInc(const UnaryOperator *UO) {
7035 return VisitUnaryPreIncDec(UO);
7036 }
7037 bool VisitUnaryPreDec(const UnaryOperator *UO) {
7038 return VisitUnaryPreIncDec(UO);
7039 }
Richard Smith3229b742013-05-05 21:17:10 +00007040 bool VisitBinAssign(const BinaryOperator *BO);
7041 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00007042
Peter Collingbournee9200682011-05-13 03:29:01 +00007043 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00007044 switch (E->getCastKind()) {
7045 default:
Richard Smith027bf112011-11-17 22:56:20 +00007046 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00007047
Eli Friedmance3e02a2011-10-11 00:13:24 +00007048 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00007049 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00007050 if (!Visit(E->getSubExpr()))
7051 return false;
7052 Result.Designator.setInvalid();
7053 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00007054
Richard Smith027bf112011-11-17 22:56:20 +00007055 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00007056 if (!Visit(E->getSubExpr()))
7057 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007058 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00007059
7060 case CK_Dynamic:
7061 if (!Visit(E->getSubExpr()))
7062 return false;
7063 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00007064 }
7065 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007066};
7067} // end anonymous namespace
7068
Richard Smith11562c52011-10-28 17:51:58 +00007069/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00007070/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00007071/// * function designators in C, and
7072/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00007073/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00007074static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7075 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00007076 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00007077 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00007078 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007079}
7080
Peter Collingbournee9200682011-05-13 03:29:01 +00007081bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00007082 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00007083 return Success(FD);
7084 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00007085 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00007086 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00007087 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00007088 return Error(E);
7089}
Richard Smith733237d2011-10-24 23:14:33 +00007090
Faisal Vali0528a312016-11-13 06:09:16 +00007091
Richard Smith11562c52011-10-28 17:51:58 +00007092bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007093
7094 // If we are within a lambda's call operator, check whether the 'VD' referred
7095 // to within 'E' actually represents a lambda-capture that maps to a
7096 // data-member/field within the closure object, and if so, evaluate to the
7097 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00007098 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7099 isa<DeclRefExpr>(E) &&
7100 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7101 // We don't always have a complete capture-map when checking or inferring if
7102 // the function call operator meets the requirements of a constexpr function
7103 // - but we don't need to evaluate the captures to determine constexprness
7104 // (dcl.constexpr C++17).
7105 if (Info.checkingPotentialConstantExpression())
7106 return false;
7107
Faisal Vali051e3a22017-02-16 04:12:21 +00007108 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007109 // Start with 'Result' referring to the complete closure object...
7110 Result = *Info.CurrentCall->This;
7111 // ... then update it to refer to the field of the closure object
7112 // that represents the capture.
7113 if (!HandleLValueMember(Info, E, Result, FD))
7114 return false;
7115 // And if the field is of reference type, update 'Result' to refer to what
7116 // the field refers to.
7117 if (FD->getType()->isReferenceType()) {
7118 APValue RVal;
7119 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7120 RVal))
7121 return false;
7122 Result.setFrom(Info.Ctx, RVal);
7123 }
7124 return true;
7125 }
7126 }
Craig Topper36250ad2014-05-12 05:36:57 +00007127 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00007128 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7129 // Only if a local variable was declared in the function currently being
7130 // evaluated, do we expect to be able to find its value in the current
7131 // frame. (Otherwise it was likely declared in an enclosing context and
7132 // could either have a valid evaluatable value (for e.g. a constexpr
7133 // variable) or be ill-formed (and trigger an appropriate evaluation
7134 // diagnostic)).
7135 if (Info.CurrentCall->Callee &&
7136 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7137 Frame = Info.CurrentCall;
7138 }
7139 }
Richard Smith3229b742013-05-05 21:17:10 +00007140
Richard Smithfec09922011-11-01 16:57:24 +00007141 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00007142 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007143 Result.set({VD, Frame->Index,
7144 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00007145 return true;
7146 }
Richard Smithce40ad62011-11-12 22:28:03 +00007147 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00007148 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00007149
Richard Smith3229b742013-05-05 21:17:10 +00007150 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007151 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007152 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00007153 if (!V->hasValue()) {
7154 // FIXME: Is it possible for V to be indeterminate here? If so, we should
7155 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00007156 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00007157 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007158 return false;
7159 }
Richard Smith3229b742013-05-05 21:17:10 +00007160 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00007161}
7162
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007163bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7164 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007165 // Walk through the expression to find the materialized temporary itself.
7166 SmallVector<const Expr *, 2> CommaLHSs;
7167 SmallVector<SubobjectAdjustment, 2> Adjustments;
7168 const Expr *Inner = E->GetTemporaryExpr()->
7169 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00007170
Richard Smith84401042013-06-03 05:03:02 +00007171 // If we passed any comma operators, evaluate their LHSs.
7172 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7173 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7174 return false;
7175
Richard Smithe6c01442013-06-05 00:46:14 +00007176 // A materialized temporary with static storage duration can appear within the
7177 // result of a constant expression evaluation, so we need to preserve its
7178 // value for use outside this evaluation.
7179 APValue *Value;
7180 if (E->getStorageDuration() == SD_Static) {
7181 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00007182 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00007183 Result.set(E);
7184 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007185 Value = &Info.CurrentCall->createTemporary(
7186 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
Richard Smithe6c01442013-06-05 00:46:14 +00007187 }
7188
Richard Smithea4ad5d2013-06-06 08:19:16 +00007189 QualType Type = Inner->getType();
7190
Richard Smith84401042013-06-03 05:03:02 +00007191 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00007192 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
7193 (E->getStorageDuration() == SD_Static &&
7194 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
7195 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00007196 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00007197 }
Richard Smith84401042013-06-03 05:03:02 +00007198
7199 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00007200 for (unsigned I = Adjustments.size(); I != 0; /**/) {
7201 --I;
7202 switch (Adjustments[I].Kind) {
7203 case SubobjectAdjustment::DerivedToBaseAdjustment:
7204 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7205 Type, Result))
7206 return false;
7207 Type = Adjustments[I].DerivedToBase.BasePath->getType();
7208 break;
7209
7210 case SubobjectAdjustment::FieldAdjustment:
7211 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7212 return false;
7213 Type = Adjustments[I].Field->getType();
7214 break;
7215
7216 case SubobjectAdjustment::MemberPointerAdjustment:
7217 if (!HandleMemberPointerAccess(this->Info, Type, Result,
7218 Adjustments[I].Ptr.RHS))
7219 return false;
7220 Type = Adjustments[I].Ptr.MPT->getPointeeType();
7221 break;
7222 }
7223 }
7224
7225 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007226}
7227
Peter Collingbournee9200682011-05-13 03:29:01 +00007228bool
7229LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00007230 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7231 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00007232 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7233 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00007234 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007235}
7236
Richard Smith6e525142011-12-27 12:18:28 +00007237bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00007238 TypeInfoLValue TypeInfo;
7239
Richard Smithee0ce3022019-05-17 07:06:46 +00007240 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00007241 if (E->isTypeOperand())
7242 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7243 else
7244 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00007245 } else {
7246 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7247 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7248 << E->getExprOperand()->getType()
7249 << E->getExprOperand()->getSourceRange();
7250 }
7251
7252 if (!Visit(E->getExprOperand()))
7253 return false;
7254
7255 Optional<DynamicType> DynType =
7256 ComputeDynamicType(Info, E, Result, AK_TypeId);
7257 if (!DynType)
7258 return false;
7259
7260 TypeInfo =
7261 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00007262 }
Richard Smith6f3d4352012-10-17 23:52:07 +00007263
Richard Smitha9330302019-05-17 19:19:28 +00007264 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00007265}
7266
Francois Pichet0066db92012-04-16 04:08:35 +00007267bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7268 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00007269}
Francois Pichet0066db92012-04-16 04:08:35 +00007270
Peter Collingbournee9200682011-05-13 03:29:01 +00007271bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007272 // Handle static data members.
7273 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007274 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00007275 return VisitVarDecl(E, VD);
7276 }
7277
Richard Smith254a73d2011-10-28 22:34:42 +00007278 // Handle static member functions.
7279 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7280 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00007281 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00007282 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00007283 }
7284 }
7285
Richard Smithd62306a2011-11-10 06:34:14 +00007286 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00007287 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007288}
7289
Peter Collingbournee9200682011-05-13 03:29:01 +00007290bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007291 // FIXME: Deal with vectors as array subscript bases.
7292 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007293 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007294
Nick Lewyckyad888682017-04-27 07:27:36 +00007295 bool Success = true;
7296 if (!evaluatePointer(E->getBase(), Result)) {
7297 if (!Info.noteFailure())
7298 return false;
7299 Success = false;
7300 }
Mike Stump11289f42009-09-09 15:08:12 +00007301
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007302 APSInt Index;
7303 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00007304 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007305
Nick Lewyckyad888682017-04-27 07:27:36 +00007306 return Success &&
7307 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007308}
Eli Friedman9a156e52008-11-12 09:44:48 +00007309
Peter Collingbournee9200682011-05-13 03:29:01 +00007310bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007311 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00007312}
7313
Richard Smith66c96992012-02-18 22:04:06 +00007314bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7315 if (!Visit(E->getSubExpr()))
7316 return false;
7317 // __real is a no-op on scalar lvalues.
7318 if (E->getSubExpr()->getType()->isAnyComplexType())
7319 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7320 return true;
7321}
7322
7323bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7324 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7325 "lvalue __imag__ on scalar?");
7326 if (!Visit(E->getSubExpr()))
7327 return false;
7328 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7329 return true;
7330}
7331
Richard Smith243ef902013-05-05 23:31:59 +00007332bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007333 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007334 return Error(UO);
7335
7336 if (!this->Visit(UO->getSubExpr()))
7337 return false;
7338
Richard Smith243ef902013-05-05 23:31:59 +00007339 return handleIncDec(
7340 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00007341 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00007342}
7343
7344bool LValueExprEvaluator::VisitCompoundAssignOperator(
7345 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007346 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007347 return Error(CAO);
7348
Richard Smith3229b742013-05-05 21:17:10 +00007349 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00007350
7351 // The overall lvalue result is the result of evaluating the LHS.
7352 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007353 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007354 Evaluate(RHS, this->Info, CAO->getRHS());
7355 return false;
7356 }
7357
Richard Smith3229b742013-05-05 21:17:10 +00007358 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7359 return false;
7360
Richard Smith43e77732013-05-07 04:50:00 +00007361 return handleCompoundAssignment(
7362 this->Info, CAO,
7363 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7364 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00007365}
7366
7367bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007368 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007369 return Error(E);
7370
Richard Smith3229b742013-05-05 21:17:10 +00007371 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00007372
7373 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007374 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007375 Evaluate(NewVal, this->Info, E->getRHS());
7376 return false;
7377 }
7378
Richard Smith3229b742013-05-05 21:17:10 +00007379 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7380 return false;
Richard Smith243ef902013-05-05 23:31:59 +00007381
Richard Smith31c69a32019-05-21 23:15:20 +00007382 if (Info.getLangOpts().CPlusPlus2a &&
7383 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7384 return false;
7385
Richard Smith243ef902013-05-05 23:31:59 +00007386 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00007387 NewVal);
7388}
7389
Eli Friedman9a156e52008-11-12 09:44:48 +00007390//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007391// Pointer Evaluation
7392//===----------------------------------------------------------------------===//
7393
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007394/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00007395/// returned by a function with the alloc_size attribute. Returns true if we
7396/// were successful. Places an unsigned number into `Result`.
7397///
7398/// This expects the given CallExpr to be a call to a function with an
7399/// alloc_size attribute.
7400static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7401 const CallExpr *Call,
7402 llvm::APInt &Result) {
7403 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7404
Joel E. Denny81508102018-03-13 14:51:22 +00007405 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7406 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007407 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7408 if (Call->getNumArgs() <= SizeArgNo)
7409 return false;
7410
7411 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00007412 Expr::EvalResult ExprResult;
7413 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00007414 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007415 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00007416 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7417 return false;
7418 Into = Into.zextOrSelf(BitsInSizeT);
7419 return true;
7420 };
7421
7422 APSInt SizeOfElem;
7423 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7424 return false;
7425
Joel E. Denny81508102018-03-13 14:51:22 +00007426 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007427 Result = std::move(SizeOfElem);
7428 return true;
7429 }
7430
7431 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00007432 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007433 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7434 return false;
7435
7436 bool Overflow;
7437 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7438 if (Overflow)
7439 return false;
7440
7441 Result = std::move(BytesAvailable);
7442 return true;
7443}
7444
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007445/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00007446/// function.
7447static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7448 const LValue &LVal,
7449 llvm::APInt &Result) {
7450 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7451 "Can't get the size of a non alloc_size function");
7452 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7453 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7454 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7455}
7456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007457/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00007458/// a function with the alloc_size attribute. If it was possible to do so, this
7459/// function will return true, make Result's Base point to said function call,
7460/// and mark Result's Base as invalid.
7461static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7462 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007463 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00007464 return false;
7465
7466 // Because we do no form of static analysis, we only support const variables.
7467 //
7468 // Additionally, we can't support parameters, nor can we support static
7469 // variables (in the latter case, use-before-assign isn't UB; in the former,
7470 // we have no clue what they'll be assigned to).
7471 const auto *VD =
7472 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7473 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7474 return false;
7475
7476 const Expr *Init = VD->getAnyInitializer();
7477 if (!Init)
7478 return false;
7479
7480 const Expr *E = Init->IgnoreParens();
7481 if (!tryUnwrapAllocSizeCall(E))
7482 return false;
7483
7484 // Store E instead of E unwrapped so that the type of the LValue's base is
7485 // what the user wanted.
7486 Result.setInvalid(E);
7487
7488 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007489 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007490 return true;
7491}
7492
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007493namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007494class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007495 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007496 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007497 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007498
Peter Collingbournee9200682011-05-13 03:29:01 +00007499 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007500 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007501 return true;
7502 }
George Burgess IVe3763372016-12-22 02:50:20 +00007503
George Burgess IVf9013bf2017-02-10 22:52:29 +00007504 bool evaluateLValue(const Expr *E, LValue &Result) {
7505 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7506 }
7507
7508 bool evaluatePointer(const Expr *E, LValue &Result) {
7509 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7510 }
7511
George Burgess IVe3763372016-12-22 02:50:20 +00007512 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007513public:
Mike Stump11289f42009-09-09 15:08:12 +00007514
George Burgess IVf9013bf2017-02-10 22:52:29 +00007515 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7516 : ExprEvaluatorBaseTy(info), Result(Result),
7517 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007518
Richard Smith2e312c82012-03-03 22:46:17 +00007519 bool Success(const APValue &V, const Expr *E) {
7520 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007521 return true;
7522 }
Richard Smithfddd3842011-12-30 21:15:51 +00007523 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00007524 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7525 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00007526 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007527 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007528
John McCall45d55e42010-05-07 21:00:08 +00007529 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007530 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007531 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007532 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007533 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007534 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007535 if (E->isExpressibleAsConstantInitializer())
7536 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007537 if (Info.noteFailure())
7538 EvaluateIgnoredValue(Info, E->getSubExpr());
7539 return Error(E);
7540 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007541 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007542 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007543 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007544 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007545 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007546 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007547 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007548 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007549 }
Richard Smithd62306a2011-11-10 06:34:14 +00007550 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007551 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007552 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007553 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007554 if (!Info.CurrentCall->This) {
7555 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007556 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007557 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007558 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007559 return false;
7560 }
Richard Smithd62306a2011-11-10 06:34:14 +00007561 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007562 // If we are inside a lambda's call operator, the 'this' expression refers
7563 // to the enclosing '*this' object (either by value or reference) which is
7564 // either copied into the closure object's field that represents the '*this'
7565 // or refers to '*this'.
7566 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7567 // Update 'Result' to refer to the data member/field of the closure object
7568 // that represents the '*this' capture.
7569 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007570 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007571 return false;
7572 // If we captured '*this' by reference, replace the field with its referent.
7573 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7574 ->isPointerType()) {
7575 APValue RVal;
7576 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7577 RVal))
7578 return false;
7579
7580 Result.setFrom(Info.Ctx, RVal);
7581 }
7582 }
Richard Smithd62306a2011-11-10 06:34:14 +00007583 return true;
7584 }
John McCallc07a0c72011-02-17 10:25:35 +00007585
Richard Smithda1b4342019-09-27 01:26:47 +00007586 bool VisitCXXNewExpr(const CXXNewExpr *E);
7587
Eric Fiselier708afb52019-05-16 21:04:15 +00007588 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7589 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7590 APValue LValResult = E->EvaluateInContext(
7591 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7592 Result.setFrom(Info.Ctx, LValResult);
7593 return true;
7594 }
7595
Eli Friedman449fe542009-03-23 04:56:01 +00007596 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007597};
Chris Lattner05706e882008-07-11 18:11:29 +00007598} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007599
George Burgess IVf9013bf2017-02-10 22:52:29 +00007600static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7601 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007602 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007603 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007604}
7605
John McCall45d55e42010-05-07 21:00:08 +00007606bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007607 if (E->getOpcode() != BO_Add &&
7608 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007609 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007610
Chris Lattner05706e882008-07-11 18:11:29 +00007611 const Expr *PExp = E->getLHS();
7612 const Expr *IExp = E->getRHS();
7613 if (IExp->getType()->isPointerType())
7614 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007615
George Burgess IVf9013bf2017-02-10 22:52:29 +00007616 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007617 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007618 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007619
John McCall45d55e42010-05-07 21:00:08 +00007620 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007621 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007622 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007623
Richard Smith96e0c102011-11-04 02:25:55 +00007624 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007625 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007626
Ted Kremenek28831752012-08-23 20:46:57 +00007627 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007628 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007629}
Eli Friedman9a156e52008-11-12 09:44:48 +00007630
John McCall45d55e42010-05-07 21:00:08 +00007631bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007632 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007633}
Mike Stump11289f42009-09-09 15:08:12 +00007634
Richard Smith81dfef92018-07-11 00:29:05 +00007635bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7636 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007637
Eli Friedman847a2bc2009-12-27 05:43:15 +00007638 switch (E->getCastKind()) {
7639 default:
7640 break;
John McCalle3027922010-08-25 11:45:40 +00007641 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007642 case CK_CPointerToObjCPointerCast:
7643 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007644 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007645 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007646 if (!Visit(SubExpr))
7647 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007648 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7649 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7650 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007651 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00007652 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00007653 if (SubExpr->getType()->isVoidPointerType())
7654 CCEDiag(E, diag::note_constexpr_invalid_cast)
7655 << 3 << SubExpr->getType();
7656 else
7657 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7658 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007659 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7660 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007661 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007662
Anders Carlsson18275092010-10-31 20:41:46 +00007663 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007664 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007665 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007666 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007667 if (!Result.Base && Result.Offset.isZero())
7668 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007669
Richard Smithd62306a2011-11-10 06:34:14 +00007670 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007671 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007672 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7673 castAs<PointerType>()->getPointeeType(),
7674 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007675
Richard Smith027bf112011-11-17 22:56:20 +00007676 case CK_BaseToDerived:
7677 if (!Visit(E->getSubExpr()))
7678 return false;
7679 if (!Result.Base && Result.Offset.isZero())
7680 return true;
7681 return HandleBaseToDerivedCast(Info, E, Result);
7682
Richard Smith7bd54ab2019-05-15 20:22:21 +00007683 case CK_Dynamic:
7684 if (!Visit(E->getSubExpr()))
7685 return false;
7686 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7687
Richard Smith0b0a0b62011-10-29 20:57:55 +00007688 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007689 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007690 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007691
John McCalle3027922010-08-25 11:45:40 +00007692 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007693 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7694
Richard Smith2e312c82012-03-03 22:46:17 +00007695 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007696 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007697 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007698
John McCall45d55e42010-05-07 21:00:08 +00007699 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007700 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7701 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007702 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007703 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007704 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007705 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007706 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007707 return true;
7708 } else {
7709 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007710 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007711 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007712 }
7713 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007714
7715 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007716 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007717 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007718 return false;
7719 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007720 APValue &Value = Info.CurrentCall->createTemporary(
7721 SubExpr, SubExpr->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007722 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007723 return false;
7724 }
Richard Smith96e0c102011-11-04 02:25:55 +00007725 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00007726 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7727 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00007728 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00007729 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00007730 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00007731 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00007732 }
Richard Smithdd785442011-10-31 20:57:44 +00007733
John McCalle3027922010-08-25 11:45:40 +00007734 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007735 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007736
7737 case CK_LValueToRValue: {
7738 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007739 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00007740 return false;
7741
7742 APValue RVal;
7743 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7744 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7745 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00007746 return InvalidBaseOK &&
7747 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007748 return Success(RVal, E);
7749 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007750 }
7751
Richard Smith11562c52011-10-28 17:51:58 +00007752 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00007753}
Chris Lattner05706e882008-07-11 18:11:29 +00007754
Richard Smith6822bd72018-10-26 19:26:45 +00007755static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7756 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007757 // C++ [expr.alignof]p3:
7758 // When alignof is applied to a reference type, the result is the
7759 // alignment of the referenced type.
7760 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7761 T = Ref->getPointeeType();
7762
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00007763 if (T.getQualifiers().hasUnaligned())
7764 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00007765
7766 const bool AlignOfReturnsPreferred =
7767 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7768
7769 // __alignof is defined to return the preferred alignment.
7770 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7771 // as well.
7772 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7773 return Info.Ctx.toCharUnitsFromBits(
7774 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7775 // alignof and _Alignof are defined to return the ABI alignment.
7776 else if (ExprKind == UETT_AlignOf)
7777 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7778 else
7779 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00007780}
7781
Richard Smith6822bd72018-10-26 19:26:45 +00007782static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7783 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007784 E = E->IgnoreParens();
7785
7786 // The kinds of expressions that we have special-case logic here for
7787 // should be kept up to date with the special checks for those
7788 // expressions in Sema.
7789
7790 // alignof decl is always accepted, even if it doesn't make sense: we default
7791 // to 1 in those cases.
7792 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7793 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7794 /*RefAsPointee*/true);
7795
7796 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7797 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7798 /*RefAsPointee*/true);
7799
Richard Smith6822bd72018-10-26 19:26:45 +00007800 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007801}
7802
George Burgess IVe3763372016-12-22 02:50:20 +00007803// To be clear: this happily visits unsupported builtins. Better name welcomed.
7804bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7805 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7806 return true;
7807
George Burgess IVf9013bf2017-02-10 22:52:29 +00007808 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00007809 return false;
7810
7811 Result.setInvalid(E);
7812 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007813 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00007814 return true;
7815}
7816
Peter Collingbournee9200682011-05-13 03:29:01 +00007817bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007818 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00007819 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00007820
Richard Smith6328cbd2016-11-16 00:57:23 +00007821 if (unsigned BuiltinOp = E->getBuiltinCallee())
7822 return VisitBuiltinCallExpr(E, BuiltinOp);
7823
George Burgess IVe3763372016-12-22 02:50:20 +00007824 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007825}
7826
7827bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7828 unsigned BuiltinOp) {
7829 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00007830 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007831 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007832 case Builtin::BI__builtin_assume_aligned: {
7833 // We need to be very careful here because: if the pointer does not have the
7834 // asserted alignment, then the behavior is undefined, and undefined
7835 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00007836 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00007837 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00007838
Hal Finkel0dd05d42014-10-03 17:18:37 +00007839 LValue OffsetResult(Result);
7840 APSInt Alignment;
7841 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7842 return false;
Richard Smith642a2362017-01-30 23:30:26 +00007843 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00007844
7845 if (E->getNumArgs() > 2) {
7846 APSInt Offset;
7847 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7848 return false;
7849
Richard Smith642a2362017-01-30 23:30:26 +00007850 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007851 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7852 }
7853
7854 // If there is a base object, then it must have the correct alignment.
7855 if (OffsetResult.Base) {
7856 CharUnits BaseAlignment;
7857 if (const ValueDecl *VD =
7858 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7859 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00007860 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7861 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007862 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00007863 BaseAlignment = GetAlignOfType(
7864 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007865 }
7866
7867 if (BaseAlignment < Align) {
7868 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00007869 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00007870 CCEDiag(E->getArg(0),
7871 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00007872 << (unsigned)BaseAlignment.getQuantity()
7873 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007874 return false;
7875 }
7876 }
7877
7878 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007879 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007880 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007881
Richard Smith642a2362017-01-30 23:30:26 +00007882 (OffsetResult.Base
7883 ? CCEDiag(E->getArg(0),
7884 diag::note_constexpr_baa_insufficient_alignment) << 1
7885 : CCEDiag(E->getArg(0),
7886 diag::note_constexpr_baa_value_insufficient_alignment))
7887 << (int)OffsetResult.Offset.getQuantity()
7888 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007889 return false;
7890 }
7891
7892 return true;
7893 }
Eric Fiselier26187502018-12-14 21:11:28 +00007894 case Builtin::BI__builtin_launder:
7895 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00007896 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007897 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00007898 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007899 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00007900 if (Info.getLangOpts().CPlusPlus11)
7901 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7902 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007903 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00007904 else
7905 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007906 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00007907 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007908 case Builtin::BI__builtin_wcschr:
7909 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007910 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007911 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00007912 if (!Visit(E->getArg(0)))
7913 return false;
7914 APSInt Desired;
7915 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7916 return false;
7917 uint64_t MaxLength = uint64_t(-1);
7918 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007919 BuiltinOp != Builtin::BIwcschr &&
7920 BuiltinOp != Builtin::BI__builtin_strchr &&
7921 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00007922 APSInt N;
7923 if (!EvaluateInteger(E->getArg(2), N, Info))
7924 return false;
7925 MaxLength = N.getExtValue();
7926 }
Hubert Tong147b7432018-12-12 16:53:43 +00007927 // We cannot find the value if there are no candidates to match against.
7928 if (MaxLength == 0u)
7929 return ZeroInitialization(E);
7930 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7931 Result.Designator.Invalid)
7932 return false;
7933 QualType CharTy = Result.Designator.getType(Info.Ctx);
7934 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7935 BuiltinOp == Builtin::BI__builtin_memchr;
7936 assert(IsRawByte ||
7937 Info.Ctx.hasSameUnqualifiedType(
7938 CharTy, E->getArg(0)->getType()->getPointeeType()));
7939 // Pointers to const void may point to objects of incomplete type.
7940 if (IsRawByte && CharTy->isIncompleteType()) {
7941 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7942 return false;
7943 }
7944 // Give up on byte-oriented matching against multibyte elements.
7945 // FIXME: We can compare the bytes in the correct order.
7946 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7947 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007948 // Figure out what value we're actually looking for (after converting to
7949 // the corresponding unsigned type if necessary).
7950 uint64_t DesiredVal;
7951 bool StopAtNull = false;
7952 switch (BuiltinOp) {
7953 case Builtin::BIstrchr:
7954 case Builtin::BI__builtin_strchr:
7955 // strchr compares directly to the passed integer, and therefore
7956 // always fails if given an int that is not a char.
7957 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7958 E->getArg(1)->getType(),
7959 Desired),
7960 Desired))
7961 return ZeroInitialization(E);
7962 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007963 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007964 case Builtin::BImemchr:
7965 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007966 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007967 // memchr compares by converting both sides to unsigned char. That's also
7968 // correct for strchr if we get this far (to cope with plain char being
7969 // unsigned in the strchr case).
7970 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7971 break;
Richard Smithe9507952016-11-12 01:39:56 +00007972
Richard Smith8110c9d2016-11-29 19:45:17 +00007973 case Builtin::BIwcschr:
7974 case Builtin::BI__builtin_wcschr:
7975 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007976 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007977 case Builtin::BIwmemchr:
7978 case Builtin::BI__builtin_wmemchr:
7979 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7980 DesiredVal = Desired.getZExtValue();
7981 break;
7982 }
Richard Smithe9507952016-11-12 01:39:56 +00007983
7984 for (; MaxLength; --MaxLength) {
7985 APValue Char;
7986 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7987 !Char.isInt())
7988 return false;
7989 if (Char.getInt().getZExtValue() == DesiredVal)
7990 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007991 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007992 break;
7993 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7994 return false;
7995 }
7996 // Not found: return nullptr.
7997 return ZeroInitialization(E);
7998 }
7999
Richard Smith06f71b52018-08-04 00:57:17 +00008000 case Builtin::BImemcpy:
8001 case Builtin::BImemmove:
8002 case Builtin::BIwmemcpy:
8003 case Builtin::BIwmemmove:
8004 if (Info.getLangOpts().CPlusPlus11)
8005 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8006 << /*isConstexpr*/0 << /*isConstructor*/0
8007 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8008 else
8009 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8010 LLVM_FALLTHROUGH;
8011 case Builtin::BI__builtin_memcpy:
8012 case Builtin::BI__builtin_memmove:
8013 case Builtin::BI__builtin_wmemcpy:
8014 case Builtin::BI__builtin_wmemmove: {
8015 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8016 BuiltinOp == Builtin::BIwmemmove ||
8017 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8018 BuiltinOp == Builtin::BI__builtin_wmemmove;
8019 bool Move = BuiltinOp == Builtin::BImemmove ||
8020 BuiltinOp == Builtin::BIwmemmove ||
8021 BuiltinOp == Builtin::BI__builtin_memmove ||
8022 BuiltinOp == Builtin::BI__builtin_wmemmove;
8023
8024 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00008025 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00008026 return false;
8027 LValue Dest = Result;
8028
8029 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00008030 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00008031 return false;
8032
8033 APSInt N;
8034 if (!EvaluateInteger(E->getArg(2), N, Info))
8035 return false;
8036 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8037
8038 // If the size is zero, we treat this as always being a valid no-op.
8039 // (Even if one of the src and dest pointers is null.)
8040 if (!N)
8041 return true;
8042
Richard Smith128719c2018-09-13 22:47:33 +00008043 // Otherwise, if either of the operands is null, we can't proceed. Don't
8044 // try to determine the type of the copied objects, because there aren't
8045 // any.
8046 if (!Src.Base || !Dest.Base) {
8047 APValue Val;
8048 (!Src.Base ? Src : Dest).moveInto(Val);
8049 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8050 << Move << WChar << !!Src.Base
8051 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8052 return false;
8053 }
8054 if (Src.Designator.Invalid || Dest.Designator.Invalid)
8055 return false;
8056
Richard Smith06f71b52018-08-04 00:57:17 +00008057 // We require that Src and Dest are both pointers to arrays of
8058 // trivially-copyable type. (For the wide version, the designator will be
8059 // invalid if the designated object is not a wchar_t.)
8060 QualType T = Dest.Designator.getType(Info.Ctx);
8061 QualType SrcT = Src.Designator.getType(Info.Ctx);
8062 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8063 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8064 return false;
8065 }
Petr Pavlued083f22018-10-04 09:25:44 +00008066 if (T->isIncompleteType()) {
8067 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8068 return false;
8069 }
Richard Smith06f71b52018-08-04 00:57:17 +00008070 if (!T.isTriviallyCopyableType(Info.Ctx)) {
8071 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8072 return false;
8073 }
8074
8075 // Figure out how many T's we're copying.
8076 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8077 if (!WChar) {
8078 uint64_t Remainder;
8079 llvm::APInt OrigN = N;
8080 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8081 if (Remainder) {
8082 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8083 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8084 << (unsigned)TSize;
8085 return false;
8086 }
8087 }
8088
8089 // Check that the copying will remain within the arrays, just so that we
8090 // can give a more meaningful diagnostic. This implicitly also checks that
8091 // N fits into 64 bits.
8092 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8093 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8094 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8095 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8096 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8097 << N.toString(10, /*Signed*/false);
8098 return false;
8099 }
8100 uint64_t NElems = N.getZExtValue();
8101 uint64_t NBytes = NElems * TSize;
8102
8103 // Check for overlap.
8104 int Direction = 1;
8105 if (HasSameBase(Src, Dest)) {
8106 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8107 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8108 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8109 // Dest is inside the source region.
8110 if (!Move) {
8111 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8112 return false;
8113 }
8114 // For memmove and friends, copy backwards.
8115 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8116 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8117 return false;
8118 Direction = -1;
8119 } else if (!Move && SrcOffset >= DestOffset &&
8120 SrcOffset - DestOffset < NBytes) {
8121 // Src is inside the destination region for memcpy: invalid.
8122 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8123 return false;
8124 }
8125 }
8126
8127 while (true) {
8128 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00008129 // FIXME: Set WantObjectRepresentation to true if we're copying a
8130 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00008131 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8132 !handleAssignment(Info, E, Dest, T, Val))
8133 return false;
8134 // Do not iterate past the last element; if we're copying backwards, that
8135 // might take us off the start of the array.
8136 if (--NElems == 0)
8137 return true;
8138 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8139 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8140 return false;
8141 }
8142 }
8143
Richard Smith6cbd65d2013-07-11 02:27:57 +00008144 default:
George Burgess IVe3763372016-12-22 02:50:20 +00008145 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00008146 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008147}
Chris Lattner05706e882008-07-11 18:11:29 +00008148
Richard Smithda1b4342019-09-27 01:26:47 +00008149static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8150 APValue &Result, const InitListExpr *ILE,
8151 QualType AllocType);
8152
8153bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
Richard Smith62a95562019-09-27 01:26:49 +00008154 if (!Info.getLangOpts().CPlusPlus2a)
8155 Info.CCEDiag(E, diag::note_constexpr_new);
8156
Richard Smithda1b4342019-09-27 01:26:47 +00008157 // We cannot speculatively evaluate a delete expression.
8158 if (Info.SpeculativeEvaluationDepth)
8159 return false;
8160
8161 FunctionDecl *OperatorNew = E->getOperatorNew();
8162 if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8163 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8164 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8165 return false;
8166 }
8167
Richard Smith62a95562019-09-27 01:26:49 +00008168 bool IsNothrow = false;
8169 if (E->getNumPlacementArgs()) {
8170 // The only new-placement list we support is of the form (std::nothrow).
8171 //
8172 // FIXME: There is no restriction on this, but it's not clear that any
8173 // other form makes any sense. We get here for cases such as:
8174 //
8175 // new (std::align_val_t{N}) X(int)
8176 //
8177 // (which should presumably be valid only if N is a multiple of
8178 // alignof(int), and in any case can't be deallocated unless N is
8179 // alignof(X) and X has new-extended alignment).
8180 if (E->getNumPlacementArgs() != 1 ||
8181 !E->getPlacementArg(0)->getType()->isNothrowT())
8182 return Error(E, diag::note_constexpr_new_placement);
8183
8184 LValue Nothrow;
8185 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8186 return false;
8187 IsNothrow = true;
8188 }
Richard Smithda1b4342019-09-27 01:26:47 +00008189
8190 const Expr *Init = E->getInitializer();
8191 const InitListExpr *ResizedArrayILE = nullptr;
8192
8193 QualType AllocType = E->getAllocatedType();
8194 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8195 const Expr *Stripped = *ArraySize;
8196 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8197 Stripped = ICE->getSubExpr())
8198 if (ICE->getCastKind() != CK_NoOp &&
8199 ICE->getCastKind() != CK_IntegralCast)
8200 break;
8201
8202 llvm::APSInt ArrayBound;
8203 if (!EvaluateInteger(Stripped, ArrayBound, Info))
8204 return false;
8205
8206 // C++ [expr.new]p9:
8207 // The expression is erroneous if:
8208 // -- [...] its value before converting to size_t [or] applying the
8209 // second standard conversion sequence is less than zero
8210 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
Richard Smith62a95562019-09-27 01:26:49 +00008211 if (IsNothrow)
8212 return ZeroInitialization(E);
8213
Richard Smithda1b4342019-09-27 01:26:47 +00008214 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8215 << ArrayBound << (*ArraySize)->getSourceRange();
8216 return false;
8217 }
8218
8219 // -- its value is such that the size of the allocated object would
8220 // exceed the implementation-defined limit
8221 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8222 ArrayBound) >
8223 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
Richard Smith62a95562019-09-27 01:26:49 +00008224 if (IsNothrow)
8225 return ZeroInitialization(E);
8226
Richard Smithda1b4342019-09-27 01:26:47 +00008227 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8228 << ArrayBound << (*ArraySize)->getSourceRange();
8229 return false;
8230 }
8231
8232 // -- the new-initializer is a braced-init-list and the number of
8233 // array elements for which initializers are provided [...]
8234 // exceeds the number of elements to initialize
8235 if (Init) {
8236 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8237 assert(CAT && "unexpected type for array initializer");
8238
8239 unsigned Bits =
8240 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8241 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8242 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8243 if (InitBound.ugt(AllocBound)) {
Richard Smith62a95562019-09-27 01:26:49 +00008244 if (IsNothrow)
8245 return ZeroInitialization(E);
8246
Richard Smithda1b4342019-09-27 01:26:47 +00008247 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8248 << AllocBound.toString(10, /*Signed=*/false)
8249 << InitBound.toString(10, /*Signed=*/false)
8250 << (*ArraySize)->getSourceRange();
8251 return false;
8252 }
8253
8254 // If the sizes differ, we must have an initializer list, and we need
8255 // special handling for this case when we initialize.
8256 if (InitBound != AllocBound)
8257 ResizedArrayILE = cast<InitListExpr>(Init);
8258 }
8259
8260 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound,
8261 ArrayType::Normal, 0);
8262 } else {
8263 assert(!AllocType->isArrayType() &&
8264 "array allocation with non-array new");
8265 }
8266
8267 // Perform the allocation and obtain a pointer to the resulting object.
8268 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
8269 if (!Val)
8270 return false;
8271
8272 if (ResizedArrayILE) {
8273 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8274 AllocType))
8275 return false;
8276 } else if (Init) {
8277 if (!EvaluateInPlace(*Val, Info, Result, Init))
8278 return false;
8279 } else {
8280 *Val = getDefaultInitValue(AllocType);
8281 }
8282
8283 // Array new returns a pointer to the first element, not a pointer to the
8284 // array.
8285 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8286 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8287
8288 return true;
8289}
Chris Lattner05706e882008-07-11 18:11:29 +00008290//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008291// Member Pointer Evaluation
8292//===----------------------------------------------------------------------===//
8293
8294namespace {
8295class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008296 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00008297 MemberPtr &Result;
8298
8299 bool Success(const ValueDecl *D) {
8300 Result = MemberPtr(D);
8301 return true;
8302 }
8303public:
8304
8305 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8306 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8307
Richard Smith2e312c82012-03-03 22:46:17 +00008308 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008309 Result.setFrom(V);
8310 return true;
8311 }
Richard Smithfddd3842011-12-30 21:15:51 +00008312 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00008313 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00008314 }
8315
8316 bool VisitCastExpr(const CastExpr *E);
8317 bool VisitUnaryAddrOf(const UnaryOperator *E);
8318};
8319} // end anonymous namespace
8320
8321static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8322 EvalInfo &Info) {
8323 assert(E->isRValue() && E->getType()->isMemberPointerType());
8324 return MemberPointerExprEvaluator(Info, Result).Visit(E);
8325}
8326
8327bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8328 switch (E->getCastKind()) {
8329 default:
8330 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8331
8332 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00008333 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008334 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00008335
8336 case CK_BaseToDerivedMemberPointer: {
8337 if (!Visit(E->getSubExpr()))
8338 return false;
8339 if (E->path_empty())
8340 return true;
8341 // Base-to-derived member pointer casts store the path in derived-to-base
8342 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8343 // the wrong end of the derived->base arc, so stagger the path by one class.
8344 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8345 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8346 PathI != PathE; ++PathI) {
8347 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8348 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8349 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008350 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008351 }
8352 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8353 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008354 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008355 return true;
8356 }
8357
8358 case CK_DerivedToBaseMemberPointer:
8359 if (!Visit(E->getSubExpr()))
8360 return false;
8361 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8362 PathE = E->path_end(); PathI != PathE; ++PathI) {
8363 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8364 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8365 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008366 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008367 }
8368 return true;
8369 }
8370}
8371
8372bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8373 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8374 // member can be formed.
8375 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8376}
8377
8378//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00008379// Record Evaluation
8380//===----------------------------------------------------------------------===//
8381
8382namespace {
8383 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008384 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008385 const LValue &This;
8386 APValue &Result;
8387 public:
8388
8389 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8390 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8391
Richard Smith2e312c82012-03-03 22:46:17 +00008392 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00008393 Result = V;
8394 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00008395 }
Richard Smithb8348f52016-05-12 22:16:28 +00008396 bool ZeroInitialization(const Expr *E) {
8397 return ZeroInitialization(E, E->getType());
8398 }
8399 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00008400
Richard Smith52a980a2015-08-28 02:43:42 +00008401 bool VisitCallExpr(const CallExpr *E) {
8402 return handleCallExpr(E, Result, &This);
8403 }
Richard Smithe97cbd72011-11-11 04:05:33 +00008404 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008405 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008406 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8407 return VisitCXXConstructExpr(E, E->getType());
8408 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008409 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00008410 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008411 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00008412 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008413
Richard Smith457226e2019-09-23 03:48:44 +00008414 // Temporaries are registered when created, so we don't care about
8415 // CXXBindTemporaryExpr.
8416 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8417 return Visit(E->getSubExpr());
8418 }
8419
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008420 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008421 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008422}
Richard Smithd62306a2011-11-10 06:34:14 +00008423
Richard Smithfddd3842011-12-30 21:15:51 +00008424/// Perform zero-initialization on an object of non-union class type.
8425/// C++11 [dcl.init]p5:
8426/// To zero-initialize an object or reference of type T means:
8427/// [...]
8428/// -- if T is a (possibly cv-qualified) non-union class type,
8429/// each non-static data member and each base-class subobject is
8430/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00008431static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8432 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00008433 const LValue &This, APValue &Result) {
8434 assert(!RD->isUnion() && "Expected non-union class type");
8435 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8436 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00008437 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00008438
John McCalld7bca762012-05-01 00:38:49 +00008439 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008440 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8441
8442 if (CD) {
8443 unsigned Index = 0;
8444 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00008445 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00008446 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8447 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008448 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8449 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00008450 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00008451 Result.getStructBase(Index)))
8452 return false;
8453 }
8454 }
8455
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008456 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00008457 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00008458 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00008459 continue;
8460
8461 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008462 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008463 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008464
David Blaikie2d7c57e2012-04-30 02:36:29 +00008465 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008466 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00008467 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00008468 return false;
8469 }
8470
8471 return true;
8472}
8473
Richard Smithb8348f52016-05-12 22:16:28 +00008474bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8475 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008476 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008477 if (RD->isUnion()) {
8478 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8479 // object's first non-static named data member is zero-initialized
8480 RecordDecl::field_iterator I = RD->field_begin();
8481 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00008482 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00008483 return true;
8484 }
8485
8486 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00008487 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00008488 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00008489 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00008490 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008491 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00008492 }
8493
Richard Smith5d108602012-02-17 00:44:16 +00008494 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008495 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00008496 return false;
8497 }
8498
Richard Smitha8105bc2012-01-06 16:39:00 +00008499 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00008500}
8501
Richard Smithe97cbd72011-11-11 04:05:33 +00008502bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8503 switch (E->getCastKind()) {
8504 default:
8505 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8506
8507 case CK_ConstructorConversion:
8508 return Visit(E->getSubExpr());
8509
8510 case CK_DerivedToBase:
8511 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00008512 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008513 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00008514 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008515 if (!DerivedObject.isStruct())
8516 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00008517
8518 // Derived-to-base rvalue conversion: just slice off the derived part.
8519 APValue *Value = &DerivedObject;
8520 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8521 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8522 PathE = E->path_end(); PathI != PathE; ++PathI) {
8523 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
8524 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8525 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8526 RD = Base;
8527 }
8528 Result = *Value;
8529 return true;
8530 }
8531 }
8532}
8533
Richard Smithd62306a2011-11-10 06:34:14 +00008534bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00008535 if (E->isTransparent())
8536 return Visit(E->getInit(0));
8537
Richard Smithd62306a2011-11-10 06:34:14 +00008538 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008539 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008540 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008541 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8542
8543 EvalInfo::EvaluatingConstructorRAII EvalObj(
8544 Info,
8545 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8546 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00008547
8548 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00008549 const FieldDecl *Field = E->getInitializedFieldInUnion();
8550 Result = APValue(Field);
8551 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00008552 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00008553
8554 // If the initializer list for a union does not contain any elements, the
8555 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00008556 // FIXME: The element should be initialized from an initializer list.
8557 // Is this difference ever observable for initializer lists which
8558 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00008559 ImplicitValueInitExpr VIE(Field->getType());
8560 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8561
Richard Smithd62306a2011-11-10 06:34:14 +00008562 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008563 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8564 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00008565
8566 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8567 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8568 isa<CXXDefaultInitExpr>(InitExpr));
8569
Richard Smithb228a862012-02-15 02:18:13 +00008570 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00008571 }
8572
Richard Smithe637cbe2019-05-21 23:15:18 +00008573 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00008574 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8575 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00008576 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00008577 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00008578
8579 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008580 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00008581 for (const auto &Base : CXXRD->bases()) {
8582 assert(ElementNo < E->getNumInits() && "missing init for base class");
8583 const Expr *Init = E->getInit(ElementNo);
8584
8585 LValue Subobject = This;
8586 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8587 return false;
8588
8589 APValue &FieldVal = Result.getStructBase(ElementNo);
8590 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008591 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00008592 return false;
8593 Success = false;
8594 }
8595 ++ElementNo;
8596 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008597
8598 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00008599 }
8600
8601 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008602 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008603 // Anonymous bit-fields are not considered members of the class for
8604 // purposes of aggregate initialization.
8605 if (Field->isUnnamedBitfield())
8606 continue;
8607
8608 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00008609
Richard Smith253c2a32012-01-27 01:14:48 +00008610 bool HaveInit = ElementNo < E->getNumInits();
8611
8612 // FIXME: Diagnostics here should point to the end of the initializer
8613 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00008614 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008615 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008616 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008617
8618 // Perform an implicit value-initialization for members beyond the end of
8619 // the initializer list.
8620 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00008621 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00008622
Richard Smith852c9db2013-04-20 22:23:05 +00008623 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8624 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8625 isa<CXXDefaultInitExpr>(Init));
8626
Richard Smith49ca8aa2013-08-06 07:09:20 +00008627 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8628 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8629 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008630 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00008631 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00008632 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008633 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00008634 }
8635 }
8636
Richard Smith253c2a32012-01-27 01:14:48 +00008637 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00008638}
8639
Richard Smithb8348f52016-05-12 22:16:28 +00008640bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8641 QualType T) {
8642 // Note that E's type is not necessarily the type of our class here; we might
8643 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00008644 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00008645 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8646
Richard Smithfddd3842011-12-30 21:15:51 +00008647 bool ZeroInit = E->requiresZeroInitialization();
8648 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00008649 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00008650 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00008651 return true;
8652
Richard Smithc667cdc2019-09-18 17:37:44 +00008653 if (ZeroInit)
8654 return ZeroInitialization(E, T);
8655
8656 Result = getDefaultInitValue(T);
8657 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00008658 }
8659
Craig Topper36250ad2014-05-12 05:36:57 +00008660 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008661 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00008662
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008663 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00008664 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008665
Richard Smith1bc5c2c2012-01-10 04:32:03 +00008666 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00008667 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00008668 if (const MaterializeTemporaryExpr *ME
8669 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8670 return Visit(ME->GetTemporaryExpr());
8671
Richard Smithb8348f52016-05-12 22:16:28 +00008672 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00008673 return false;
8674
Craig Topper5fc8fc22014-08-27 06:28:36 +00008675 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00008676 return HandleConstructorCall(E, This, Args,
8677 cast<CXXConstructorDecl>(Definition), Info,
8678 Result);
8679}
8680
8681bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8682 const CXXInheritedCtorInitExpr *E) {
8683 if (!Info.CurrentCall) {
8684 assert(Info.checkingPotentialConstantExpression());
8685 return false;
8686 }
8687
8688 const CXXConstructorDecl *FD = E->getConstructor();
8689 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8690 return false;
8691
8692 const FunctionDecl *Definition = nullptr;
8693 auto Body = FD->getBody(Definition);
8694
8695 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8696 return false;
8697
8698 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008699 cast<CXXConstructorDecl>(Definition), Info,
8700 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00008701}
8702
Richard Smithcc1b96d2013-06-12 22:31:48 +00008703bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8704 const CXXStdInitializerListExpr *E) {
8705 const ConstantArrayType *ArrayType =
8706 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8707
8708 LValue Array;
8709 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8710 return false;
8711
8712 // Get a pointer to the first element of the array.
8713 Array.addArray(Info, E, ArrayType);
8714
8715 // FIXME: Perform the checks on the field types in SemaInit.
8716 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8717 RecordDecl::field_iterator Field = Record->field_begin();
8718 if (Field == Record->field_end())
8719 return Error(E);
8720
8721 // Start pointer.
8722 if (!Field->getType()->isPointerType() ||
8723 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8724 ArrayType->getElementType()))
8725 return Error(E);
8726
8727 // FIXME: What if the initializer_list type has base classes, etc?
8728 Result = APValue(APValue::UninitStruct(), 0, 2);
8729 Array.moveInto(Result.getStructField(0));
8730
8731 if (++Field == Record->field_end())
8732 return Error(E);
8733
8734 if (Field->getType()->isPointerType() &&
8735 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8736 ArrayType->getElementType())) {
8737 // End pointer.
8738 if (!HandleLValueArrayAdjustment(Info, E, Array,
8739 ArrayType->getElementType(),
8740 ArrayType->getSize().getZExtValue()))
8741 return false;
8742 Array.moveInto(Result.getStructField(1));
8743 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8744 // Length.
8745 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8746 else
8747 return Error(E);
8748
8749 if (++Field != Record->field_end())
8750 return Error(E);
8751
8752 return true;
8753}
8754
Faisal Valic72a08c2017-01-09 03:02:53 +00008755bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8756 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
Richard Smithda1b4342019-09-27 01:26:47 +00008757 if (ClosureClass->isInvalidDecl())
8758 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008759
Faisal Vali051e3a22017-02-16 04:12:21 +00008760 const size_t NumFields =
8761 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00008762
8763 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8764 E->capture_init_end()) &&
8765 "The number of lambda capture initializers should equal the number of "
8766 "fields within the closure type");
8767
Faisal Vali051e3a22017-02-16 04:12:21 +00008768 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8769 // Iterate through all the lambda's closure object's fields and initialize
8770 // them.
8771 auto *CaptureInitIt = E->capture_init_begin();
8772 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8773 bool Success = true;
8774 for (const auto *Field : ClosureClass->fields()) {
8775 assert(CaptureInitIt != E->capture_init_end());
8776 // Get the initializer for this field
8777 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00008778
Faisal Vali051e3a22017-02-16 04:12:21 +00008779 // If there is no initializer, either this is a VLA or an error has
8780 // occurred.
8781 if (!CurFieldInit)
8782 return Error(E);
8783
8784 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8785 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8786 if (!Info.keepEvaluatingAfterFailure())
8787 return false;
8788 Success = false;
8789 }
8790 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00008791 }
Faisal Vali051e3a22017-02-16 04:12:21 +00008792 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00008793}
8794
Richard Smithd62306a2011-11-10 06:34:14 +00008795static bool EvaluateRecord(const Expr *E, const LValue &This,
8796 APValue &Result, EvalInfo &Info) {
8797 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00008798 "can't evaluate expression as a record rvalue");
8799 return RecordExprEvaluator(Info, This, Result).Visit(E);
8800}
8801
8802//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008803// Temporary Evaluation
8804//
8805// Temporaries are represented in the AST as rvalues, but generally behave like
8806// lvalues. The full-object of which the temporary is a subobject is implicitly
8807// materialized so that a reference can bind to it.
8808//===----------------------------------------------------------------------===//
8809namespace {
8810class TemporaryExprEvaluator
8811 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8812public:
8813 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00008814 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00008815
8816 /// Visit an expression which constructs the value of this temporary.
8817 bool VisitConstructExpr(const Expr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00008818 APValue &Value =
8819 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008820 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00008821 }
8822
8823 bool VisitCastExpr(const CastExpr *E) {
8824 switch (E->getCastKind()) {
8825 default:
8826 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8827
8828 case CK_ConstructorConversion:
8829 return VisitConstructExpr(E->getSubExpr());
8830 }
8831 }
8832 bool VisitInitListExpr(const InitListExpr *E) {
8833 return VisitConstructExpr(E);
8834 }
8835 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8836 return VisitConstructExpr(E);
8837 }
8838 bool VisitCallExpr(const CallExpr *E) {
8839 return VisitConstructExpr(E);
8840 }
Richard Smith513955c2014-12-17 19:24:30 +00008841 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8842 return VisitConstructExpr(E);
8843 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008844 bool VisitLambdaExpr(const LambdaExpr *E) {
8845 return VisitConstructExpr(E);
8846 }
Richard Smith027bf112011-11-17 22:56:20 +00008847};
8848} // end anonymous namespace
8849
8850/// Evaluate an expression of record type as a temporary.
8851static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00008852 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00008853 return TemporaryExprEvaluator(Info, Result).Visit(E);
8854}
8855
8856//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008857// Vector Evaluation
8858//===----------------------------------------------------------------------===//
8859
8860namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008861 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008862 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00008863 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008864 public:
Mike Stump11289f42009-09-09 15:08:12 +00008865
Richard Smith2d406342011-10-22 21:10:00 +00008866 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8867 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00008868
Craig Topper9798b932015-09-29 04:30:05 +00008869 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008870 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8871 // FIXME: remove this APValue copy.
8872 Result = APValue(V.data(), V.size());
8873 return true;
8874 }
Richard Smith2e312c82012-03-03 22:46:17 +00008875 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00008876 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00008877 Result = V;
8878 return true;
8879 }
Richard Smithfddd3842011-12-30 21:15:51 +00008880 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00008881
Richard Smith2d406342011-10-22 21:10:00 +00008882 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00008883 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00008884 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00008885 bool VisitInitListExpr(const InitListExpr *E);
8886 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008887 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00008888 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00008889 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008890 };
8891} // end anonymous namespace
8892
8893static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008894 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00008895 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008896}
8897
George Burgess IV533ff002015-12-11 00:23:35 +00008898bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008899 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008900 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008901
Richard Smith161f09a2011-12-06 22:44:34 +00008902 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00008903 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008904
Eli Friedmanc757de22011-03-25 00:43:55 +00008905 switch (E->getCastKind()) {
8906 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00008907 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00008908 if (SETy->isIntegerType()) {
8909 APSInt IntResult;
8910 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00008911 return false;
8912 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008913 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00008914 APFloat FloatResult(0.0);
8915 if (!EvaluateFloat(SE, FloatResult, Info))
8916 return false;
8917 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008918 } else {
Richard Smith2d406342011-10-22 21:10:00 +00008919 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008920 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008921
8922 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00008923 SmallVector<APValue, 4> Elts(NElts, Val);
8924 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00008925 }
Eli Friedman803acb32011-12-22 03:51:45 +00008926 case CK_BitCast: {
8927 // Evaluate the operand into an APInt we can extract from.
8928 llvm::APInt SValInt;
8929 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8930 return false;
8931 // Extract the elements
8932 QualType EltTy = VTy->getElementType();
8933 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8934 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8935 SmallVector<APValue, 4> Elts;
8936 if (EltTy->isRealFloatingType()) {
8937 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00008938 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00008939 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00008940 FloatEltSize = 80;
8941 for (unsigned i = 0; i < NElts; i++) {
8942 llvm::APInt Elt;
8943 if (BigEndian)
8944 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8945 else
8946 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00008947 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00008948 }
8949 } else if (EltTy->isIntegerType()) {
8950 for (unsigned i = 0; i < NElts; i++) {
8951 llvm::APInt Elt;
8952 if (BigEndian)
8953 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8954 else
8955 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8956 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8957 }
8958 } else {
8959 return Error(E);
8960 }
8961 return Success(Elts, E);
8962 }
Eli Friedmanc757de22011-03-25 00:43:55 +00008963 default:
Richard Smith11562c52011-10-28 17:51:58 +00008964 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008965 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008966}
8967
Richard Smith2d406342011-10-22 21:10:00 +00008968bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008969VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008970 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008971 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00008972 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008973
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008974 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008975 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008976
Eli Friedmanb9c71292012-01-03 23:24:20 +00008977 // The number of initializers can be less than the number of
8978 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00008979 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00008980 // should be initialized with zeroes.
8981 unsigned CountInits = 0, CountElts = 0;
8982 while (CountElts < NumElements) {
8983 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00008984 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00008985 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00008986 APValue v;
8987 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8988 return Error(E);
8989 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00008990 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00008991 Elements.push_back(v.getVectorElt(j));
8992 CountElts += vlen;
8993 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008994 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008995 if (CountInits < NumInits) {
8996 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008997 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008998 } else // trailing integer zero.
8999 sInt = Info.Ctx.MakeIntValue(0, EltTy);
9000 Elements.push_back(APValue(sInt));
9001 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009002 } else {
9003 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009004 if (CountInits < NumInits) {
9005 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009006 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009007 } else // trailing float zero.
9008 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9009 Elements.push_back(APValue(f));
9010 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00009011 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00009012 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009013 }
Richard Smith2d406342011-10-22 21:10:00 +00009014 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009015}
9016
Richard Smith2d406342011-10-22 21:10:00 +00009017bool
Richard Smithfddd3842011-12-30 21:15:51 +00009018VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009019 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00009020 QualType EltTy = VT->getElementType();
9021 APValue ZeroElement;
9022 if (EltTy->isIntegerType())
9023 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9024 else
9025 ZeroElement =
9026 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9027
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009028 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00009029 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009030}
9031
Richard Smith2d406342011-10-22 21:10:00 +00009032bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00009033 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00009034 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009035}
9036
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009037//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00009038// Array Evaluation
9039//===----------------------------------------------------------------------===//
9040
9041namespace {
9042 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009043 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00009044 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00009045 APValue &Result;
9046 public:
9047
Richard Smithd62306a2011-11-10 06:34:14 +00009048 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9049 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00009050
9051 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00009052 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00009053 Result = V;
9054 return true;
9055 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009056
Richard Smithfddd3842011-12-30 21:15:51 +00009057 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00009058 const ConstantArrayType *CAT =
9059 Info.Ctx.getAsConstantArrayType(E->getType());
9060 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009061 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00009062
9063 Result = APValue(APValue::UninitArray(), 0,
9064 CAT->getSize().getZExtValue());
9065 if (!Result.hasArrayFiller()) return true;
9066
Richard Smithfddd3842011-12-30 21:15:51 +00009067 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00009068 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009069 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00009070 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00009071 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00009072 }
9073
Richard Smith52a980a2015-08-28 02:43:42 +00009074 bool VisitCallExpr(const CallExpr *E) {
9075 return handleCallExpr(E, Result, &This);
9076 }
Richard Smithda1b4342019-09-27 01:26:47 +00009077 bool VisitInitListExpr(const InitListExpr *E,
9078 QualType AllocType = QualType());
Richard Smith410306b2016-12-12 02:53:20 +00009079 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00009080 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00009081 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9082 const LValue &Subobject,
9083 APValue *Value, QualType Type);
Richard Smithda1b4342019-09-27 01:26:47 +00009084 bool VisitStringLiteral(const StringLiteral *E,
9085 QualType AllocType = QualType()) {
9086 expandStringLiteral(Info, E, Result, AllocType);
Eli Friedman3bf72d72019-02-08 21:18:46 +00009087 return true;
9088 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009089 };
9090} // end anonymous namespace
9091
Richard Smithd62306a2011-11-10 06:34:14 +00009092static bool EvaluateArray(const Expr *E, const LValue &This,
9093 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00009094 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00009095 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009096}
9097
Richard Smithda1b4342019-09-27 01:26:47 +00009098static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9099 APValue &Result, const InitListExpr *ILE,
9100 QualType AllocType) {
9101 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9102 "not an array rvalue");
9103 return ArrayExprEvaluator(Info, This, Result)
9104 .VisitInitListExpr(ILE, AllocType);
9105}
9106
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009107// Return true iff the given array filler may depend on the element index.
9108static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9109 // For now, just whitelist non-class value-initialization and initialization
9110 // lists comprised of them.
9111 if (isa<ImplicitValueInitExpr>(FillerExpr))
9112 return false;
9113 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9114 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9115 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9116 return true;
9117 }
9118 return false;
9119 }
9120 return true;
9121}
9122
Richard Smithda1b4342019-09-27 01:26:47 +00009123bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9124 QualType AllocType) {
9125 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9126 AllocType.isNull() ? E->getType() : AllocType);
Richard Smithf3e9e432011-11-07 09:22:26 +00009127 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009128 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009129
Richard Smithca2cfbf2011-12-22 01:07:19 +00009130 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9131 // an appropriately-typed string literal enclosed in braces.
Richard Smithda1b4342019-09-27 01:26:47 +00009132 if (E->isStringLiteralInit()) {
9133 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9134 // FIXME: Support ObjCEncodeExpr here once we support it in
9135 // ArrayExprEvaluator generally.
9136 if (!SL)
9137 return Error(E);
9138 return VisitStringLiteral(SL, AllocType);
9139 }
Richard Smithca2cfbf2011-12-22 01:07:19 +00009140
Richard Smith253c2a32012-01-27 01:14:48 +00009141 bool Success = true;
9142
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009143 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9144 "zero-initialized array shouldn't have any initialized elts");
9145 APValue Filler;
9146 if (Result.isArray() && Result.hasArrayFiller())
9147 Filler = Result.getArrayFiller();
9148
Richard Smith9543c5e2013-04-22 14:44:29 +00009149 unsigned NumEltsToInit = E->getNumInits();
9150 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00009151 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00009152
9153 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009154 // array element.
9155 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00009156 NumEltsToInit = NumElts;
9157
Nicola Zaghen3538b392018-05-15 13:30:56 +00009158 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9159 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009160
Richard Smith9543c5e2013-04-22 14:44:29 +00009161 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009162
9163 // If the array was previously zero-initialized, preserve the
9164 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00009165 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009166 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9167 Result.getArrayInitializedElt(I) = Filler;
9168 if (Result.hasArrayFiller())
9169 Result.getArrayFiller() = Filler;
9170 }
9171
Richard Smithd62306a2011-11-10 06:34:14 +00009172 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009173 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00009174 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9175 const Expr *Init =
9176 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00009177 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00009178 Info, Subobject, Init) ||
9179 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00009180 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00009181 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00009182 return false;
9183 Success = false;
9184 }
Richard Smithd62306a2011-11-10 06:34:14 +00009185 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009186
Richard Smith9543c5e2013-04-22 14:44:29 +00009187 if (!Result.hasArrayFiller())
9188 return Success;
9189
9190 // If we get here, we have a trivial filler, which we can just evaluate
9191 // once and splat over the rest of the array elements.
9192 assert(FillerExpr && "no array filler for incomplete init list");
9193 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9194 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00009195}
9196
Richard Smith410306b2016-12-12 02:53:20 +00009197bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009198 LValue CommonLV;
Richard Smith410306b2016-12-12 02:53:20 +00009199 if (E->getCommonExpr() &&
Richard Smith457226e2019-09-23 03:48:44 +00009200 !Evaluate(Info.CurrentCall->createTemporary(
9201 E->getCommonExpr(),
9202 getStorageType(Info.Ctx, E->getCommonExpr()), false,
9203 CommonLV),
Richard Smith410306b2016-12-12 02:53:20 +00009204 Info, E->getCommonExpr()->getSourceExpr()))
9205 return false;
9206
9207 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9208
9209 uint64_t Elements = CAT->getSize().getZExtValue();
9210 Result = APValue(APValue::UninitArray(), Elements, Elements);
9211
9212 LValue Subobject = This;
9213 Subobject.addArray(Info, E, CAT);
9214
9215 bool Success = true;
9216 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9217 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9218 Info, Subobject, E->getSubExpr()) ||
9219 !HandleLValueArrayAdjustment(Info, E, Subobject,
9220 CAT->getElementType(), 1)) {
9221 if (!Info.noteFailure())
9222 return false;
9223 Success = false;
9224 }
9225 }
9226
9227 return Success;
9228}
9229
Richard Smith027bf112011-11-17 22:56:20 +00009230bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00009231 return VisitCXXConstructExpr(E, This, &Result, E->getType());
9232}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009233
Richard Smith9543c5e2013-04-22 14:44:29 +00009234bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9235 const LValue &Subobject,
9236 APValue *Value,
9237 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00009238 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00009239
9240 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9241 unsigned N = CAT->getSize().getZExtValue();
9242
9243 // Preserve the array filler if we had prior zero-initialization.
9244 APValue Filler =
9245 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9246 : APValue();
9247
9248 *Value = APValue(APValue::UninitArray(), N, N);
9249
9250 if (HadZeroInit)
9251 for (unsigned I = 0; I != N; ++I)
9252 Value->getArrayInitializedElt(I) = Filler;
9253
9254 // Initialize the elements.
9255 LValue ArrayElt = Subobject;
9256 ArrayElt.addArray(Info, E, CAT);
9257 for (unsigned I = 0; I != N; ++I)
9258 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9259 CAT->getElementType()) ||
9260 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9261 CAT->getElementType(), 1))
9262 return false;
9263
9264 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009265 }
Richard Smith027bf112011-11-17 22:56:20 +00009266
Richard Smith9543c5e2013-04-22 14:44:29 +00009267 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00009268 return Error(E);
9269
Richard Smithb8348f52016-05-12 22:16:28 +00009270 return RecordExprEvaluator(Info, Subobject, *Value)
9271 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00009272}
9273
Richard Smithf3e9e432011-11-07 09:22:26 +00009274//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009275// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00009276//
9277// As a GNU extension, we support casting pointers to sufficiently-wide integer
9278// types and back in constant folding. Integer values are thus represented
9279// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00009280//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009281
9282namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009283class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009284 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00009285 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009286public:
Richard Smith2e312c82012-03-03 22:46:17 +00009287 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009288 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00009289
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009290 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009291 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009292 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009293 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009294 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009295 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009296 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009297 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009298 return true;
9299 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009300 bool Success(const llvm::APSInt &SI, const Expr *E) {
9301 return Success(SI, E, Result);
9302 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009303
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009304 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00009305 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009306 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009307 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009308 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009309 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009310 Result.getInt().setIsUnsigned(
9311 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009312 return true;
9313 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009314 bool Success(const llvm::APInt &I, const Expr *E) {
9315 return Success(I, E, Result);
9316 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009317
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009318 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009319 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009320 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009321 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009322 return true;
9323 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009324 bool Success(uint64_t Value, const Expr *E) {
9325 return Success(Value, E, Result);
9326 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009327
Ken Dyckdbc01912011-03-11 02:13:43 +00009328 bool Success(CharUnits Size, const Expr *E) {
9329 return Success(Size.getQuantity(), E);
9330 }
9331
Richard Smith2e312c82012-03-03 22:46:17 +00009332 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00009333 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00009334 Result = V;
9335 return true;
9336 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009337 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00009338 }
Mike Stump11289f42009-09-09 15:08:12 +00009339
Richard Smithfddd3842011-12-30 21:15:51 +00009340 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00009341
Peter Collingbournee9200682011-05-13 03:29:01 +00009342 //===--------------------------------------------------------------------===//
9343 // Visitor Methods
9344 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009345
Fangrui Song407659a2018-11-30 23:41:18 +00009346 bool VisitConstantExpr(const ConstantExpr *E);
9347
Chris Lattner7174bf32008-07-12 00:38:25 +00009348 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009349 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009350 }
9351 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009352 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009353 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009354
9355 bool CheckReferencedDecl(const Expr *E, const Decl *D);
9356 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009357 if (CheckReferencedDecl(E, E->getDecl()))
9358 return true;
9359
9360 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009361 }
9362 bool VisitMemberExpr(const MemberExpr *E) {
9363 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00009364 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009365 return true;
9366 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009367
9368 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009369 }
9370
Peter Collingbournee9200682011-05-13 03:29:01 +00009371 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00009372 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00009373 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00009374 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00009375 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00009376
Peter Collingbournee9200682011-05-13 03:29:01 +00009377 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009378 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00009379
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009380 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009381 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009382 }
Mike Stump11289f42009-09-09 15:08:12 +00009383
Ted Kremeneke65b0862012-03-06 20:05:56 +00009384 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9385 return Success(E->getValue(), E);
9386 }
Richard Smith410306b2016-12-12 02:53:20 +00009387
9388 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9389 if (Info.ArrayInitIndex == uint64_t(-1)) {
9390 // We were asked to evaluate this subexpression independent of the
9391 // enclosing ArrayInitLoopExpr. We can't do that.
9392 Info.FFDiag(E);
9393 return false;
9394 }
9395 return Success(Info.ArrayInitIndex, E);
9396 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009397
Richard Smith4ce706a2011-10-11 21:43:33 +00009398 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00009399 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00009400 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009401 }
9402
Douglas Gregor29c42f22012-02-24 07:38:34 +00009403 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9404 return Success(E->getValue(), E);
9405 }
9406
John Wiegley6242b6a2011-04-28 00:16:57 +00009407 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9408 return Success(E->getValue(), E);
9409 }
9410
John Wiegleyf9f65842011-04-25 06:54:41 +00009411 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9412 return Success(E->getValue(), E);
9413 }
9414
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009415 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009416 bool VisitUnaryImag(const UnaryOperator *E);
9417
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009418 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009419 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00009420 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009421 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00009422};
Leonard Chandb01c3a2018-06-20 17:19:40 +00009423
9424class FixedPointExprEvaluator
9425 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9426 APValue &Result;
9427
9428 public:
9429 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9430 : ExprEvaluatorBaseTy(info), Result(result) {}
9431
Leonard Chandb01c3a2018-06-20 17:19:40 +00009432 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009433 return Success(
9434 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009435 }
9436
Leonard Chandb01c3a2018-06-20 17:19:40 +00009437 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009438 return Success(
9439 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009440 }
9441
9442 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009443 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009444 }
9445
Leonard Chand3f3e162019-01-18 21:04:25 +00009446 bool Success(const APFixedPoint &V, const Expr *E) {
9447 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9448 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9449 "Invalid evaluation result.");
9450 Result = APValue(V);
9451 return true;
9452 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00009453
9454 //===--------------------------------------------------------------------===//
9455 // Visitor Methods
9456 //===--------------------------------------------------------------------===//
9457
9458 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9459 return Success(E->getValue(), E);
9460 }
9461
Leonard Chand3f3e162019-01-18 21:04:25 +00009462 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009463 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00009464 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009465};
Chris Lattner05706e882008-07-11 18:11:29 +00009466} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009467
Richard Smith11562c52011-10-28 17:51:58 +00009468/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9469/// produce either the integer value or a pointer.
9470///
9471/// GCC has a heinous extension which folds casts between pointer types and
9472/// pointer-sized integral types. We support this by allowing the evaluation of
9473/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9474/// Some simple arithmetic on such values is supported (they are treated much
9475/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00009476static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00009477 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009478 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009479 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00009480}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009481
Richard Smithf57d8cb2011-12-09 22:58:01 +00009482static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00009483 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009484 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00009485 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009486 if (!Val.isInt()) {
9487 // FIXME: It would be better to produce the diagnostic for casting
9488 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00009489 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009490 return false;
9491 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009492 Result = Val.getInt();
9493 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009494}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009495
Eric Fiselier708afb52019-05-16 21:04:15 +00009496bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9497 APValue Evaluated = E->EvaluateInContext(
9498 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9499 return Success(Evaluated, E);
9500}
9501
Leonard Chand3f3e162019-01-18 21:04:25 +00009502static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9503 EvalInfo &Info) {
9504 if (E->getType()->isFixedPointType()) {
9505 APValue Val;
9506 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9507 return false;
9508 if (!Val.isFixedPoint())
9509 return false;
9510
9511 Result = Val.getFixedPoint();
9512 return true;
9513 }
9514 return false;
9515}
9516
9517static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9518 EvalInfo &Info) {
9519 if (E->getType()->isIntegerType()) {
9520 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9521 APSInt Val;
9522 if (!EvaluateInteger(E, Val, Info))
9523 return false;
9524 Result = APFixedPoint(Val, FXSema);
9525 return true;
9526 } else if (E->getType()->isFixedPointType()) {
9527 return EvaluateFixedPoint(E, Result, Info);
9528 }
9529 return false;
9530}
9531
Richard Smithf57d8cb2011-12-09 22:58:01 +00009532/// Check whether the given declaration can be directly converted to an integral
9533/// rvalue. If not, no diagnostic is produced; there are other things we can
9534/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009535bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00009536 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009537 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009538 // Check for signedness/width mismatches between E type and ECD value.
9539 bool SameSign = (ECD->getInitVal().isSigned()
9540 == E->getType()->isSignedIntegerOrEnumerationType());
9541 bool SameWidth = (ECD->getInitVal().getBitWidth()
9542 == Info.Ctx.getIntWidth(E->getType()));
9543 if (SameSign && SameWidth)
9544 return Success(ECD->getInitVal(), E);
9545 else {
9546 // Get rid of mismatch (otherwise Success assertions will fail)
9547 // by computing a new value matching the type of E.
9548 llvm::APSInt Val = ECD->getInitVal();
9549 if (!SameSign)
9550 Val.setIsSigned(!ECD->getInitVal().isSigned());
9551 if (!SameWidth)
9552 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9553 return Success(Val, E);
9554 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009555 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009556 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00009557}
9558
Richard Smith08b682b2018-05-23 21:18:00 +00009559/// Values returned by __builtin_classify_type, chosen to match the values
9560/// produced by GCC's builtin.
9561enum class GCCTypeClass {
9562 None = -1,
9563 Void = 0,
9564 Integer = 1,
9565 // GCC reserves 2 for character types, but instead classifies them as
9566 // integers.
9567 Enum = 3,
9568 Bool = 4,
9569 Pointer = 5,
9570 // GCC reserves 6 for references, but appears to never use it (because
9571 // expressions never have reference type, presumably).
9572 PointerToDataMember = 7,
9573 RealFloat = 8,
9574 Complex = 9,
9575 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9576 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9577 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9578 // uses 12 for that purpose, same as for a class or struct. Maybe it
9579 // internally implements a pointer to member as a struct? Who knows.
9580 PointerToMemberFunction = 12, // Not a bug, see above.
9581 ClassOrStruct = 12,
9582 Union = 13,
9583 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9584 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9585 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9586 // literals.
9587};
9588
Chris Lattner86ee2862008-10-06 06:40:35 +00009589/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9590/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00009591static GCCTypeClass
9592EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9593 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00009594
Richard Smith08b682b2018-05-23 21:18:00 +00009595 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009596 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9597
9598 switch (CanTy->getTypeClass()) {
9599#define TYPE(ID, BASE)
9600#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9601#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9602#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
9603#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00009604 case Type::Auto:
9605 case Type::DeducedTemplateSpecialization:
9606 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009607
9608 case Type::Builtin:
9609 switch (BT->getKind()) {
9610#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00009611#define SIGNED_TYPE(ID, SINGLETON_ID) \
9612 case BuiltinType::ID: return GCCTypeClass::Integer;
9613#define FLOATING_TYPE(ID, SINGLETON_ID) \
9614 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9615#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9616 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009617#include "clang/AST/BuiltinTypes.def"
9618 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00009619 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009620
9621 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00009622 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009623
Richard Smith08b682b2018-05-23 21:18:00 +00009624 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009625 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00009626 case BuiltinType::WChar_U:
9627 case BuiltinType::Char8:
9628 case BuiltinType::Char16:
9629 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009630 case BuiltinType::UShort:
9631 case BuiltinType::UInt:
9632 case BuiltinType::ULong:
9633 case BuiltinType::ULongLong:
9634 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00009635 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009636
Leonard Chanf921d852018-06-04 16:07:52 +00009637 case BuiltinType::UShortAccum:
9638 case BuiltinType::UAccum:
9639 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009640 case BuiltinType::UShortFract:
9641 case BuiltinType::UFract:
9642 case BuiltinType::ULongFract:
9643 case BuiltinType::SatUShortAccum:
9644 case BuiltinType::SatUAccum:
9645 case BuiltinType::SatULongAccum:
9646 case BuiltinType::SatUShortFract:
9647 case BuiltinType::SatUFract:
9648 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00009649 return GCCTypeClass::None;
9650
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009651 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009652
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009653 case BuiltinType::ObjCId:
9654 case BuiltinType::ObjCClass:
9655 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00009656#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9657 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00009658#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00009659#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9660 case BuiltinType::Id:
9661#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009662 case BuiltinType::OCLSampler:
9663 case BuiltinType::OCLEvent:
9664 case BuiltinType::OCLClkEvent:
9665 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009666 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00009667#define SVE_TYPE(Name, Id, SingletonId) \
9668 case BuiltinType::Id:
9669#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00009670 return GCCTypeClass::None;
9671
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009672 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00009673 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009674 };
Richard Smith08b682b2018-05-23 21:18:00 +00009675 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009676
9677 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00009678 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009679
9680 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009681 case Type::ConstantArray:
9682 case Type::VariableArray:
9683 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00009684 case Type::FunctionNoProto:
9685 case Type::FunctionProto:
9686 return GCCTypeClass::Pointer;
9687
9688 case Type::MemberPointer:
9689 return CanTy->isMemberDataPointerType()
9690 ? GCCTypeClass::PointerToDataMember
9691 : GCCTypeClass::PointerToMemberFunction;
9692
9693 case Type::Complex:
9694 return GCCTypeClass::Complex;
9695
9696 case Type::Record:
9697 return CanTy->isUnionType() ? GCCTypeClass::Union
9698 : GCCTypeClass::ClassOrStruct;
9699
9700 case Type::Atomic:
9701 // GCC classifies _Atomic T the same as T.
9702 return EvaluateBuiltinClassifyType(
9703 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009704
9705 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009706 case Type::Vector:
9707 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009708 case Type::ObjCObject:
9709 case Type::ObjCInterface:
9710 case Type::ObjCObjectPointer:
9711 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00009712 // GCC classifies vectors as None. We follow its lead and classify all
9713 // other types that don't fit into the regular classification the same way.
9714 return GCCTypeClass::None;
9715
9716 case Type::LValueReference:
9717 case Type::RValueReference:
9718 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009719 }
9720
Richard Smith08b682b2018-05-23 21:18:00 +00009721 llvm_unreachable("unexpected type class");
9722}
9723
9724/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9725/// as GCC.
9726static GCCTypeClass
9727EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9728 // If no argument was supplied, default to None. This isn't
9729 // ideal, however it is what gcc does.
9730 if (E->getNumArgs() == 0)
9731 return GCCTypeClass::None;
9732
9733 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9734 // being an ICE, but still folds it to a constant using the type of the first
9735 // argument.
9736 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00009737}
9738
Richard Smith5fab0c92011-12-28 19:48:30 +00009739/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00009740/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00009741///
Richard Smith31cfb312019-04-27 02:58:17 +00009742/// A pointer is only "constant" if it is null (or a pointer cast to integer)
9743/// or it points to the first character of a string literal.
9744static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9745 APValue::LValueBase Base = LV.getLValueBase();
9746 if (Base.isNull()) {
9747 // A null base is acceptable.
9748 return true;
9749 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9750 if (!isa<StringLiteral>(E))
9751 return false;
9752 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00009753 } else if (Base.is<TypeInfoLValue>()) {
9754 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9755 // evaluate to true.
9756 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00009757 } else {
9758 // Any other base is not constant enough for GCC.
9759 return false;
9760 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009761}
9762
9763/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9764/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00009765static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00009766 // This evaluation is not permitted to have side-effects, so evaluate it in
9767 // a speculative evaluation context.
9768 SpeculativeEvaluationRAII SpeculativeEval(Info);
9769
Richard Smith31cfb312019-04-27 02:58:17 +00009770 // Constant-folding is always enabled for the operand of __builtin_constant_p
9771 // (even when the enclosing evaluation context otherwise requires a strict
9772 // language-specific constant expression).
9773 FoldConstant Fold(Info, true);
9774
Richard Smith5fab0c92011-12-28 19:48:30 +00009775 QualType ArgType = Arg->getType();
9776
9777 // __builtin_constant_p always has one operand. The rules which gcc follows
9778 // are not precisely documented, but are as follows:
9779 //
9780 // - If the operand is of integral, floating, complex or enumeration type,
9781 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00009782 // - If the operand can be folded to a pointer to the first character
9783 // of a string literal (or such a pointer cast to an integral type)
9784 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00009785 //
9786 // Otherwise, it returns 0.
9787 //
9788 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00009789 // its support for this did not work prior to GCC 9 and is not yet well
9790 // understood.
9791 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9792 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9793 ArgType->isNullPtrType()) {
9794 APValue V;
9795 if (!::EvaluateAsRValue(Info, Arg, V)) {
9796 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00009797 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00009798 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009799
Richard Smith31cfb312019-04-27 02:58:17 +00009800 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00009801 if (V.getKind() == APValue::LValue)
9802 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00009803
9804 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00009805 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00009806 }
9807
9808 // Anything else isn't considered to be sufficiently constant.
9809 return false;
9810}
9811
John McCall95007602010-05-10 23:27:23 +00009812/// Retrieves the "underlying object type" of the given expression,
9813/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00009814static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00009815 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9816 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00009817 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00009818 } else if (const Expr *E = B.get<const Expr*>()) {
9819 if (isa<CompoundLiteralExpr>(E))
9820 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00009821 } else if (B.is<TypeInfoLValue>()) {
9822 return B.getTypeInfoType();
Richard Smithda1b4342019-09-27 01:26:47 +00009823 } else if (B.is<DynamicAllocLValue>()) {
9824 return B.getDynamicAllocType();
John McCall95007602010-05-10 23:27:23 +00009825 }
9826
9827 return QualType();
9828}
9829
George Burgess IV3a03fab2015-09-04 21:28:13 +00009830/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00009831/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00009832/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00009833/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9834///
9835/// Always returns an RValue with a pointer representation.
9836static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9837 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9838
9839 auto *NoParens = E->IgnoreParens();
9840 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00009841 if (Cast == nullptr)
9842 return NoParens;
9843
9844 // We only conservatively allow a few kinds of casts, because this code is
9845 // inherently a simple solution that seeks to support the common case.
9846 auto CastKind = Cast->getCastKind();
9847 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9848 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00009849 return NoParens;
9850
9851 auto *SubExpr = Cast->getSubExpr();
9852 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9853 return NoParens;
9854 return ignorePointerCastsAndParens(SubExpr);
9855}
9856
George Burgess IVa51c4072015-10-16 01:49:01 +00009857/// Checks to see if the given LValue's Designator is at the end of the LValue's
9858/// record layout. e.g.
9859/// struct { struct { int a, b; } fst, snd; } obj;
9860/// obj.fst // no
9861/// obj.snd // yes
9862/// obj.fst.a // no
9863/// obj.fst.b // no
9864/// obj.snd.a // no
9865/// obj.snd.b // yes
9866///
9867/// Please note: this function is specialized for how __builtin_object_size
9868/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00009869///
Richard Smith6f4f0f12017-10-20 22:56:25 +00009870/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9871/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00009872static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9873 assert(!LVal.Designator.Invalid);
9874
George Burgess IV4168d752016-06-27 19:40:41 +00009875 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9876 const RecordDecl *Parent = FD->getParent();
9877 Invalid = Parent->isInvalidDecl();
9878 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00009879 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00009880 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00009881 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9882 };
9883
9884 auto &Base = LVal.getLValueBase();
9885 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9886 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009887 bool Invalid;
9888 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9889 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009890 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009891 for (auto *FD : IFD->chain()) {
9892 bool Invalid;
9893 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9894 return Invalid;
9895 }
George Burgess IVa51c4072015-10-16 01:49:01 +00009896 }
9897 }
9898
George Burgess IVe3763372016-12-22 02:50:20 +00009899 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00009900 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00009901 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00009902 // If we don't know the array bound, conservatively assume we're looking at
9903 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00009904 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00009905 if (BaseType->isIncompleteArrayType())
9906 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9907 else
9908 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00009909 }
9910
9911 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9912 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00009913 if (BaseType->isArrayType()) {
9914 // Because __builtin_object_size treats arrays as objects, we can ignore
9915 // the index iff this is the last array in the Designator.
9916 if (I + 1 == E)
9917 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00009918 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00009919 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009920 if (Index + 1 != CAT->getSize())
9921 return false;
9922 BaseType = CAT->getElementType();
9923 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00009924 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009925 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009926 if (Index != 1)
9927 return false;
9928 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00009929 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00009930 bool Invalid;
9931 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9932 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009933 BaseType = FD->getType();
9934 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00009935 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00009936 return false;
9937 }
9938 }
9939 return true;
9940}
9941
George Burgess IVe3763372016-12-22 02:50:20 +00009942/// Tests to see if the LValue has a user-specified designator (that isn't
9943/// necessarily valid). Note that this always returns 'true' if the LValue has
9944/// an unsized array as its first designator entry, because there's currently no
9945/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00009946static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00009947 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00009948 return false;
9949
George Burgess IVe3763372016-12-22 02:50:20 +00009950 if (!LVal.Designator.Entries.empty())
9951 return LVal.Designator.isMostDerivedAnUnsizedArray();
9952
George Burgess IVa51c4072015-10-16 01:49:01 +00009953 if (!LVal.InvalidBase)
9954 return true;
9955
George Burgess IVe3763372016-12-22 02:50:20 +00009956 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9957 // the LValueBase.
9958 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9959 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00009960}
9961
George Burgess IVe3763372016-12-22 02:50:20 +00009962/// Attempts to detect a user writing into a piece of memory that's impossible
9963/// to figure out the size of by just using types.
9964static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9965 const SubobjectDesignator &Designator = LVal.Designator;
9966 // Notes:
9967 // - Users can only write off of the end when we have an invalid base. Invalid
9968 // bases imply we don't know where the memory came from.
9969 // - We used to be a bit more aggressive here; we'd only be conservative if
9970 // the array at the end was flexible, or if it had 0 or 1 elements. This
9971 // broke some common standard library extensions (PR30346), but was
9972 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9973 // with some sort of whitelist. OTOH, it seems that GCC is always
9974 // conservative with the last element in structs (if it's an array), so our
9975 // current behavior is more compatible than a whitelisting approach would
9976 // be.
9977 return LVal.InvalidBase &&
9978 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9979 Designator.MostDerivedIsArrayElement &&
9980 isDesignatorAtObjectEnd(Ctx, LVal);
9981}
9982
9983/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9984/// Fails if the conversion would cause loss of precision.
9985static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9986 CharUnits &Result) {
9987 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9988 if (Int.ugt(CharUnitsMax))
9989 return false;
9990 Result = CharUnits::fromQuantity(Int.getZExtValue());
9991 return true;
9992}
9993
9994/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9995/// determine how many bytes exist from the beginning of the object to either
9996/// the end of the current subobject, or the end of the object itself, depending
9997/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00009998///
George Burgess IVe3763372016-12-22 02:50:20 +00009999/// If this returns false, the value of Result is undefined.
10000static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10001 unsigned Type, const LValue &LVal,
10002 CharUnits &EndOffset) {
10003 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010004
George Burgess IV7fb7e362017-01-03 23:35:19 +000010005 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10006 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10007 return false;
10008 return HandleSizeof(Info, ExprLoc, Ty, Result);
10009 };
10010
George Burgess IVe3763372016-12-22 02:50:20 +000010011 // We want to evaluate the size of the entire object. This is a valid fallback
10012 // for when Type=1 and the designator is invalid, because we're asked for an
10013 // upper-bound.
10014 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10015 // Type=3 wants a lower bound, so we can't fall back to this.
10016 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +000010017 return false;
George Burgess IVe3763372016-12-22 02:50:20 +000010018
10019 llvm::APInt APEndOffset;
10020 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10021 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10022 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10023
10024 if (LVal.InvalidBase)
10025 return false;
10026
10027 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +000010028 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +000010029 }
10030
George Burgess IVe3763372016-12-22 02:50:20 +000010031 // We want to evaluate the size of a subobject.
10032 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010033
10034 // The following is a moderately common idiom in C:
10035 //
10036 // struct Foo { int a; char c[1]; };
10037 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10038 // strcpy(&F->c[0], Bar);
10039 //
George Burgess IVe3763372016-12-22 02:50:20 +000010040 // In order to not break too much legacy code, we need to support it.
10041 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10042 // If we can resolve this to an alloc_size call, we can hand that back,
10043 // because we know for certain how many bytes there are to write to.
10044 llvm::APInt APEndOffset;
10045 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10046 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10047 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10048
10049 // If we cannot determine the size of the initial allocation, then we can't
10050 // given an accurate upper-bound. However, we are still able to give
10051 // conservative lower-bounds for Type=3.
10052 if (Type == 1)
10053 return false;
10054 }
10055
10056 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +000010057 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010058 return false;
10059
George Burgess IVe3763372016-12-22 02:50:20 +000010060 // According to the GCC documentation, we want the size of the subobject
10061 // denoted by the pointer. But that's not quite right -- what we actually
10062 // want is the size of the immediately-enclosing array, if there is one.
10063 int64_t ElemsRemaining;
10064 if (Designator.MostDerivedIsArrayElement &&
10065 Designator.Entries.size() == Designator.MostDerivedPathLength) {
10066 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010067 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +000010068 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10069 } else {
10070 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10071 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010072
George Burgess IVe3763372016-12-22 02:50:20 +000010073 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10074 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010075}
10076
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010077/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +000010078/// returns true and stores the result in @p Size.
10079///
10080/// If @p WasError is non-null, this will report whether the failure to evaluate
10081/// is to be treated as an Error in IntExprEvaluator.
10082static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10083 EvalInfo &Info, uint64_t &Size) {
10084 // Determine the denoted object.
10085 LValue LVal;
10086 {
10087 // The operand of __builtin_object_size is never evaluated for side-effects.
10088 // If there are any, but we can determine the pointed-to object anyway, then
10089 // ignore the side-effects.
10090 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +000010091 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +000010092
10093 if (E->isGLValue()) {
10094 // It's possible for us to be given GLValues if we're called via
10095 // Expr::tryEvaluateObjectSize.
10096 APValue RVal;
10097 if (!EvaluateAsRValue(Info, E, RVal))
10098 return false;
10099 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +000010100 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10101 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +000010102 return false;
10103 }
10104
10105 // If we point to before the start of the object, there are no accessible
10106 // bytes.
10107 if (LVal.getLValueOffset().isNegative()) {
10108 Size = 0;
10109 return true;
10110 }
10111
10112 CharUnits EndOffset;
10113 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10114 return false;
10115
10116 // If we've fallen outside of the end offset, just pretend there's nothing to
10117 // write to/read from.
10118 if (EndOffset <= LVal.getLValueOffset())
10119 Size = 0;
10120 else
10121 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10122 return true;
John McCall95007602010-05-10 23:27:23 +000010123}
10124
Fangrui Song407659a2018-11-30 23:41:18 +000010125bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10126 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +000010127 if (E->getResultAPValueKind() != APValue::None)
10128 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +000010129 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10130}
10131
Peter Collingbournee9200682011-05-13 03:29:01 +000010132bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +000010133 if (unsigned BuiltinOp = E->getBuiltinCallee())
10134 return VisitBuiltinCallExpr(E, BuiltinOp);
10135
10136 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10137}
10138
10139bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10140 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +000010141 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010142 default:
Peter Collingbournee9200682011-05-13 03:29:01 +000010143 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +000010144
Erik Pilkington9c3b5882019-01-30 20:34:53 +000010145 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +000010146 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +000010147 // The type was checked when we built the expression.
10148 unsigned Type =
10149 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10150 assert(Type <= 3 && "unexpected type");
10151
George Burgess IVe3763372016-12-22 02:50:20 +000010152 uint64_t Size;
10153 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10154 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +000010155
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010156 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +000010157 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +000010158
Richard Smith01ade172012-05-23 04:13:20 +000010159 // Expression had no side effects, but we couldn't statically determine the
10160 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010161 switch (Info.EvalMode) {
10162 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010163 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010164 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010165 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010166 return Error(E);
10167 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010168 // Reduce it to a constant now.
10169 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010170 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +000010171
10172 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +000010173 }
10174
Tim Northover314fbfa2018-11-02 13:14:11 +000010175 case Builtin::BI__builtin_os_log_format_buffer_size: {
10176 analyze_os_log::OSLogBufferLayout Layout;
10177 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10178 return Success(Layout.size().getQuantity(), E);
10179 }
10180
Benjamin Kramera801f4a2012-10-06 14:42:22 +000010181 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +000010182 case Builtin::BI__builtin_bswap32:
10183 case Builtin::BI__builtin_bswap64: {
10184 APSInt Val;
10185 if (!EvaluateInteger(E->getArg(0), Val, Info))
10186 return false;
10187
10188 return Success(Val.byteSwap(), E);
10189 }
10190
Richard Smith8889a3d2013-06-13 06:26:32 +000010191 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +000010192 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +000010193
Craig Topperf95a6d92018-08-08 22:31:12 +000010194 case Builtin::BI__builtin_clrsb:
10195 case Builtin::BI__builtin_clrsbl:
10196 case Builtin::BI__builtin_clrsbll: {
10197 APSInt Val;
10198 if (!EvaluateInteger(E->getArg(0), Val, Info))
10199 return false;
10200
10201 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10202 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010203
Richard Smith80b3c8e2013-06-13 05:04:16 +000010204 case Builtin::BI__builtin_clz:
10205 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010206 case Builtin::BI__builtin_clzll:
10207 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010208 APSInt Val;
10209 if (!EvaluateInteger(E->getArg(0), Val, Info))
10210 return false;
10211 if (!Val)
10212 return Error(E);
10213
10214 return Success(Val.countLeadingZeros(), E);
10215 }
10216
Fangrui Song407659a2018-11-30 23:41:18 +000010217 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +000010218 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +000010219 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +000010220 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +000010221 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +000010222 // Outside a constant context, eagerly evaluate to false in the presence
10223 // of side-effects in order to avoid -Wunsequenced false-positives in
10224 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +000010225 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +000010226 }
David Blaikie639b3d12019-05-03 18:11:31 +000010227 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10228 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000010229 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010230
Eric Fiselieradd16a82019-04-24 02:23:30 +000010231 case Builtin::BI__builtin_is_constant_evaluated:
10232 return Success(Info.InConstantContext, E);
10233
Richard Smith80b3c8e2013-06-13 05:04:16 +000010234 case Builtin::BI__builtin_ctz:
10235 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010236 case Builtin::BI__builtin_ctzll:
10237 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010238 APSInt Val;
10239 if (!EvaluateInteger(E->getArg(0), Val, Info))
10240 return false;
10241 if (!Val)
10242 return Error(E);
10243
10244 return Success(Val.countTrailingZeros(), E);
10245 }
10246
Richard Smith8889a3d2013-06-13 06:26:32 +000010247 case Builtin::BI__builtin_eh_return_data_regno: {
10248 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10249 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10250 return Success(Operand, E);
10251 }
10252
10253 case Builtin::BI__builtin_expect:
10254 return Visit(E->getArg(0));
10255
10256 case Builtin::BI__builtin_ffs:
10257 case Builtin::BI__builtin_ffsl:
10258 case Builtin::BI__builtin_ffsll: {
10259 APSInt Val;
10260 if (!EvaluateInteger(E->getArg(0), Val, Info))
10261 return false;
10262
10263 unsigned N = Val.countTrailingZeros();
10264 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10265 }
10266
10267 case Builtin::BI__builtin_fpclassify: {
10268 APFloat Val(0.0);
10269 if (!EvaluateFloat(E->getArg(5), Val, Info))
10270 return false;
10271 unsigned Arg;
10272 switch (Val.getCategory()) {
10273 case APFloat::fcNaN: Arg = 0; break;
10274 case APFloat::fcInfinity: Arg = 1; break;
10275 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10276 case APFloat::fcZero: Arg = 4; break;
10277 }
10278 return Visit(E->getArg(Arg));
10279 }
10280
10281 case Builtin::BI__builtin_isinf_sign: {
10282 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +000010283 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +000010284 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10285 }
10286
Richard Smithea3019d2013-10-15 19:07:14 +000010287 case Builtin::BI__builtin_isinf: {
10288 APFloat Val(0.0);
10289 return EvaluateFloat(E->getArg(0), Val, Info) &&
10290 Success(Val.isInfinity() ? 1 : 0, E);
10291 }
10292
10293 case Builtin::BI__builtin_isfinite: {
10294 APFloat Val(0.0);
10295 return EvaluateFloat(E->getArg(0), Val, Info) &&
10296 Success(Val.isFinite() ? 1 : 0, E);
10297 }
10298
10299 case Builtin::BI__builtin_isnan: {
10300 APFloat Val(0.0);
10301 return EvaluateFloat(E->getArg(0), Val, Info) &&
10302 Success(Val.isNaN() ? 1 : 0, E);
10303 }
10304
10305 case Builtin::BI__builtin_isnormal: {
10306 APFloat Val(0.0);
10307 return EvaluateFloat(E->getArg(0), Val, Info) &&
10308 Success(Val.isNormal() ? 1 : 0, E);
10309 }
10310
Richard Smith8889a3d2013-06-13 06:26:32 +000010311 case Builtin::BI__builtin_parity:
10312 case Builtin::BI__builtin_parityl:
10313 case Builtin::BI__builtin_parityll: {
10314 APSInt Val;
10315 if (!EvaluateInteger(E->getArg(0), Val, Info))
10316 return false;
10317
10318 return Success(Val.countPopulation() % 2, E);
10319 }
10320
Richard Smith80b3c8e2013-06-13 05:04:16 +000010321 case Builtin::BI__builtin_popcount:
10322 case Builtin::BI__builtin_popcountl:
10323 case Builtin::BI__builtin_popcountll: {
10324 APSInt Val;
10325 if (!EvaluateInteger(E->getArg(0), Val, Info))
10326 return false;
10327
10328 return Success(Val.countPopulation(), E);
10329 }
10330
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010331 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +000010332 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +000010333 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010334 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010335 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +000010336 << /*isConstexpr*/0 << /*isConstructor*/0
10337 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +000010338 else
Richard Smithce1ec5e2012-03-15 04:53:45 +000010339 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010340 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +000010341 case Builtin::BI__builtin_strlen:
10342 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +000010343 // As an extension, we support __builtin_strlen() as a constant expression,
10344 // and support folding strlen() to a constant.
10345 LValue String;
10346 if (!EvaluatePointer(E->getArg(0), String, Info))
10347 return false;
10348
Richard Smith8110c9d2016-11-29 19:45:17 +000010349 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10350
Richard Smithe6c19f22013-11-15 02:10:04 +000010351 // Fast path: if it's a string literal, search the string value.
10352 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10353 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010354 // The string literal may have embedded null characters. Find the first
10355 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +000010356 StringRef Str = S->getBytes();
10357 int64_t Off = String.Offset.getQuantity();
10358 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010359 S->getCharByteWidth() == 1 &&
10360 // FIXME: Add fast-path for wchar_t too.
10361 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +000010362 Str = Str.substr(Off);
10363
10364 StringRef::size_type Pos = Str.find(0);
10365 if (Pos != StringRef::npos)
10366 Str = Str.substr(0, Pos);
10367
10368 return Success(Str.size(), E);
10369 }
10370
10371 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010372 }
Richard Smithe6c19f22013-11-15 02:10:04 +000010373
10374 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +000010375 for (uint64_t Strlen = 0; /**/; ++Strlen) {
10376 APValue Char;
10377 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
10378 !Char.isInt())
10379 return false;
10380 if (!Char.getInt())
10381 return Success(Strlen, E);
10382 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
10383 return false;
10384 }
10385 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010386
Richard Smithe151bab2016-11-11 23:43:35 +000010387 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010388 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010389 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010390 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010391 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010392 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010393 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010394 // A call to strlen is not a constant expression.
10395 if (Info.getLangOpts().CPlusPlus11)
10396 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10397 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +000010398 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +000010399 else
10400 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010401 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +000010402 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010403 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010404 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010405 case Builtin::BI__builtin_wcsncmp:
10406 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010407 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010408 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +000010409 LValue String1, String2;
10410 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10411 !EvaluatePointer(E->getArg(1), String2, Info))
10412 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +000010413
Richard Smithe151bab2016-11-11 23:43:35 +000010414 uint64_t MaxLength = uint64_t(-1);
10415 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010416 BuiltinOp != Builtin::BIwcscmp &&
10417 BuiltinOp != Builtin::BI__builtin_strcmp &&
10418 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +000010419 APSInt N;
10420 if (!EvaluateInteger(E->getArg(2), N, Info))
10421 return false;
10422 MaxLength = N.getExtValue();
10423 }
Hubert Tong147b7432018-12-12 16:53:43 +000010424
10425 // Empty substrings compare equal by definition.
10426 if (MaxLength == 0u)
10427 return Success(0, E);
10428
10429 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10430 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10431 String1.Designator.Invalid || String2.Designator.Invalid)
10432 return false;
10433
10434 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10435 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10436
10437 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +000010438 BuiltinOp == Builtin::BIbcmp ||
10439 BuiltinOp == Builtin::BI__builtin_memcmp ||
10440 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010441
10442 assert(IsRawByte ||
10443 (Info.Ctx.hasSameUnqualifiedType(
10444 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
10445 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
10446
10447 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10448 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10449 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10450 Char1.isInt() && Char2.isInt();
10451 };
10452 const auto &AdvanceElems = [&] {
10453 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10454 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10455 };
10456
10457 if (IsRawByte) {
10458 uint64_t BytesRemaining = MaxLength;
10459 // Pointers to const void may point to objects of incomplete type.
10460 if (CharTy1->isIncompleteType()) {
10461 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10462 return false;
10463 }
10464 if (CharTy2->isIncompleteType()) {
10465 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10466 return false;
10467 }
10468 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10469 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10470 // Give up on comparing between elements with disparate widths.
10471 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10472 return false;
10473 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10474 assert(BytesRemaining && "BytesRemaining should not be zero: the "
10475 "following loop considers at least one element");
10476 while (true) {
10477 APValue Char1, Char2;
10478 if (!ReadCurElems(Char1, Char2))
10479 return false;
10480 // We have compatible in-memory widths, but a possible type and
10481 // (for `bool`) internal representation mismatch.
10482 // Assuming two's complement representation, including 0 for `false` and
10483 // 1 for `true`, we can check an appropriate number of elements for
10484 // equality even if they are not byte-sized.
10485 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10486 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10487 if (Char1InMem.ne(Char2InMem)) {
10488 // If the elements are byte-sized, then we can produce a three-way
10489 // comparison result in a straightforward manner.
10490 if (BytesPerElement == 1u) {
10491 // memcmp always compares unsigned chars.
10492 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10493 }
10494 // The result is byte-order sensitive, and we have multibyte elements.
10495 // FIXME: We can compare the remaining bytes in the correct order.
10496 return false;
10497 }
10498 if (!AdvanceElems())
10499 return false;
10500 if (BytesRemaining <= BytesPerElement)
10501 break;
10502 BytesRemaining -= BytesPerElement;
10503 }
10504 // Enough elements are equal to account for the memcmp limit.
10505 return Success(0, E);
10506 }
10507
Clement Courbet8c3343d2019-02-14 12:00:34 +000010508 bool StopAtNull =
10509 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10510 BuiltinOp != Builtin::BIwmemcmp &&
10511 BuiltinOp != Builtin::BI__builtin_memcmp &&
10512 BuiltinOp != Builtin::BI__builtin_bcmp &&
10513 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +000010514 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10515 BuiltinOp == Builtin::BIwcsncmp ||
10516 BuiltinOp == Builtin::BIwmemcmp ||
10517 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10518 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10519 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010520
Richard Smithe151bab2016-11-11 23:43:35 +000010521 for (; MaxLength; --MaxLength) {
10522 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +000010523 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +000010524 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +000010525 if (Char1.getInt() != Char2.getInt()) {
10526 if (IsWide) // wmemcmp compares with wchar_t signedness.
10527 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10528 // memcmp always compares unsigned chars.
10529 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10530 }
Richard Smithe151bab2016-11-11 23:43:35 +000010531 if (StopAtNull && !Char1.getInt())
10532 return Success(0, E);
10533 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +000010534 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +000010535 return false;
10536 }
10537 // We hit the strncmp / memcmp limit.
10538 return Success(0, E);
10539 }
10540
Richard Smith01ba47d2012-04-13 00:45:38 +000010541 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +000010542 case Builtin::BI__atomic_is_lock_free:
10543 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +000010544 APSInt SizeVal;
10545 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10546 return false;
10547
10548 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10549 // of two less than the maximum inline atomic width, we know it is
10550 // lock-free. If the size isn't a power of two, or greater than the
10551 // maximum alignment where we promote atomics, we know it is not lock-free
10552 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10553 // the answer can only be determined at runtime; for example, 16-byte
10554 // atomics have lock-free implementations on some, but not all,
10555 // x86-64 processors.
10556
10557 // Check power-of-two.
10558 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +000010559 if (Size.isPowerOfTwo()) {
10560 // Check against inlining width.
10561 unsigned InlineWidthBits =
10562 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10563 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10564 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10565 Size == CharUnits::One() ||
10566 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10567 Expr::NPC_NeverValueDependent))
10568 // OK, we will inline appropriately-aligned operations of this size,
10569 // and _Atomic(T) is appropriately-aligned.
10570 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010571
Richard Smith01ba47d2012-04-13 00:45:38 +000010572 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10573 castAs<PointerType>()->getPointeeType();
10574 if (!PointeeType->isIncompleteType() &&
10575 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10576 // OK, we will inline operations on this object.
10577 return Success(1, E);
10578 }
10579 }
10580 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010581
Richard Smith01ba47d2012-04-13 00:45:38 +000010582 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10583 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010584 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +000010585 case Builtin::BIomp_is_initial_device:
10586 // We can decide statically which value the runtime would return if called.
10587 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +000010588 case Builtin::BI__builtin_add_overflow:
10589 case Builtin::BI__builtin_sub_overflow:
10590 case Builtin::BI__builtin_mul_overflow:
10591 case Builtin::BI__builtin_sadd_overflow:
10592 case Builtin::BI__builtin_uadd_overflow:
10593 case Builtin::BI__builtin_uaddl_overflow:
10594 case Builtin::BI__builtin_uaddll_overflow:
10595 case Builtin::BI__builtin_usub_overflow:
10596 case Builtin::BI__builtin_usubl_overflow:
10597 case Builtin::BI__builtin_usubll_overflow:
10598 case Builtin::BI__builtin_umul_overflow:
10599 case Builtin::BI__builtin_umull_overflow:
10600 case Builtin::BI__builtin_umulll_overflow:
10601 case Builtin::BI__builtin_saddl_overflow:
10602 case Builtin::BI__builtin_saddll_overflow:
10603 case Builtin::BI__builtin_ssub_overflow:
10604 case Builtin::BI__builtin_ssubl_overflow:
10605 case Builtin::BI__builtin_ssubll_overflow:
10606 case Builtin::BI__builtin_smul_overflow:
10607 case Builtin::BI__builtin_smull_overflow:
10608 case Builtin::BI__builtin_smulll_overflow: {
10609 LValue ResultLValue;
10610 APSInt LHS, RHS;
10611
10612 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10613 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10614 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10615 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10616 return false;
10617
10618 APSInt Result;
10619 bool DidOverflow = false;
10620
10621 // If the types don't have to match, enlarge all 3 to the largest of them.
10622 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10623 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10624 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10625 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
10626 ResultType->isSignedIntegerOrEnumerationType();
10627 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
10628 ResultType->isSignedIntegerOrEnumerationType();
10629 uint64_t LHSSize = LHS.getBitWidth();
10630 uint64_t RHSSize = RHS.getBitWidth();
10631 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
10632 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
10633
10634 // Add an additional bit if the signedness isn't uniformly agreed to. We
10635 // could do this ONLY if there is a signed and an unsigned that both have
10636 // MaxBits, but the code to check that is pretty nasty. The issue will be
10637 // caught in the shrink-to-result later anyway.
10638 if (IsSigned && !AllSigned)
10639 ++MaxBits;
10640
Erich Keanefc3dfd32019-05-30 21:35:32 +000010641 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
10642 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +000010643 Result = APSInt(MaxBits, !IsSigned);
10644 }
10645
10646 // Find largest int.
10647 switch (BuiltinOp) {
10648 default:
10649 llvm_unreachable("Invalid value for BuiltinOp");
10650 case Builtin::BI__builtin_add_overflow:
10651 case Builtin::BI__builtin_sadd_overflow:
10652 case Builtin::BI__builtin_saddl_overflow:
10653 case Builtin::BI__builtin_saddll_overflow:
10654 case Builtin::BI__builtin_uadd_overflow:
10655 case Builtin::BI__builtin_uaddl_overflow:
10656 case Builtin::BI__builtin_uaddll_overflow:
10657 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10658 : LHS.uadd_ov(RHS, DidOverflow);
10659 break;
10660 case Builtin::BI__builtin_sub_overflow:
10661 case Builtin::BI__builtin_ssub_overflow:
10662 case Builtin::BI__builtin_ssubl_overflow:
10663 case Builtin::BI__builtin_ssubll_overflow:
10664 case Builtin::BI__builtin_usub_overflow:
10665 case Builtin::BI__builtin_usubl_overflow:
10666 case Builtin::BI__builtin_usubll_overflow:
10667 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10668 : LHS.usub_ov(RHS, DidOverflow);
10669 break;
10670 case Builtin::BI__builtin_mul_overflow:
10671 case Builtin::BI__builtin_smul_overflow:
10672 case Builtin::BI__builtin_smull_overflow:
10673 case Builtin::BI__builtin_smulll_overflow:
10674 case Builtin::BI__builtin_umul_overflow:
10675 case Builtin::BI__builtin_umull_overflow:
10676 case Builtin::BI__builtin_umulll_overflow:
10677 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10678 : LHS.umul_ov(RHS, DidOverflow);
10679 break;
10680 }
10681
10682 // In the case where multiple sizes are allowed, truncate and see if
10683 // the values are the same.
10684 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10685 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10686 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10687 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10688 // since it will give us the behavior of a TruncOrSelf in the case where
10689 // its parameter <= its size. We previously set Result to be at least the
10690 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10691 // will work exactly like TruncOrSelf.
10692 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10693 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10694
10695 if (!APSInt::isSameValue(Temp, Result))
10696 DidOverflow = true;
10697 Result = Temp;
10698 }
10699
10700 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000010701 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10702 return false;
Erich Keane00958272018-06-13 20:43:27 +000010703 return Success(DidOverflow, E);
10704 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010705 }
Chris Lattner7174bf32008-07-12 00:38:25 +000010706}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000010707
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010708/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000010709/// object referred to by the lvalue.
10710static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10711 const LValue &LV) {
10712 // A null pointer can be viewed as being "past the end" but we don't
10713 // choose to look at it that way here.
10714 if (!LV.getLValueBase())
10715 return false;
10716
10717 // If the designator is valid and refers to a subobject, we're not pointing
10718 // past the end.
10719 if (!LV.getLValueDesignator().Invalid &&
10720 !LV.getLValueDesignator().isOnePastTheEnd())
10721 return false;
10722
David Majnemerc378ca52015-08-29 08:32:55 +000010723 // A pointer to an incomplete type might be past-the-end if the type's size is
10724 // zero. We cannot tell because the type is incomplete.
10725 QualType Ty = getType(LV.getLValueBase());
10726 if (Ty->isIncompleteType())
10727 return true;
10728
Richard Smithd20f1e62014-10-21 23:01:04 +000010729 // We're a past-the-end pointer if we point to the byte after the object,
10730 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000010731 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000010732 return LV.getLValueOffset() == Size;
10733}
10734
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010735namespace {
Richard Smith11562c52011-10-28 17:51:58 +000010736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010737/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010738///
10739/// We use a data recursive algorithm for binary operators so that we are able
10740/// to handle extreme cases of chained binary operators without causing stack
10741/// overflow.
10742class DataRecursiveIntBinOpEvaluator {
10743 struct EvalResult {
10744 APValue Val;
10745 bool Failed;
10746
10747 EvalResult() : Failed(false) { }
10748
10749 void swap(EvalResult &RHS) {
10750 Val.swap(RHS.Val);
10751 Failed = RHS.Failed;
10752 RHS.Failed = false;
10753 }
10754 };
10755
10756 struct Job {
10757 const Expr *E;
10758 EvalResult LHSResult; // meaningful only for binary operator expression.
10759 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000010760
David Blaikie73726062015-08-12 23:09:24 +000010761 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000010762 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000010763
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010764 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000010765 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010766 }
George Burgess IV8c892b52016-05-25 22:31:54 +000010767
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010768 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000010769 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010770 };
10771
10772 SmallVector<Job, 16> Queue;
10773
10774 IntExprEvaluator &IntEval;
10775 EvalInfo &Info;
10776 APValue &FinalResult;
10777
10778public:
10779 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10780 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10781
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010782 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010783 /// data recursively.
10784 /// We handle binary operators that are comma, logical, or that have operands
10785 /// with integral or enumeration type.
10786 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010787 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10788 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000010789 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010790 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000010791 }
10792
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010793 bool Traverse(const BinaryOperator *E) {
10794 enqueue(E);
10795 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000010796 while (!Queue.empty())
10797 process(PrevResult);
10798
10799 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010800
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010801 FinalResult.swap(PrevResult.Val);
10802 return true;
10803 }
10804
10805private:
10806 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10807 return IntEval.Success(Value, E, Result);
10808 }
10809 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10810 return IntEval.Success(Value, E, Result);
10811 }
10812 bool Error(const Expr *E) {
10813 return IntEval.Error(E);
10814 }
10815 bool Error(const Expr *E, diag::kind D) {
10816 return IntEval.Error(E, D);
10817 }
10818
10819 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10820 return Info.CCEDiag(E, D);
10821 }
10822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010823 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010824 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010825 bool &SuppressRHSDiags);
10826
10827 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10828 const BinaryOperator *E, APValue &Result);
10829
10830 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10831 Result.Failed = !Evaluate(Result.Val, Info, E);
10832 if (Result.Failed)
10833 Result.Val = APValue();
10834 }
10835
Richard Trieuba4d0872012-03-21 23:30:30 +000010836 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010837
10838 void enqueue(const Expr *E) {
10839 E = E->IgnoreParens();
10840 Queue.resize(Queue.size()+1);
10841 Queue.back().E = E;
10842 Queue.back().Kind = Job::AnyExprKind;
10843 }
10844};
10845
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010846}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010847
10848bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010849 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010850 bool &SuppressRHSDiags) {
10851 if (E->getOpcode() == BO_Comma) {
10852 // Ignore LHS but note if we could not evaluate it.
10853 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000010854 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010855 return true;
10856 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010857
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010858 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010859 bool LHSAsBool;
10860 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010861 // We were able to evaluate the LHS, see if we can get away with not
10862 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000010863 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10864 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010865 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010866 }
10867 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010868 LHSResult.Failed = true;
10869
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010870 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000010871 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000010872 if (!Info.noteSideEffect())
10873 return false;
10874
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010875 // We can't evaluate the LHS; however, sometimes the result
10876 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10877 // Don't ignore RHS and suppress diagnostics from this arm.
10878 SuppressRHSDiags = true;
10879 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010880
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010881 return true;
10882 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010883
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010884 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10885 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000010886
George Burgess IVa145e252016-05-25 22:38:36 +000010887 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010888 return false; // Ignore RHS;
10889
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010890 return true;
10891}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010892
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000010893static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10894 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000010895 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10896 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10897 // offsets.
10898 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10899 CharUnits &Offset = LVal.getLValueOffset();
10900 uint64_t Offset64 = Offset.getQuantity();
10901 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10902 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10903 : Offset64 + Index64);
10904}
10905
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010906bool DataRecursiveIntBinOpEvaluator::
10907 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10908 const BinaryOperator *E, APValue &Result) {
10909 if (E->getOpcode() == BO_Comma) {
10910 if (RHSResult.Failed)
10911 return false;
10912 Result = RHSResult.Val;
10913 return true;
10914 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010915
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010916 if (E->isLogicalOp()) {
10917 bool lhsResult, rhsResult;
10918 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10919 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000010920
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010921 if (LHSIsOK) {
10922 if (RHSIsOK) {
10923 if (E->getOpcode() == BO_LOr)
10924 return Success(lhsResult || rhsResult, E, Result);
10925 else
10926 return Success(lhsResult && rhsResult, E, Result);
10927 }
10928 } else {
10929 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010930 // We can't evaluate the LHS; however, sometimes the result
10931 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10932 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010933 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010934 }
10935 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010936
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010937 return false;
10938 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010939
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010940 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10941 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000010942
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010943 if (LHSResult.Failed || RHSResult.Failed)
10944 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010945
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010946 const APValue &LHSVal = LHSResult.Val;
10947 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000010948
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010949 // Handle cases like (unsigned long)&a + 4.
10950 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10951 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010952 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010953 return true;
10954 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010955
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010956 // Handle cases like 4 + (unsigned long)&a
10957 if (E->getOpcode() == BO_Add &&
10958 RHSVal.isLValue() && LHSVal.isInt()) {
10959 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010960 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010961 return true;
10962 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010963
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010964 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10965 // Handle (intptr_t)&&A - (intptr_t)&&B.
10966 if (!LHSVal.getLValueOffset().isZero() ||
10967 !RHSVal.getLValueOffset().isZero())
10968 return false;
10969 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10970 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10971 if (!LHSExpr || !RHSExpr)
10972 return false;
10973 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10974 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10975 if (!LHSAddrExpr || !RHSAddrExpr)
10976 return false;
10977 // Make sure both labels come from the same function.
10978 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10979 RHSAddrExpr->getLabel()->getDeclContext())
10980 return false;
10981 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10982 return true;
10983 }
Richard Smith43e77732013-05-07 04:50:00 +000010984
10985 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010986 if (!LHSVal.isInt() || !RHSVal.isInt())
10987 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000010988
10989 // Set up the width and signedness manually, in case it can't be deduced
10990 // from the operation we're performing.
10991 // FIXME: Don't do this in the cases where we can deduce it.
10992 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10993 E->getType()->isUnsignedIntegerOrEnumerationType());
10994 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10995 RHSVal.getInt(), Value))
10996 return false;
10997 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010998}
10999
Richard Trieuba4d0872012-03-21 23:30:30 +000011000void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011001 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000011002
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011003 switch (job.Kind) {
11004 case Job::AnyExprKind: {
11005 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11006 if (shouldEnqueue(Bop)) {
11007 job.Kind = Job::BinOpKind;
11008 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011009 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011010 }
11011 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011012
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011013 EvaluateExpr(job.E, Result);
11014 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011015 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011016 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011017
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011018 case Job::BinOpKind: {
11019 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011020 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011021 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011022 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011023 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011024 }
11025 if (SuppressRHSDiags)
11026 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011027 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011028 job.Kind = Job::BinOpVisitedLHSKind;
11029 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011030 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011031 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011032
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011033 case Job::BinOpVisitedLHSKind: {
11034 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11035 EvalResult RHS;
11036 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000011037 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011038 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011039 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011040 }
11041 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011042
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011043 llvm_unreachable("Invalid Job::Kind!");
11044}
11045
George Burgess IV8c892b52016-05-25 22:31:54 +000011046namespace {
11047/// Used when we determine that we should fail, but can keep evaluating prior to
11048/// noting that we had a failure.
11049class DelayedNoteFailureRAII {
11050 EvalInfo &Info;
11051 bool NoteFailure;
11052
11053public:
11054 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11055 : Info(Info), NoteFailure(NoteFailure) {}
11056 ~DelayedNoteFailureRAII() {
11057 if (NoteFailure) {
11058 bool ContinueAfterFailure = Info.noteFailure();
11059 (void)ContinueAfterFailure;
11060 assert(ContinueAfterFailure &&
11061 "Shouldn't have kept evaluating on failure.");
11062 }
11063 }
11064};
11065}
11066
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011067template <class SuccessCB, class AfterCB>
11068static bool
11069EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11070 SuccessCB &&Success, AfterCB &&DoAfter) {
11071 assert(E->isComparisonOp() && "expected comparison operator");
11072 assert((E->getOpcode() == BO_Cmp ||
11073 E->getType()->isIntegralOrEnumerationType()) &&
11074 "unsupported binary expression evaluation");
11075 auto Error = [&](const Expr *E) {
11076 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11077 return false;
11078 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011079
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011080 using CCR = ComparisonCategoryResult;
11081 bool IsRelational = E->isRelationalOp();
11082 bool IsEquality = E->isEqualityOp();
11083 if (E->getOpcode() == BO_Cmp) {
11084 const ComparisonCategoryInfo &CmpInfo =
11085 Info.Ctx.CompCategories.getInfoForType(E->getType());
11086 IsRelational = CmpInfo.isOrdered();
11087 IsEquality = CmpInfo.isEquality();
11088 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000011089
Anders Carlssonacc79812008-11-16 07:17:21 +000011090 QualType LHSTy = E->getLHS()->getType();
11091 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011092
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011093 if (LHSTy->isIntegralOrEnumerationType() &&
11094 RHSTy->isIntegralOrEnumerationType()) {
11095 APSInt LHS, RHS;
11096 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11097 if (!LHSOK && !Info.noteFailure())
11098 return false;
11099 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11100 return false;
11101 if (LHS < RHS)
11102 return Success(CCR::Less, E);
11103 if (LHS > RHS)
11104 return Success(CCR::Greater, E);
11105 return Success(CCR::Equal, E);
11106 }
11107
Leonard Chance1d4f12019-02-21 20:50:09 +000011108 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11109 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11110 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11111
11112 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11113 if (!LHSOK && !Info.noteFailure())
11114 return false;
11115 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11116 return false;
11117 if (LHSFX < RHSFX)
11118 return Success(CCR::Less, E);
11119 if (LHSFX > RHSFX)
11120 return Success(CCR::Greater, E);
11121 return Success(CCR::Equal, E);
11122 }
11123
Chandler Carruthb29a7432014-10-11 11:03:30 +000011124 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011125 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000011126 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000011127 if (E->isAssignmentOp()) {
11128 LValue LV;
11129 EvaluateLValue(E->getLHS(), LV, Info);
11130 LHSOK = false;
11131 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000011132 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11133 if (LHSOK) {
11134 LHS.makeComplexFloat();
11135 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11136 }
11137 } else {
11138 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11139 }
George Burgess IVa145e252016-05-25 22:38:36 +000011140 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011141 return false;
11142
Chandler Carruthb29a7432014-10-11 11:03:30 +000011143 if (E->getRHS()->getType()->isRealFloatingType()) {
11144 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11145 return false;
11146 RHS.makeComplexFloat();
11147 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11148 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011149 return false;
11150
11151 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000011152 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011153 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000011154 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011155 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011156 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11157 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011158 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011159 assert(IsEquality && "invalid complex comparison");
11160 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11161 LHS.getComplexIntImag() == RHS.getComplexIntImag();
11162 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011163 }
11164 }
Mike Stump11289f42009-09-09 15:08:12 +000011165
Anders Carlssonacc79812008-11-16 07:17:21 +000011166 if (LHSTy->isRealFloatingType() &&
11167 RHSTy->isRealFloatingType()) {
11168 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000011169
Richard Smith253c2a32012-01-27 01:14:48 +000011170 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011171 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000011172 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011173
Richard Smith253c2a32012-01-27 01:14:48 +000011174 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000011175 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011176
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011177 assert(E->isComparisonOp() && "Invalid binary operator!");
11178 auto GetCmpRes = [&]() {
11179 switch (LHS.compare(RHS)) {
11180 case APFloat::cmpEqual:
11181 return CCR::Equal;
11182 case APFloat::cmpLessThan:
11183 return CCR::Less;
11184 case APFloat::cmpGreaterThan:
11185 return CCR::Greater;
11186 case APFloat::cmpUnordered:
11187 return CCR::Unordered;
11188 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000011189 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011190 };
11191 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000011192 }
Mike Stump11289f42009-09-09 15:08:12 +000011193
Eli Friedmana38da572009-04-28 19:17:36 +000011194 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011195 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000011196
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011197 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11198 if (!LHSOK && !Info.noteFailure())
11199 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011200
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011201 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11202 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011203
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011204 // Reject differing bases from the normal codepath; we special-case
11205 // comparisons to null.
11206 if (!HasSameBase(LHSValue, RHSValue)) {
11207 // Inequalities and subtractions between unrelated pointers have
11208 // unspecified or undefined behavior.
11209 if (!IsEquality)
11210 return Error(E);
11211 // A constant address may compare equal to the address of a symbol.
11212 // The one exception is that address of an object cannot compare equal
11213 // to a null pointer constant.
11214 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11215 (!RHSValue.Base && !RHSValue.Offset.isZero()))
11216 return Error(E);
11217 // It's implementation-defined whether distinct literals will have
11218 // distinct addresses. In clang, the result of such a comparison is
11219 // unspecified, so it is not a constant expression. However, we do know
11220 // that the address of a literal will be non-null.
11221 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11222 LHSValue.Base && RHSValue.Base)
11223 return Error(E);
11224 // We can't tell whether weak symbols will end up pointing to the same
11225 // object.
11226 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11227 return Error(E);
11228 // We can't compare the address of the start of one object with the
11229 // past-the-end address of another object, per C++ DR1652.
11230 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11231 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11232 (RHSValue.Base && RHSValue.Offset.isZero() &&
11233 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11234 return Error(E);
11235 // We can't tell whether an object is at the same address as another
11236 // zero sized object.
11237 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11238 (LHSValue.Base && isZeroSized(RHSValue)))
11239 return Error(E);
11240 return Success(CCR::Nonequal, E);
11241 }
Eli Friedman64004332009-03-23 04:38:34 +000011242
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011243 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11244 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000011245
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011246 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11247 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000011248
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011249 // C++11 [expr.rel]p3:
11250 // Pointers to void (after pointer conversions) can be compared, with a
11251 // result defined as follows: If both pointers represent the same
11252 // address or are both the null pointer value, the result is true if the
11253 // operator is <= or >= and false otherwise; otherwise the result is
11254 // unspecified.
11255 // We interpret this as applying to pointers to *cv* void.
11256 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11257 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000011258
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011259 // C++11 [expr.rel]p2:
11260 // - If two pointers point to non-static data members of the same object,
11261 // or to subobjects or array elements fo such members, recursively, the
11262 // pointer to the later declared member compares greater provided the
11263 // two members have the same access control and provided their class is
11264 // not a union.
11265 // [...]
11266 // - Otherwise pointer comparisons are unspecified.
11267 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11268 bool WasArrayIndex;
11269 unsigned Mismatch = FindDesignatorMismatch(
11270 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11271 // At the point where the designators diverge, the comparison has a
11272 // specified value if:
11273 // - we are comparing array indices
11274 // - we are comparing fields of a union, or fields with the same access
11275 // Otherwise, the result is unspecified and thus the comparison is not a
11276 // constant expression.
11277 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11278 Mismatch < RHSDesignator.Entries.size()) {
11279 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11280 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11281 if (!LF && !RF)
11282 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11283 else if (!LF)
11284 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011285 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11286 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011287 else if (!RF)
11288 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011289 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11290 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011291 else if (!LF->getParent()->isUnion() &&
11292 LF->getAccess() != RF->getAccess())
11293 Info.CCEDiag(E,
11294 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011295 << LF << LF->getAccess() << RF << RF->getAccess()
11296 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000011297 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011298 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011299
11300 // The comparison here must be unsigned, and performed with the same
11301 // width as the pointer.
11302 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11303 uint64_t CompareLHS = LHSOffset.getQuantity();
11304 uint64_t CompareRHS = RHSOffset.getQuantity();
11305 assert(PtrSize <= 64 && "Unexpected pointer width");
11306 uint64_t Mask = ~0ULL >> (64 - PtrSize);
11307 CompareLHS &= Mask;
11308 CompareRHS &= Mask;
11309
11310 // If there is a base and this is a relational operator, we can only
11311 // compare pointers within the object in question; otherwise, the result
11312 // depends on where the object is located in memory.
11313 if (!LHSValue.Base.isNull() && IsRelational) {
11314 QualType BaseTy = getType(LHSValue.Base);
11315 if (BaseTy->isIncompleteType())
11316 return Error(E);
11317 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11318 uint64_t OffsetLimit = Size.getQuantity();
11319 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11320 return Error(E);
11321 }
11322
11323 if (CompareLHS < CompareRHS)
11324 return Success(CCR::Less, E);
11325 if (CompareLHS > CompareRHS)
11326 return Success(CCR::Greater, E);
11327 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011328 }
Richard Smith7bb00672012-02-01 01:42:44 +000011329
11330 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011331 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000011332 assert(RHSTy->isMemberPointerType() && "invalid comparison");
11333
11334 MemberPtr LHSValue, RHSValue;
11335
11336 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011337 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000011338 return false;
11339
11340 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11341 return false;
11342
11343 // C++11 [expr.eq]p2:
11344 // If both operands are null, they compare equal. Otherwise if only one is
11345 // null, they compare unequal.
11346 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11347 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011348 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011349 }
11350
11351 // Otherwise if either is a pointer to a virtual member function, the
11352 // result is unspecified.
11353 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11354 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011355 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011356 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11357 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011358 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011359
11360 // Otherwise they compare equal if and only if they would refer to the
11361 // same member of the same most derived object or the same subobject if
11362 // they were dereferenced with a hypothetical object of the associated
11363 // class type.
11364 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011365 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011366 }
11367
Richard Smithab44d9b2012-02-14 22:35:28 +000011368 if (LHSTy->isNullPtrType()) {
11369 assert(E->isComparisonOp() && "unexpected nullptr operation");
11370 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
11371 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
11372 // are compared, the result is true of the operator is <=, >= or ==, and
11373 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011374 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000011375 }
11376
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011377 return DoAfter();
11378}
11379
11380bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
11381 if (!CheckLiteralType(Info, E))
11382 return false;
11383
11384 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11385 const BinaryOperator *E) {
11386 // Evaluation succeeded. Lookup the information for the comparison category
11387 // type and fetch the VarDecl for the result.
11388 const ComparisonCategoryInfo &CmpInfo =
11389 Info.Ctx.CompCategories.getInfoForType(E->getType());
11390 const VarDecl *VD =
11391 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
11392 // Check and evaluate the result as a constant expression.
11393 LValue LV;
11394 LV.set(VD);
11395 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11396 return false;
11397 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11398 };
11399 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11400 return ExprEvaluatorBaseTy::VisitBinCmp(E);
11401 });
11402}
11403
11404bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11405 // We don't call noteFailure immediately because the assignment happens after
11406 // we evaluate LHS and RHS.
11407 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11408 return Error(E);
11409
11410 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11411 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11412 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11413
11414 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
11415 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011416 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011417
11418 if (E->isComparisonOp()) {
11419 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11420 // comparisons and then translating the result.
11421 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11422 const BinaryOperator *E) {
11423 using CCR = ComparisonCategoryResult;
11424 bool IsEqual = ResKind == CCR::Equal,
11425 IsLess = ResKind == CCR::Less,
11426 IsGreater = ResKind == CCR::Greater;
11427 auto Op = E->getOpcode();
11428 switch (Op) {
11429 default:
11430 llvm_unreachable("unsupported binary operator");
11431 case BO_EQ:
11432 case BO_NE:
11433 return Success(IsEqual == (Op == BO_EQ), E);
11434 case BO_LT: return Success(IsLess, E);
11435 case BO_GT: return Success(IsGreater, E);
11436 case BO_LE: return Success(IsEqual || IsLess, E);
11437 case BO_GE: return Success(IsEqual || IsGreater, E);
11438 }
11439 };
11440 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11441 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11442 });
11443 }
11444
11445 QualType LHSTy = E->getLHS()->getType();
11446 QualType RHSTy = E->getRHS()->getType();
11447
11448 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11449 E->getOpcode() == BO_Sub) {
11450 LValue LHSValue, RHSValue;
11451
11452 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11453 if (!LHSOK && !Info.noteFailure())
11454 return false;
11455
11456 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11457 return false;
11458
11459 // Reject differing bases from the normal codepath; we special-case
11460 // comparisons to null.
11461 if (!HasSameBase(LHSValue, RHSValue)) {
11462 // Handle &&A - &&B.
11463 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11464 return Error(E);
11465 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11466 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11467 if (!LHSExpr || !RHSExpr)
11468 return Error(E);
11469 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11470 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11471 if (!LHSAddrExpr || !RHSAddrExpr)
11472 return Error(E);
11473 // Make sure both labels come from the same function.
11474 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11475 RHSAddrExpr->getLabel()->getDeclContext())
11476 return Error(E);
11477 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11478 }
11479 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11480 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11481
11482 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11483 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11484
11485 // C++11 [expr.add]p6:
11486 // Unless both pointers point to elements of the same array object, or
11487 // one past the last element of the array object, the behavior is
11488 // undefined.
11489 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11490 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11491 RHSDesignator))
11492 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11493
11494 QualType Type = E->getLHS()->getType();
11495 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
11496
11497 CharUnits ElementSize;
11498 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11499 return false;
11500
11501 // As an extension, a type may have zero size (empty struct or union in
11502 // C, array of zero length). Pointer subtraction in such cases has
11503 // undefined behavior, so is not constant.
11504 if (ElementSize.isZero()) {
11505 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11506 << ElementType;
11507 return false;
11508 }
11509
11510 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11511 // and produce incorrect results when it overflows. Such behavior
11512 // appears to be non-conforming, but is common, so perhaps we should
11513 // assume the standard intended for such cases to be undefined behavior
11514 // and check for them.
11515
11516 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11517 // overflow in the final conversion to ptrdiff_t.
11518 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11519 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11520 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11521 false);
11522 APSInt TrueResult = (LHS - RHS) / ElemSize;
11523 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11524
11525 if (Result.extend(65) != TrueResult &&
11526 !HandleOverflow(Info, E, TrueResult, E->getType()))
11527 return false;
11528 return Success(Result, E);
11529 }
11530
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011531 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000011532}
11533
Peter Collingbournee190dee2011-03-11 19:24:49 +000011534/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11535/// a result as the expression's type.
11536bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11537 const UnaryExprOrTypeTraitExpr *E) {
11538 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000011539 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000011540 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000011541 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000011542 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11543 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011544 else
Richard Smith6822bd72018-10-26 19:26:45 +000011545 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11546 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011547 }
Eli Friedman64004332009-03-23 04:38:34 +000011548
Peter Collingbournee190dee2011-03-11 19:24:49 +000011549 case UETT_VecStep: {
11550 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000011551
Peter Collingbournee190dee2011-03-11 19:24:49 +000011552 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000011553 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000011554
Peter Collingbournee190dee2011-03-11 19:24:49 +000011555 // The vec_step built-in functions that take a 3-component
11556 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11557 if (n == 3)
11558 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000011559
Peter Collingbournee190dee2011-03-11 19:24:49 +000011560 return Success(n, E);
11561 } else
11562 return Success(1, E);
11563 }
11564
11565 case UETT_SizeOf: {
11566 QualType SrcTy = E->getTypeOfArgument();
11567 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11568 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000011569 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11570 SrcTy = Ref->getPointeeType();
11571
Richard Smithd62306a2011-11-10 06:34:14 +000011572 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000011573 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000011574 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000011575 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011576 }
Alexey Bataev00396512015-07-02 03:40:19 +000011577 case UETT_OpenMPRequiredSimdAlign:
11578 assert(E->isArgumentType());
11579 return Success(
11580 Info.Ctx.toCharUnitsFromBits(
11581 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11582 .getQuantity(),
11583 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011584 }
11585
11586 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000011587}
11588
Peter Collingbournee9200682011-05-13 03:29:01 +000011589bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011590 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000011591 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000011592 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011593 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000011594 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000011595 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000011596 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000011597 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000011598 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000011599 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000011600 APSInt IdxResult;
11601 if (!EvaluateInteger(Idx, IdxResult, Info))
11602 return false;
11603 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11604 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011605 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011606 CurrentType = AT->getElementType();
11607 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11608 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000011609 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000011610 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011611
James Y Knight7281c352015-12-29 22:31:18 +000011612 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000011613 FieldDecl *MemberDecl = ON.getField();
11614 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011615 if (!RT)
11616 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011617 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011618 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000011619 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000011620 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000011621 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000011622 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000011623 CurrentType = MemberDecl->getType().getNonReferenceType();
11624 break;
11625 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011626
James Y Knight7281c352015-12-29 22:31:18 +000011627 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000011628 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000011629
James Y Knight7281c352015-12-29 22:31:18 +000011630 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000011631 CXXBaseSpecifier *BaseSpec = ON.getBase();
11632 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000011633 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011634
11635 // Find the layout of the class whose base we are looking into.
11636 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011637 if (!RT)
11638 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011639 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011640 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000011641 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11642
11643 // Find the base class itself.
11644 CurrentType = BaseSpec->getType();
11645 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
11646 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011647 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000011648
Douglas Gregord1702062010-04-29 00:18:15 +000011649 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000011650 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000011651 break;
11652 }
Douglas Gregor882211c2010-04-28 22:16:22 +000011653 }
11654 }
Peter Collingbournee9200682011-05-13 03:29:01 +000011655 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011656}
11657
Chris Lattnere13042c2008-07-11 19:10:17 +000011658bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011659 switch (E->getOpcode()) {
11660 default:
11661 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11662 // See C99 6.6p3.
11663 return Error(E);
11664 case UO_Extension:
11665 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11666 // If so, we could clear the diagnostic ID.
11667 return Visit(E->getSubExpr());
11668 case UO_Plus:
11669 // The result is just the value.
11670 return Visit(E->getSubExpr());
11671 case UO_Minus: {
11672 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000011673 return false;
11674 if (!Result.isInt()) return Error(E);
11675 const APSInt &Value = Result.getInt();
11676 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11677 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11678 E->getType()))
11679 return false;
Richard Smithfe800032012-01-31 04:08:20 +000011680 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011681 }
11682 case UO_Not: {
11683 if (!Visit(E->getSubExpr()))
11684 return false;
11685 if (!Result.isInt()) return Error(E);
11686 return Success(~Result.getInt(), E);
11687 }
11688 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000011689 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000011690 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000011691 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000011692 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000011693 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011694 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011695}
Mike Stump11289f42009-09-09 15:08:12 +000011696
Chris Lattner477c4be2008-07-12 01:15:53 +000011697/// HandleCast - This is used to evaluate implicit or explicit casts where the
11698/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000011699bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11700 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011701 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000011702 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011703
Eli Friedmanc757de22011-03-25 00:43:55 +000011704 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000011705 case CK_BaseToDerived:
11706 case CK_DerivedToBase:
11707 case CK_UncheckedDerivedToBase:
11708 case CK_Dynamic:
11709 case CK_ToUnion:
11710 case CK_ArrayToPointerDecay:
11711 case CK_FunctionToPointerDecay:
11712 case CK_NullToPointer:
11713 case CK_NullToMemberPointer:
11714 case CK_BaseToDerivedMemberPointer:
11715 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000011716 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000011717 case CK_ConstructorConversion:
11718 case CK_IntegralToPointer:
11719 case CK_ToVoid:
11720 case CK_VectorSplat:
11721 case CK_IntegralToFloating:
11722 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011723 case CK_CPointerToObjCPointerCast:
11724 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011725 case CK_AnyPointerToBlockPointerCast:
11726 case CK_ObjCObjectLValueCast:
11727 case CK_FloatingRealToComplex:
11728 case CK_FloatingComplexToReal:
11729 case CK_FloatingComplexCast:
11730 case CK_FloatingComplexToIntegralComplex:
11731 case CK_IntegralRealToComplex:
11732 case CK_IntegralComplexCast:
11733 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000011734 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011735 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011736 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011737 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011738 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011739 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011740 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000011741 llvm_unreachable("invalid cast kind for integral value");
11742
Eli Friedman9faf2f92011-03-25 19:07:11 +000011743 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011744 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011745 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000011746 case CK_ARCProduceObject:
11747 case CK_ARCConsumeObject:
11748 case CK_ARCReclaimReturnedObject:
11749 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011750 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011751 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011752
Richard Smith4ef685b2012-01-17 21:17:26 +000011753 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000011754 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011755 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000011756 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011757 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011758 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011759
11760 case CK_MemberPointerToBoolean:
11761 case CK_PointerToBoolean:
11762 case CK_IntegralToBoolean:
11763 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011764 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000011765 case CK_FloatingComplexToBoolean:
11766 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011767 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000011768 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000011769 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000011770 uint64_t IntResult = BoolResult;
11771 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11772 IntResult = (uint64_t)-1;
11773 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011774 }
11775
Leonard Chan8f7caae2019-03-06 00:28:43 +000011776 case CK_FixedPointToIntegral: {
11777 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11778 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11779 return false;
11780 bool Overflowed;
11781 llvm::APSInt Result = Src.convertToInt(
11782 Info.Ctx.getIntWidth(DestType),
11783 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11784 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11785 return false;
11786 return Success(Result, E);
11787 }
11788
Leonard Chanb4ba4672018-10-23 17:55:35 +000011789 case CK_FixedPointToBoolean: {
11790 // Unsigned padding does not affect this.
11791 APValue Val;
11792 if (!Evaluate(Val, Info, SubExpr))
11793 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011794 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000011795 }
11796
Eli Friedmanc757de22011-03-25 00:43:55 +000011797 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000011798 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000011799 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000011800
Eli Friedman742421e2009-02-20 01:15:07 +000011801 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000011802 // Allow casts of address-of-label differences if they are no-ops
11803 // or narrowing. (The narrowing case isn't actually guaranteed to
11804 // be constant-evaluatable except in some narrow cases which are hard
11805 // to detect here. We let it through on the assumption the user knows
11806 // what they are doing.)
11807 if (Result.isAddrLabelDiff())
11808 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000011809 // Only allow casts of lvalues if they are lossless.
11810 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11811 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000011812
Richard Smith911e1422012-01-30 22:27:01 +000011813 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11814 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000011815 }
Mike Stump11289f42009-09-09 15:08:12 +000011816
Eli Friedmanc757de22011-03-25 00:43:55 +000011817 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000011818 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11819
John McCall45d55e42010-05-07 21:00:08 +000011820 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000011821 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000011822 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000011823
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011824 if (LV.getLValueBase()) {
11825 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000011826 // FIXME: Allow a larger integer size than the pointer size, and allow
11827 // narrowing back down to pointer width in subsequent integral casts.
11828 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011829 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011830 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011831
Richard Smithcf74da72011-11-16 07:18:12 +000011832 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000011833 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011834 return true;
11835 }
11836
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000011837 APSInt AsInt;
11838 APValue V;
11839 LV.moveInto(V);
11840 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11841 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000011842
Richard Smith911e1422012-01-30 22:27:01 +000011843 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011844 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011845
Eli Friedmanc757de22011-03-25 00:43:55 +000011846 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000011847 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011848 if (!EvaluateComplex(SubExpr, C, Info))
11849 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000011850 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011851 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000011852
Eli Friedmanc757de22011-03-25 00:43:55 +000011853 case CK_FloatingToIntegral: {
11854 APFloat F(0.0);
11855 if (!EvaluateFloat(SubExpr, F, Info))
11856 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000011857
Richard Smith357362d2011-12-13 06:39:58 +000011858 APSInt Value;
11859 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11860 return false;
11861 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011862 }
11863 }
Mike Stump11289f42009-09-09 15:08:12 +000011864
Eli Friedmanc757de22011-03-25 00:43:55 +000011865 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000011866}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011867
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011868bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11869 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011870 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011871 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11872 return false;
11873 if (!LV.isComplexInt())
11874 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011875 return Success(LV.getComplexIntReal(), E);
11876 }
11877
11878 return Visit(E->getSubExpr());
11879}
11880
Eli Friedman4e7a2412009-02-27 04:45:43 +000011881bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011882 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011883 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011884 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11885 return false;
11886 if (!LV.isComplexInt())
11887 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011888 return Success(LV.getComplexIntImag(), E);
11889 }
11890
Richard Smith4a678122011-10-24 18:44:57 +000011891 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000011892 return Success(0, E);
11893}
11894
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011895bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11896 return Success(E->getPackLength(), E);
11897}
11898
Sebastian Redl5f0180d2010-09-10 20:55:47 +000011899bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11900 return Success(E->getValue(), E);
11901}
11902
Leonard Chandb01c3a2018-06-20 17:19:40 +000011903bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11904 switch (E->getOpcode()) {
11905 default:
11906 // Invalid unary operators
11907 return Error(E);
11908 case UO_Plus:
11909 // The result is just the value.
11910 return Visit(E->getSubExpr());
11911 case UO_Minus: {
11912 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011913 if (!Result.isFixedPoint())
11914 return Error(E);
11915 bool Overflowed;
11916 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11917 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11918 return false;
11919 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011920 }
11921 case UO_LNot: {
11922 bool bres;
11923 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11924 return false;
11925 return Success(!bres, E);
11926 }
11927 }
11928}
11929
Leonard Chand3f3e162019-01-18 21:04:25 +000011930bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11931 const Expr *SubExpr = E->getSubExpr();
11932 QualType DestType = E->getType();
11933 assert(DestType->isFixedPointType() &&
11934 "Expected destination type to be a fixed point type");
11935 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11936
11937 switch (E->getCastKind()) {
11938 case CK_FixedPointCast: {
11939 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11940 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11941 return false;
11942 bool Overflowed;
11943 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11944 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11945 return false;
11946 return Success(Result, E);
11947 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011948 case CK_IntegralToFixedPoint: {
11949 APSInt Src;
11950 if (!EvaluateInteger(SubExpr, Src, Info))
11951 return false;
11952
11953 bool Overflowed;
11954 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11955 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11956
11957 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11958 return false;
11959
11960 return Success(IntResult, E);
11961 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011962 case CK_NoOp:
11963 case CK_LValueToRValue:
11964 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11965 default:
11966 return Error(E);
11967 }
11968}
11969
11970bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11971 const Expr *LHS = E->getLHS();
11972 const Expr *RHS = E->getRHS();
11973 FixedPointSemantics ResultFXSema =
11974 Info.Ctx.getFixedPointSemantics(E->getType());
11975
11976 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11977 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11978 return false;
11979 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11980 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11981 return false;
11982
11983 switch (E->getOpcode()) {
11984 case BO_Add: {
11985 bool AddOverflow, ConversionOverflow;
11986 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11987 .convert(ResultFXSema, &ConversionOverflow);
11988 if ((AddOverflow || ConversionOverflow) &&
11989 !HandleOverflow(Info, E, Result, E->getType()))
11990 return false;
11991 return Success(Result, E);
11992 }
11993 default:
11994 return false;
11995 }
11996 llvm_unreachable("Should've exited before this");
11997}
11998
Chris Lattner05706e882008-07-11 18:11:29 +000011999//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000012000// Float Evaluation
12001//===----------------------------------------------------------------------===//
12002
12003namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012004class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012005 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000012006 APFloat &Result;
12007public:
12008 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012009 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000012010
Richard Smith2e312c82012-03-03 22:46:17 +000012011 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012012 Result = V.getFloat();
12013 return true;
12014 }
Eli Friedman24c01542008-08-22 00:06:13 +000012015
Richard Smithfddd3842011-12-30 21:15:51 +000012016 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000012017 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12018 return true;
12019 }
12020
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012021 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012022
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012023 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012024 bool VisitBinaryOperator(const BinaryOperator *E);
12025 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012026 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000012027
John McCallb1fb0d32010-05-07 22:08:54 +000012028 bool VisitUnaryReal(const UnaryOperator *E);
12029 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000012030
Richard Smithfddd3842011-12-30 21:15:51 +000012031 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000012032};
12033} // end anonymous namespace
12034
12035static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012036 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012037 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000012038}
12039
Jay Foad39c79802011-01-12 09:06:06 +000012040static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000012041 QualType ResultTy,
12042 const Expr *Arg,
12043 bool SNaN,
12044 llvm::APFloat &Result) {
12045 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12046 if (!S) return false;
12047
12048 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12049
12050 llvm::APInt fill;
12051
12052 // Treat empty strings as if they were zero.
12053 if (S->getString().empty())
12054 fill = llvm::APInt(32, 0);
12055 else if (S->getString().getAsInteger(0, fill))
12056 return false;
12057
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000012058 if (Context.getTargetInfo().isNan2008()) {
12059 if (SNaN)
12060 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12061 else
12062 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12063 } else {
12064 // Prior to IEEE 754-2008, architectures were allowed to choose whether
12065 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12066 // a different encoding to what became a standard in 2008, and for pre-
12067 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12068 // sNaN. This is now known as "legacy NaN" encoding.
12069 if (SNaN)
12070 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12071 else
12072 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12073 }
12074
John McCall16291492010-02-28 13:00:19 +000012075 return true;
12076}
12077
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012078bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000012079 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012080 default:
12081 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12082
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012083 case Builtin::BI__builtin_huge_val:
12084 case Builtin::BI__builtin_huge_valf:
12085 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012086 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012087 case Builtin::BI__builtin_inf:
12088 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012089 case Builtin::BI__builtin_infl:
12090 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012091 const llvm::fltSemantics &Sem =
12092 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000012093 Result = llvm::APFloat::getInf(Sem);
12094 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012095 }
Mike Stump11289f42009-09-09 15:08:12 +000012096
John McCall16291492010-02-28 13:00:19 +000012097 case Builtin::BI__builtin_nans:
12098 case Builtin::BI__builtin_nansf:
12099 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012100 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012101 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12102 true, Result))
12103 return Error(E);
12104 return true;
John McCall16291492010-02-28 13:00:19 +000012105
Chris Lattner0b7282e2008-10-06 06:31:58 +000012106 case Builtin::BI__builtin_nan:
12107 case Builtin::BI__builtin_nanf:
12108 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012109 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000012110 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000012111 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000012112 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12113 false, Result))
12114 return Error(E);
12115 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012116
12117 case Builtin::BI__builtin_fabs:
12118 case Builtin::BI__builtin_fabsf:
12119 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012120 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012121 if (!EvaluateFloat(E->getArg(0), Result, Info))
12122 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012123
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012124 if (Result.isNegative())
12125 Result.changeSign();
12126 return true;
12127
Richard Smith8889a3d2013-06-13 06:26:32 +000012128 // FIXME: Builtin::BI__builtin_powi
12129 // FIXME: Builtin::BI__builtin_powif
12130 // FIXME: Builtin::BI__builtin_powil
12131
Mike Stump11289f42009-09-09 15:08:12 +000012132 case Builtin::BI__builtin_copysign:
12133 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012134 case Builtin::BI__builtin_copysignl:
12135 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012136 APFloat RHS(0.);
12137 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12138 !EvaluateFloat(E->getArg(1), RHS, Info))
12139 return false;
12140 Result.copySign(RHS);
12141 return true;
12142 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012143 }
12144}
12145
John McCallb1fb0d32010-05-07 22:08:54 +000012146bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012147 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12148 ComplexValue CV;
12149 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12150 return false;
12151 Result = CV.FloatReal;
12152 return true;
12153 }
12154
12155 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000012156}
12157
12158bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012159 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12160 ComplexValue CV;
12161 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12162 return false;
12163 Result = CV.FloatImag;
12164 return true;
12165 }
12166
Richard Smith4a678122011-10-24 18:44:57 +000012167 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000012168 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12169 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000012170 return true;
12171}
12172
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012173bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012174 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012175 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012176 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000012177 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000012178 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000012179 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12180 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012181 Result.changeSign();
12182 return true;
12183 }
12184}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012185
Eli Friedman24c01542008-08-22 00:06:13 +000012186bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012187 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12188 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000012189
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012190 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000012191 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000012192 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000012193 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000012194 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12195 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000012196}
12197
12198bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12199 Result = E->getValue();
12200 return true;
12201}
12202
Peter Collingbournee9200682011-05-13 03:29:01 +000012203bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12204 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000012205
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012206 switch (E->getCastKind()) {
12207 default:
Richard Smith11562c52011-10-28 17:51:58 +000012208 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012209
12210 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012211 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000012212 return EvaluateInteger(SubExpr, IntResult, Info) &&
12213 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12214 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012215 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012216
12217 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012218 if (!Visit(SubExpr))
12219 return false;
Richard Smith357362d2011-12-13 06:39:58 +000012220 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12221 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012222 }
John McCalld7646252010-11-14 08:17:51 +000012223
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012224 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000012225 ComplexValue V;
12226 if (!EvaluateComplex(SubExpr, V, Info))
12227 return false;
12228 Result = V.getComplexFloatReal();
12229 return true;
12230 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012231 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012232}
12233
Eli Friedman24c01542008-08-22 00:06:13 +000012234//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012235// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000012236//===----------------------------------------------------------------------===//
12237
12238namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012239class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012240 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000012241 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000012242
Anders Carlsson537969c2008-11-16 20:27:53 +000012243public:
John McCall93d91dc2010-05-07 17:22:02 +000012244 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012245 : ExprEvaluatorBaseTy(info), Result(Result) {}
12246
Richard Smith2e312c82012-03-03 22:46:17 +000012247 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012248 Result.setFrom(V);
12249 return true;
12250 }
Mike Stump11289f42009-09-09 15:08:12 +000012251
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012252 bool ZeroInitialization(const Expr *E);
12253
Anders Carlsson537969c2008-11-16 20:27:53 +000012254 //===--------------------------------------------------------------------===//
12255 // Visitor Methods
12256 //===--------------------------------------------------------------------===//
12257
Peter Collingbournee9200682011-05-13 03:29:01 +000012258 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012259 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000012260 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012261 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012262 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012263};
12264} // end anonymous namespace
12265
John McCall93d91dc2010-05-07 17:22:02 +000012266static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12267 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012268 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012269 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012270}
12271
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012272bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000012273 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012274 if (ElemTy->isRealFloatingType()) {
12275 Result.makeComplexFloat();
12276 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12277 Result.FloatReal = Zero;
12278 Result.FloatImag = Zero;
12279 } else {
12280 Result.makeComplexInt();
12281 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12282 Result.IntReal = Zero;
12283 Result.IntImag = Zero;
12284 }
12285 return true;
12286}
12287
Peter Collingbournee9200682011-05-13 03:29:01 +000012288bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12289 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012290
12291 if (SubExpr->getType()->isRealFloatingType()) {
12292 Result.makeComplexFloat();
12293 APFloat &Imag = Result.FloatImag;
12294 if (!EvaluateFloat(SubExpr, Imag, Info))
12295 return false;
12296
12297 Result.FloatReal = APFloat(Imag.getSemantics());
12298 return true;
12299 } else {
12300 assert(SubExpr->getType()->isIntegerType() &&
12301 "Unexpected imaginary literal.");
12302
12303 Result.makeComplexInt();
12304 APSInt &Imag = Result.IntImag;
12305 if (!EvaluateInteger(SubExpr, Imag, Info))
12306 return false;
12307
12308 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12309 return true;
12310 }
12311}
12312
Peter Collingbournee9200682011-05-13 03:29:01 +000012313bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012314
John McCallfcef3cf2010-12-14 17:51:41 +000012315 switch (E->getCastKind()) {
12316 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012317 case CK_BaseToDerived:
12318 case CK_DerivedToBase:
12319 case CK_UncheckedDerivedToBase:
12320 case CK_Dynamic:
12321 case CK_ToUnion:
12322 case CK_ArrayToPointerDecay:
12323 case CK_FunctionToPointerDecay:
12324 case CK_NullToPointer:
12325 case CK_NullToMemberPointer:
12326 case CK_BaseToDerivedMemberPointer:
12327 case CK_DerivedToBaseMemberPointer:
12328 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000012329 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000012330 case CK_ConstructorConversion:
12331 case CK_IntegralToPointer:
12332 case CK_PointerToIntegral:
12333 case CK_PointerToBoolean:
12334 case CK_ToVoid:
12335 case CK_VectorSplat:
12336 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012337 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000012338 case CK_IntegralToBoolean:
12339 case CK_IntegralToFloating:
12340 case CK_FloatingToIntegral:
12341 case CK_FloatingToBoolean:
12342 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000012343 case CK_CPointerToObjCPointerCast:
12344 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012345 case CK_AnyPointerToBlockPointerCast:
12346 case CK_ObjCObjectLValueCast:
12347 case CK_FloatingComplexToReal:
12348 case CK_FloatingComplexToBoolean:
12349 case CK_IntegralComplexToReal:
12350 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000012351 case CK_ARCProduceObject:
12352 case CK_ARCConsumeObject:
12353 case CK_ARCReclaimReturnedObject:
12354 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012355 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000012356 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012357 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012358 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012359 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012360 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012361 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000012362 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012363 case CK_FixedPointToIntegral:
12364 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000012365 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000012366
John McCallfcef3cf2010-12-14 17:51:41 +000012367 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012368 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000012369 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012370 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012371 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012372
12373 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012374 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012375 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012376 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012377
12378 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012379 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000012380 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012381 return false;
12382
John McCallfcef3cf2010-12-14 17:51:41 +000012383 Result.makeComplexFloat();
12384 Result.FloatImag = APFloat(Real.getSemantics());
12385 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012386 }
12387
John McCallfcef3cf2010-12-14 17:51:41 +000012388 case CK_FloatingComplexCast: {
12389 if (!Visit(E->getSubExpr()))
12390 return false;
12391
12392 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12393 QualType From
12394 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12395
Richard Smith357362d2011-12-13 06:39:58 +000012396 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
12397 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012398 }
12399
12400 case CK_FloatingComplexToIntegralComplex: {
12401 if (!Visit(E->getSubExpr()))
12402 return false;
12403
12404 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12405 QualType From
12406 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12407 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000012408 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12409 To, Result.IntReal) &&
12410 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12411 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012412 }
12413
12414 case CK_IntegralRealToComplex: {
12415 APSInt &Real = Result.IntReal;
12416 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12417 return false;
12418
12419 Result.makeComplexInt();
12420 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12421 return true;
12422 }
12423
12424 case CK_IntegralComplexCast: {
12425 if (!Visit(E->getSubExpr()))
12426 return false;
12427
12428 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12429 QualType From
12430 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12431
Richard Smith911e1422012-01-30 22:27:01 +000012432 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12433 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012434 return true;
12435 }
12436
12437 case CK_IntegralComplexToFloatingComplex: {
12438 if (!Visit(E->getSubExpr()))
12439 return false;
12440
Ted Kremenek28831752012-08-23 20:46:57 +000012441 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012442 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000012443 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012444 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000012445 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12446 To, Result.FloatReal) &&
12447 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12448 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012449 }
12450 }
12451
12452 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012453}
12454
John McCall93d91dc2010-05-07 17:22:02 +000012455bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012456 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000012457 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12458
Chandler Carrutha216cad2014-10-11 00:57:18 +000012459 // Track whether the LHS or RHS is real at the type system level. When this is
12460 // the case we can simplify our evaluation strategy.
12461 bool LHSReal = false, RHSReal = false;
12462
12463 bool LHSOK;
12464 if (E->getLHS()->getType()->isRealFloatingType()) {
12465 LHSReal = true;
12466 APFloat &Real = Result.FloatReal;
12467 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12468 if (LHSOK) {
12469 Result.makeComplexFloat();
12470 Result.FloatImag = APFloat(Real.getSemantics());
12471 }
12472 } else {
12473 LHSOK = Visit(E->getLHS());
12474 }
George Burgess IVa145e252016-05-25 22:38:36 +000012475 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000012476 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012477
John McCall93d91dc2010-05-07 17:22:02 +000012478 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012479 if (E->getRHS()->getType()->isRealFloatingType()) {
12480 RHSReal = true;
12481 APFloat &Real = RHS.FloatReal;
12482 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12483 return false;
12484 RHS.makeComplexFloat();
12485 RHS.FloatImag = APFloat(Real.getSemantics());
12486 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000012487 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012488
Chandler Carrutha216cad2014-10-11 00:57:18 +000012489 assert(!(LHSReal && RHSReal) &&
12490 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012491 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012492 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012493 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012494 if (Result.isComplexFloat()) {
12495 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12496 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012497 if (LHSReal)
12498 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12499 else if (!RHSReal)
12500 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12501 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012502 } else {
12503 Result.getComplexIntReal() += RHS.getComplexIntReal();
12504 Result.getComplexIntImag() += RHS.getComplexIntImag();
12505 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012506 break;
John McCalle3027922010-08-25 11:45:40 +000012507 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012508 if (Result.isComplexFloat()) {
12509 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12510 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012511 if (LHSReal) {
12512 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12513 Result.getComplexFloatImag().changeSign();
12514 } else if (!RHSReal) {
12515 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12516 APFloat::rmNearestTiesToEven);
12517 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012518 } else {
12519 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12520 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12521 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012522 break;
John McCalle3027922010-08-25 11:45:40 +000012523 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012524 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012525 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012526 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012527 // following naming scheme:
12528 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000012529 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012530 APFloat &A = LHS.getComplexFloatReal();
12531 APFloat &B = LHS.getComplexFloatImag();
12532 APFloat &C = RHS.getComplexFloatReal();
12533 APFloat &D = RHS.getComplexFloatImag();
12534 APFloat &ResR = Result.getComplexFloatReal();
12535 APFloat &ResI = Result.getComplexFloatImag();
12536 if (LHSReal) {
12537 assert(!RHSReal && "Cannot have two real operands for a complex op!");
12538 ResR = A * C;
12539 ResI = A * D;
12540 } else if (RHSReal) {
12541 ResR = C * A;
12542 ResI = C * B;
12543 } else {
12544 // In the fully general case, we need to handle NaNs and infinities
12545 // robustly.
12546 APFloat AC = A * C;
12547 APFloat BD = B * D;
12548 APFloat AD = A * D;
12549 APFloat BC = B * C;
12550 ResR = AC - BD;
12551 ResI = AD + BC;
12552 if (ResR.isNaN() && ResI.isNaN()) {
12553 bool Recalc = false;
12554 if (A.isInfinity() || B.isInfinity()) {
12555 A = APFloat::copySign(
12556 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12557 B = APFloat::copySign(
12558 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12559 if (C.isNaN())
12560 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12561 if (D.isNaN())
12562 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12563 Recalc = true;
12564 }
12565 if (C.isInfinity() || D.isInfinity()) {
12566 C = APFloat::copySign(
12567 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12568 D = APFloat::copySign(
12569 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12570 if (A.isNaN())
12571 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12572 if (B.isNaN())
12573 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12574 Recalc = true;
12575 }
12576 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12577 AD.isInfinity() || BC.isInfinity())) {
12578 if (A.isNaN())
12579 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12580 if (B.isNaN())
12581 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12582 if (C.isNaN())
12583 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12584 if (D.isNaN())
12585 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12586 Recalc = true;
12587 }
12588 if (Recalc) {
12589 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12590 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12591 }
12592 }
12593 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012594 } else {
John McCall93d91dc2010-05-07 17:22:02 +000012595 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000012596 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012597 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12598 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000012599 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012600 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12601 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12602 }
12603 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012604 case BO_Div:
12605 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012606 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012607 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012608 // following naming scheme:
12609 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012610 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012611 APFloat &A = LHS.getComplexFloatReal();
12612 APFloat &B = LHS.getComplexFloatImag();
12613 APFloat &C = RHS.getComplexFloatReal();
12614 APFloat &D = RHS.getComplexFloatImag();
12615 APFloat &ResR = Result.getComplexFloatReal();
12616 APFloat &ResI = Result.getComplexFloatImag();
12617 if (RHSReal) {
12618 ResR = A / C;
12619 ResI = B / C;
12620 } else {
12621 if (LHSReal) {
12622 // No real optimizations we can do here, stub out with zero.
12623 B = APFloat::getZero(A.getSemantics());
12624 }
12625 int DenomLogB = 0;
12626 APFloat MaxCD = maxnum(abs(C), abs(D));
12627 if (MaxCD.isFinite()) {
12628 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000012629 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
12630 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012631 }
12632 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000012633 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
12634 APFloat::rmNearestTiesToEven);
12635 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
12636 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012637 if (ResR.isNaN() && ResI.isNaN()) {
12638 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
12639 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
12640 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
12641 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
12642 D.isFinite()) {
12643 A = APFloat::copySign(
12644 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12645 B = APFloat::copySign(
12646 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12647 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
12648 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
12649 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
12650 C = APFloat::copySign(
12651 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12652 D = APFloat::copySign(
12653 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12654 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
12655 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12656 }
12657 }
12658 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012659 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012660 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12661 return Error(E, diag::note_expr_divide_by_zero);
12662
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012663 ComplexValue LHS = Result;
12664 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12665 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12666 Result.getComplexIntReal() =
12667 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12668 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12669 Result.getComplexIntImag() =
12670 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12671 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12672 }
12673 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012674 }
12675
John McCall93d91dc2010-05-07 17:22:02 +000012676 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012677}
12678
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012679bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12680 // Get the operand value into 'Result'.
12681 if (!Visit(E->getSubExpr()))
12682 return false;
12683
12684 switch (E->getOpcode()) {
12685 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012686 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012687 case UO_Extension:
12688 return true;
12689 case UO_Plus:
12690 // The result is always just the subexpr.
12691 return true;
12692 case UO_Minus:
12693 if (Result.isComplexFloat()) {
12694 Result.getComplexFloatReal().changeSign();
12695 Result.getComplexFloatImag().changeSign();
12696 }
12697 else {
12698 Result.getComplexIntReal() = -Result.getComplexIntReal();
12699 Result.getComplexIntImag() = -Result.getComplexIntImag();
12700 }
12701 return true;
12702 case UO_Not:
12703 if (Result.isComplexFloat())
12704 Result.getComplexFloatImag().changeSign();
12705 else
12706 Result.getComplexIntImag() = -Result.getComplexIntImag();
12707 return true;
12708 }
12709}
12710
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012711bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12712 if (E->getNumInits() == 2) {
12713 if (E->getType()->isComplexType()) {
12714 Result.makeComplexFloat();
12715 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12716 return false;
12717 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12718 return false;
12719 } else {
12720 Result.makeComplexInt();
12721 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12722 return false;
12723 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12724 return false;
12725 }
12726 return true;
12727 }
12728 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12729}
12730
Anders Carlsson537969c2008-11-16 20:27:53 +000012731//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000012732// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12733// implicit conversion.
12734//===----------------------------------------------------------------------===//
12735
12736namespace {
12737class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000012738 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012739 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000012740 APValue &Result;
12741public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012742 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12743 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000012744
12745 bool Success(const APValue &V, const Expr *E) {
12746 Result = V;
12747 return true;
12748 }
12749
12750 bool ZeroInitialization(const Expr *E) {
12751 ImplicitValueInitExpr VIE(
12752 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012753 // For atomic-qualified class (and array) types in C++, initialize the
12754 // _Atomic-wrapped subobject directly, in-place.
12755 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12756 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000012757 }
12758
12759 bool VisitCastExpr(const CastExpr *E) {
12760 switch (E->getCastKind()) {
12761 default:
12762 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12763 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012764 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12765 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000012766 }
12767 }
12768};
12769} // end anonymous namespace
12770
Richard Smith64cb9ca2017-02-22 22:09:50 +000012771static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12772 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000012773 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012774 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000012775}
12776
12777//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000012778// Void expression evaluation, primarily for a cast to void on the LHS of a
12779// comma operator
12780//===----------------------------------------------------------------------===//
12781
12782namespace {
12783class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012784 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000012785public:
12786 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12787
Richard Smith2e312c82012-03-03 22:46:17 +000012788 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000012789
Richard Smith7cd577b2017-08-17 19:35:50 +000012790 bool ZeroInitialization(const Expr *E) { return true; }
12791
Richard Smith42d3af92011-12-07 00:43:50 +000012792 bool VisitCastExpr(const CastExpr *E) {
12793 switch (E->getCastKind()) {
12794 default:
12795 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12796 case CK_ToVoid:
12797 VisitIgnoredValue(E->getSubExpr());
12798 return true;
12799 }
12800 }
Hal Finkela8443c32014-07-17 14:49:58 +000012801
12802 bool VisitCallExpr(const CallExpr *E) {
12803 switch (E->getBuiltinCallee()) {
12804 default:
12805 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12806 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000012807 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000012808 // The argument is not evaluated!
12809 return true;
12810 }
12811 }
Richard Smithda1b4342019-09-27 01:26:47 +000012812
12813 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
Richard Smith42d3af92011-12-07 00:43:50 +000012814};
12815} // end anonymous namespace
12816
Richard Smithda1b4342019-09-27 01:26:47 +000012817static bool hasVirtualDestructor(QualType T) {
12818 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
12819 if (CXXDestructorDecl *DD = RD->getDestructor())
12820 return DD->isVirtual();
12821 return false;
12822}
12823
12824bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
12825 // We cannot speculatively evaluate a delete expression.
12826 if (Info.SpeculativeEvaluationDepth)
12827 return false;
12828
12829 FunctionDecl *OperatorDelete = E->getOperatorDelete();
12830 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
12831 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
12832 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
12833 return false;
12834 }
12835
12836 const Expr *Arg = E->getArgument();
12837
12838 LValue Pointer;
12839 if (!EvaluatePointer(Arg, Pointer, Info))
12840 return false;
12841 if (Pointer.Designator.Invalid)
12842 return false;
12843
12844 // Deleting a null pointer has no effect.
12845 if (Pointer.isNullPointer()) {
12846 // This is the only case where we need to produce an extension warning:
12847 // the only other way we can succeed is if we find a dynamic allocation,
12848 // and we will have warned when we allocated it in that case.
12849 if (!Info.getLangOpts().CPlusPlus2a)
12850 Info.CCEDiag(E, diag::note_constexpr_new);
12851 return true;
12852 }
12853
12854 auto PointerAsString = [&] {
12855 APValue Printable;
12856 Pointer.moveInto(Printable);
12857 return Printable.getAsString(Info.Ctx, Arg->getType());
12858 };
12859
12860 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
12861 if (!DA) {
12862 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
12863 << PointerAsString();
12864 if (Pointer.Base)
12865 NoteLValueLocation(Info, Pointer.Base);
12866 return false;
12867 }
12868 QualType AllocType = Pointer.Base.getDynamicAllocType();
12869
12870 Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
12871 if (!Alloc) {
12872 Info.FFDiag(E, diag::note_constexpr_double_delete);
12873 return false;
12874 }
12875
12876 if (E->isArrayForm() != AllocType->isConstantArrayType()) {
12877 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
12878 << E->isArrayForm() << AllocType;
12879 NoteLValueLocation(Info, Pointer.Base);
12880 return false;
12881 }
12882
12883 bool Subobject = false;
12884 if (E->isArrayForm()) {
12885 Subobject = Pointer.Designator.Entries.size() != 1 ||
12886 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
12887 } else {
12888 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
12889 Pointer.Designator.isOnePastTheEnd();
12890 }
12891 if (Subobject) {
12892 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
12893 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
12894 return false;
12895 }
12896
12897 // For the non-array case, the designator must be empty if the static type
12898 // does not have a virtual destructor.
12899 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
12900 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
12901 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
12902 << Arg->getType()->getPointeeType() << AllocType;
12903 return false;
12904 }
12905
Richard Smith61422f92019-09-27 20:24:36 +000012906 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
12907 (*Alloc)->Value, AllocType))
Richard Smithda1b4342019-09-27 01:26:47 +000012908 return false;
12909
12910 if (!Info.HeapAllocs.erase(DA)) {
12911 // The element was already erased. This means the destructor call also
12912 // deleted the object.
12913 // FIXME: This probably results in undefined behavior before we get this
12914 // far, and should be diagnosed elsewhere first.
12915 Info.FFDiag(E, diag::note_constexpr_double_delete);
12916 return false;
12917 }
12918
12919 return true;
12920}
12921
Richard Smith42d3af92011-12-07 00:43:50 +000012922static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12923 assert(E->isRValue() && E->getType()->isVoidType());
12924 return VoidExprEvaluator(Info).Visit(E);
12925}
12926
12927//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000012928// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000012929//===----------------------------------------------------------------------===//
12930
Richard Smith2e312c82012-03-03 22:46:17 +000012931static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000012932 // In C, function designators are not lvalues, but we evaluate them as if they
12933 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000012934 QualType T = E->getType();
12935 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000012936 LValue LV;
12937 if (!EvaluateLValue(E, LV, Info))
12938 return false;
12939 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012940 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012941 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000012942 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012943 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012944 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012945 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012946 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000012947 LValue LV;
12948 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012949 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012950 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012951 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000012952 llvm::APFloat F(0.0);
12953 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012954 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000012955 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000012956 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000012957 ComplexValue C;
12958 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012959 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012960 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012961 } else if (T->isFixedPointType()) {
12962 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012963 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000012964 MemberPtr P;
12965 if (!EvaluateMemberPointer(E, P, Info))
12966 return false;
12967 P.moveInto(Result);
12968 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000012969 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012970 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012971 APValue &Value =
12972 Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012973 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000012974 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012975 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012976 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012977 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012978 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012979 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000012980 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012981 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012982 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012983 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000012984 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000012985 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000012986 if (!EvaluateVoid(E, Info))
12987 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012988 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012989 QualType Unqual = T.getAtomicUnqualifiedType();
12990 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12991 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012992 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012993 if (!EvaluateAtomic(E, &LV, Value, Info))
12994 return false;
12995 } else {
12996 if (!EvaluateAtomic(E, nullptr, Result, Info))
12997 return false;
12998 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012999 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000013000 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000013001 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013002 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000013003 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000013004 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013005 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013006
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000013007 return true;
13008}
13009
Richard Smithb228a862012-02-15 02:18:13 +000013010/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13011/// cases, the in-place evaluation is essential, since later initializers for
13012/// an object can indirectly refer to subobjects which were initialized earlier.
13013static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000013014 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000013015 assert(!E->isValueDependent());
13016
Richard Smith7525ff62013-05-09 07:14:00 +000013017 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000013018 return false;
13019
13020 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000013021 // Evaluate arrays and record types in-place, so that later initializers can
13022 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000013023 QualType T = E->getType();
13024 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000013025 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013026 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000013027 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013028 else if (T->isAtomicType()) {
13029 QualType Unqual = T.getAtomicUnqualifiedType();
13030 if (Unqual->isArrayType() || Unqual->isRecordType())
13031 return EvaluateAtomic(E, &This, Result, Info);
13032 }
Richard Smithed5165f2011-11-04 05:33:44 +000013033 }
13034
13035 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000013036 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000013037}
13038
Richard Smithf57d8cb2011-12-09 22:58:01 +000013039/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13040/// lvalue-to-rvalue cast if it is an lvalue.
13041static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Licker950b70d2019-09-13 09:46:16 +000013042 if (Info.EnableNewConstInterp) {
13043 auto &InterpCtx = Info.Ctx.getInterpContext();
13044 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
13045 case interp::InterpResult::Success:
13046 return true;
13047 case interp::InterpResult::Fail:
13048 return false;
13049 case interp::InterpResult::Bail:
13050 break;
13051 }
13052 }
13053
James Dennett0492ef02014-03-14 17:44:10 +000013054 if (E->getType().isNull())
13055 return false;
13056
Nick Lewyckyc190f962017-05-02 01:06:16 +000013057 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000013058 return false;
13059
Richard Smith2e312c82012-03-03 22:46:17 +000013060 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000013061 return false;
13062
13063 if (E->isGLValue()) {
13064 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000013065 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000013066 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000013067 return false;
13068 }
13069
Richard Smith2e312c82012-03-03 22:46:17 +000013070 // Check this core constant expression is a constant expression.
Richard Smithda1b4342019-09-27 01:26:47 +000013071 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13072 CheckMemoryLeaks(Info);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013073}
Richard Smith11562c52011-10-28 17:51:58 +000013074
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013075static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000013076 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013077 // Fast-path evaluations of integer literals, since we sometimes see files
13078 // containing vast quantities of these.
13079 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13080 Result.Val = APValue(APSInt(L->getValue(),
13081 L->getType()->isUnsignedIntegerType()));
13082 IsConst = true;
13083 return true;
13084 }
James Dennett0492ef02014-03-14 17:44:10 +000013085
13086 // This case should be rare, but we need to check it before we check on
13087 // the type below.
13088 if (Exp->getType().isNull()) {
13089 IsConst = false;
13090 return true;
13091 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013092
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013093 // FIXME: Evaluating values of large array and record types can cause
13094 // performance problems. Only do so in C++11 for now.
13095 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13096 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000013097 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013098 IsConst = false;
13099 return true;
13100 }
13101 return false;
13102}
13103
Fangrui Song407659a2018-11-30 23:41:18 +000013104static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13105 Expr::SideEffectsKind SEK) {
13106 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13107 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13108}
13109
13110static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13111 const ASTContext &Ctx, EvalInfo &Info) {
13112 bool IsConst;
13113 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13114 return IsConst;
13115
13116 return EvaluateAsRValue(Info, E, Result.Val);
13117}
13118
13119static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13120 const ASTContext &Ctx,
13121 Expr::SideEffectsKind AllowSideEffects,
13122 EvalInfo &Info) {
13123 if (!E->getType()->isIntegralOrEnumerationType())
13124 return false;
13125
13126 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13127 !ExprResult.Val.isInt() ||
13128 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13129 return false;
13130
13131 return true;
13132}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013133
Leonard Chand3f3e162019-01-18 21:04:25 +000013134static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13135 const ASTContext &Ctx,
13136 Expr::SideEffectsKind AllowSideEffects,
13137 EvalInfo &Info) {
13138 if (!E->getType()->isFixedPointType())
13139 return false;
13140
13141 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13142 return false;
13143
13144 if (!ExprResult.Val.isFixedPoint() ||
13145 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13146 return false;
13147
13148 return true;
13149}
13150
Richard Smith7b553f12011-10-29 00:50:52 +000013151/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000013152/// any crazy technique (that has nothing to do with language standards) that
13153/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000013154/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13155/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000013156bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13157 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013158 assert(!isValueDependent() &&
13159 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000013160 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013161 Info.InConstantContext = InConstantContext;
13162 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000013163}
13164
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013165bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13166 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013167 assert(!isValueDependent() &&
13168 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000013169 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013170 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000013171 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000013172}
13173
Fangrui Song407659a2018-11-30 23:41:18 +000013174bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013175 SideEffectsKind AllowSideEffects,
13176 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013177 assert(!isValueDependent() &&
13178 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000013179 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013180 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000013181 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000013182}
13183
Leonard Chand3f3e162019-01-18 21:04:25 +000013184bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013185 SideEffectsKind AllowSideEffects,
13186 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013187 assert(!isValueDependent() &&
13188 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000013189 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013190 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000013191 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13192}
13193
Richard Trieube234c32016-04-21 21:04:55 +000013194bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013195 SideEffectsKind AllowSideEffects,
13196 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013197 assert(!isValueDependent() &&
13198 "Expression evaluator can't be called on a dependent expression.");
13199
Richard Trieube234c32016-04-21 21:04:55 +000013200 if (!getType()->isRealFloatingType())
13201 return false;
13202
13203 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013204 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13205 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000013206 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000013207 return false;
13208
13209 Result = ExprResult.Val.getFloat();
13210 return true;
13211}
13212
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013213bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13214 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013215 assert(!isValueDependent() &&
13216 "Expression evaluator can't be called on a dependent expression.");
13217
Richard Smith6d4c6582013-11-05 22:18:15 +000013218 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013219 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000013220 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013221 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13222 Result.HasSideEffects ||
Richard Smithb228a862012-02-15 02:18:13 +000013223 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000013224 Ctx.getLValueReferenceType(getType()), LV,
13225 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000013226 return false;
13227
Richard Smith2e312c82012-03-03 22:46:17 +000013228 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000013229 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000013230}
13231
Reid Kleckner1a840d22018-05-10 18:57:35 +000013232bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13233 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013234 assert(!isValueDependent() &&
13235 "Expression evaluator can't be called on a dependent expression.");
13236
Reid Kleckner1a840d22018-05-10 18:57:35 +000013237 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13238 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000013239 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000013240
Richard Smithda1b4342019-09-27 01:26:47 +000013241 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
Reid Kleckner1a840d22018-05-10 18:57:35 +000013242 return false;
13243
Richard Smith457226e2019-09-23 03:48:44 +000013244 if (!Info.discardCleanups())
13245 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13246
Reid Kleckner1a840d22018-05-10 18:57:35 +000013247 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
Richard Smithda1b4342019-09-27 01:26:47 +000013248 Usage) &&
13249 CheckMemoryLeaks(Info);
Reid Kleckner1a840d22018-05-10 18:57:35 +000013250}
13251
Richard Smithd0b4dd62011-12-19 06:19:21 +000013252bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13253 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013254 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013255 assert(!isValueDependent() &&
13256 "Expression evaluator can't be called on a dependent expression.");
13257
Richard Smithdafff942012-01-14 04:30:29 +000013258 // FIXME: Evaluating initializers for large array and record types can cause
13259 // performance problems. Only do so in C++11 for now.
13260 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013261 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000013262 return false;
13263
Richard Smithd0b4dd62011-12-19 06:19:21 +000013264 Expr::EvalStatus EStatus;
13265 EStatus.Diag = &Notes;
13266
Nandor Licker950b70d2019-09-13 09:46:16 +000013267 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000013268 ? EvalInfo::EM_ConstantExpression
13269 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000013270 Info.setEvaluatingDecl(VD, Value);
13271 Info.InConstantContext = true;
13272
13273 SourceLocation DeclLoc = VD->getLocation();
13274 QualType DeclTy = VD->getType();
13275
13276 if (Info.EnableNewConstInterp) {
13277 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13278 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
13279 case interp::InterpResult::Fail:
13280 // Bail out if an error was encountered.
13281 return false;
13282 case interp::InterpResult::Success:
13283 // Evaluation succeeded and value was set.
13284 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
13285 case interp::InterpResult::Bail:
13286 // Evaluate the value again for the tree evaluator to use.
13287 break;
13288 }
13289 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000013290
13291 LValue LVal;
13292 LVal.set(VD);
13293
Richard Smithfddd3842011-12-30 21:15:51 +000013294 // C++11 [basic.start.init]p2:
13295 // Variables with static storage duration or thread storage duration shall be
13296 // zero-initialized before any other initialization takes place.
13297 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013298 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Nandor Licker950b70d2019-09-13 09:46:16 +000013299 !DeclTy->isReferenceType()) {
13300 ImplicitValueInitExpr VIE(DeclTy);
13301 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000013302 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000013303 return false;
13304 }
13305
Nandor Licker950b70d2019-09-13 09:46:16 +000013306 if (!EvaluateInPlace(Value, Info, LVal, this,
Richard Smith7525ff62013-05-09 07:14:00 +000013307 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000013308 EStatus.HasSideEffects)
13309 return false;
13310
Richard Smith457226e2019-09-23 03:48:44 +000013311 // At this point, any lifetime-extended temporaries are completely
13312 // initialized.
13313 Info.performLifetimeExtension();
13314
13315 if (!Info.discardCleanups())
13316 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13317
Richard Smithda1b4342019-09-27 01:26:47 +000013318 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13319 CheckMemoryLeaks(Info);
Richard Smithd0b4dd62011-12-19 06:19:21 +000013320}
13321
Richard Smith2b4fa532019-09-29 05:08:46 +000013322bool VarDecl::evaluateDestruction(
13323 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13324 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
13325 "cannot evaluate destruction of non-constant-initialized variable");
13326
13327 Expr::EvalStatus EStatus;
13328 EStatus.Diag = &Notes;
13329
13330 // Make a copy of the value for the destructor to mutate.
13331 APValue DestroyedValue = *getEvaluatedValue();
13332
13333 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13334 Info.setEvaluatingDecl(this, DestroyedValue,
13335 EvalInfo::EvaluatingDeclKind::Dtor);
13336 Info.InConstantContext = true;
13337
13338 SourceLocation DeclLoc = getLocation();
13339 QualType DeclTy = getType();
13340
13341 LValue LVal;
13342 LVal.set(this);
13343
13344 // FIXME: Consider storing whether this variable has constant destruction in
13345 // the EvaluatedStmt so that CodeGen can query it.
13346 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13347 EStatus.HasSideEffects)
13348 return false;
13349
13350 if (!Info.discardCleanups())
13351 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13352
13353 ensureEvaluatedStmt()->HasConstantDestruction = true;
13354 return true;
13355}
13356
Richard Smith7b553f12011-10-29 00:50:52 +000013357/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13358/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000013359bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013360 assert(!isValueDependent() &&
13361 "Expression evaluator can't be called on a dependent expression.");
13362
Anders Carlsson5b3638b2008-12-01 06:44:05 +000013363 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000013364 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000013365 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000013366}
Anders Carlsson59689ed2008-11-22 21:04:56 +000013367
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000013368APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013369 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013370 assert(!isValueDependent() &&
13371 "Expression evaluator can't be called on a dependent expression.");
13372
Fangrui Song407659a2018-11-30 23:41:18 +000013373 EvalResult EVResult;
13374 EVResult.Diag = Diag;
13375 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13376 Info.InConstantContext = true;
13377
13378 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000013379 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000013380 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013381 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000013382
Fangrui Song407659a2018-11-30 23:41:18 +000013383 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000013384}
John McCall864e3962010-05-07 05:32:02 +000013385
David Bolvansky3b6ae572018-10-18 20:49:06 +000013386APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13387 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013388 assert(!isValueDependent() &&
13389 "Expression evaluator can't be called on a dependent expression.");
13390
Fangrui Song407659a2018-11-30 23:41:18 +000013391 EvalResult EVResult;
13392 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000013393 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013394 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013395 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013396
13397 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000013398 (void)Result;
13399 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013400 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000013401
Fangrui Song407659a2018-11-30 23:41:18 +000013402 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000013403}
13404
Richard Smithe9ff7702013-11-05 22:23:30 +000013405void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013406 assert(!isValueDependent() &&
13407 "Expression evaluator can't be called on a dependent expression.");
13408
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013409 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000013410 EvalResult EVResult;
13411 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000013412 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13413 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013414 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013415 }
13416}
13417
Richard Smithe6c01442013-06-05 00:46:14 +000013418bool Expr::EvalResult::isGlobalLValue() const {
13419 assert(Val.isLValue());
13420 return IsGlobalLValue(Val.getLValueBase());
13421}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000013422
13423
John McCall864e3962010-05-07 05:32:02 +000013424/// isIntegerConstantExpr - this recursive routine will test if an expression is
13425/// an integer constant expression.
13426
13427/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
13428/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000013429
13430// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000013431// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
13432// and a (possibly null) SourceLocation indicating the location of the problem.
13433//
John McCall864e3962010-05-07 05:32:02 +000013434// Note that to reduce code duplication, this helper does no evaluation
13435// itself; the caller checks whether the expression is evaluatable, and
13436// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000013437// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000013438
Dan Gohman28ade552010-07-26 21:25:24 +000013439namespace {
13440
Richard Smith9e575da2012-12-28 13:25:52 +000013441enum ICEKind {
13442 /// This expression is an ICE.
13443 IK_ICE,
13444 /// This expression is not an ICE, but if it isn't evaluated, it's
13445 /// a legal subexpression for an ICE. This return value is used to handle
13446 /// the comma operator in C99 mode, and non-constant subexpressions.
13447 IK_ICEIfUnevaluated,
13448 /// This expression is not an ICE, and is not a legal subexpression for one.
13449 IK_NotICE
13450};
13451
John McCall864e3962010-05-07 05:32:02 +000013452struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000013453 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000013454 SourceLocation Loc;
13455
Richard Smith9e575da2012-12-28 13:25:52 +000013456 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000013457};
13458
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013459}
Dan Gohman28ade552010-07-26 21:25:24 +000013460
Richard Smith9e575da2012-12-28 13:25:52 +000013461static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
13462
13463static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000013464
Craig Toppera31a8822013-08-22 07:09:37 +000013465static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013466 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000013467 Expr::EvalStatus Status;
13468 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13469
13470 Info.InConstantContext = true;
13471 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000013472 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013473 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000013474
John McCall864e3962010-05-07 05:32:02 +000013475 return NoDiag();
13476}
13477
Craig Toppera31a8822013-08-22 07:09:37 +000013478static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013479 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000013480 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013481 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013482
13483 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000013484#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000013485#define STMT(Node, Base) case Expr::Node##Class:
13486#define EXPR(Node, Base)
13487#include "clang/AST/StmtNodes.inc"
13488 case Expr::PredefinedExprClass:
13489 case Expr::FloatingLiteralClass:
13490 case Expr::ImaginaryLiteralClass:
13491 case Expr::StringLiteralClass:
13492 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000013493 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000013494 case Expr::MemberExprClass:
13495 case Expr::CompoundAssignOperatorClass:
13496 case Expr::CompoundLiteralExprClass:
13497 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000013498 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000013499 case Expr::ArrayInitLoopExprClass:
13500 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000013501 case Expr::NoInitExprClass:
13502 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000013503 case Expr::ImplicitValueInitExprClass:
13504 case Expr::ParenListExprClass:
13505 case Expr::VAArgExprClass:
13506 case Expr::AddrLabelExprClass:
13507 case Expr::StmtExprClass:
13508 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000013509 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000013510 case Expr::CXXDynamicCastExprClass:
13511 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000013512 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000013513 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000013514 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013515 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000013516 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013517 case Expr::CXXThisExprClass:
13518 case Expr::CXXThrowExprClass:
13519 case Expr::CXXNewExprClass:
13520 case Expr::CXXDeleteExprClass:
13521 case Expr::CXXPseudoDestructorExprClass:
13522 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000013523 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000013524 case Expr::DependentScopeDeclRefExprClass:
13525 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000013526 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000013527 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000013528 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000013529 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000013530 case Expr::CXXTemporaryObjectExprClass:
13531 case Expr::CXXUnresolvedConstructExprClass:
13532 case Expr::CXXDependentScopeMemberExprClass:
13533 case Expr::UnresolvedMemberExprClass:
13534 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000013535 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013536 case Expr::ObjCArrayLiteralClass:
13537 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013538 case Expr::ObjCEncodeExprClass:
13539 case Expr::ObjCMessageExprClass:
13540 case Expr::ObjCSelectorExprClass:
13541 case Expr::ObjCProtocolExprClass:
13542 case Expr::ObjCIvarRefExprClass:
13543 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013544 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000013545 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000013546 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000013547 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000013548 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000013549 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000013550 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000013551 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000013552 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000013553 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000013554 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000013555 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000013556 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000013557 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000013558 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000013559 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000013560 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000013561 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013562 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000013563 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013564 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013565 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000013566
Richard Smithf137f932014-01-25 20:50:08 +000013567 case Expr::InitListExprClass: {
13568 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13569 // form "T x = { a };" is equivalent to "T x = a;".
13570 // Unless we're initializing a reference, T is a scalar as it is known to be
13571 // of integral or enumeration type.
13572 if (E->isRValue())
13573 if (cast<InitListExpr>(E)->getNumInits() == 1)
13574 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013575 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000013576 }
13577
Douglas Gregor820ba7b2011-01-04 17:33:58 +000013578 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000013579 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000013580 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000013581 return NoDiag();
13582
John McCall7c454bb2011-07-15 05:09:51 +000013583 case Expr::SubstNonTypeTemplateParmExprClass:
13584 return
13585 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13586
Bill Wendling7c44da22018-10-31 03:48:47 +000013587 case Expr::ConstantExprClass:
13588 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13589
John McCall864e3962010-05-07 05:32:02 +000013590 case Expr::ParenExprClass:
13591 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000013592 case Expr::GenericSelectionExprClass:
13593 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013594 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000013595 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013596 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013597 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000013598 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000013599 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000013600 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000013601 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000013602 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000013603 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013604 return NoDiag();
13605 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000013606 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000013607 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13608 // constant expressions, but they can never be ICEs because an ICE cannot
13609 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000013610 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000013611 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000013612 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013613 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013614 }
Richard Smith6365c912012-02-24 22:12:32 +000013615 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013616 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13617 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000013618 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000013619 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000013620 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000013621 // Parameter variables are never constants. Without this check,
13622 // getAnyInitializer() can find a default argument, which leads
13623 // to chaos.
13624 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000013625 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013626
13627 // C++ 7.1.5.1p2
13628 // A variable of non-volatile const-qualified integral or enumeration
13629 // type initialized by an ICE can be used in ICEs.
13630 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000013631 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000013632 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000013633
Richard Smithd0b4dd62011-12-19 06:19:21 +000013634 const VarDecl *VD;
13635 // Look for a declaration of this variable that has an initializer, and
13636 // check whether it is an ICE.
13637 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13638 return NoDiag();
13639 else
Richard Smith9e575da2012-12-28 13:25:52 +000013640 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013641 }
13642 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013643 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000013644 }
John McCall864e3962010-05-07 05:32:02 +000013645 case Expr::UnaryOperatorClass: {
13646 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13647 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013648 case UO_PostInc:
13649 case UO_PostDec:
13650 case UO_PreInc:
13651 case UO_PreDec:
13652 case UO_AddrOf:
13653 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000013654 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000013655 // C99 6.6/3 allows increment and decrement within unevaluated
13656 // subexpressions of constant expressions, but they can never be ICEs
13657 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013658 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000013659 case UO_Extension:
13660 case UO_LNot:
13661 case UO_Plus:
13662 case UO_Minus:
13663 case UO_Not:
13664 case UO_Real:
13665 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000013666 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013667 }
Reid Klecknere540d972018-11-01 17:51:48 +000013668 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000013669 }
13670 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000013671 // Note that per C99, offsetof must be an ICE. And AFAIK, using
13672 // EvaluateAsRValue matches the proposed gcc behavior for cases like
13673 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
13674 // compliance: we should warn earlier for offsetof expressions with
13675 // array subscripts that aren't ICEs, and if the array subscripts
13676 // are ICEs, the value of the offsetof must be an integer constant.
13677 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000013678 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000013679 case Expr::UnaryExprOrTypeTraitExprClass: {
13680 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
13681 if ((Exp->getKind() == UETT_SizeOf) &&
13682 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013683 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013684 return NoDiag();
13685 }
13686 case Expr::BinaryOperatorClass: {
13687 const BinaryOperator *Exp = cast<BinaryOperator>(E);
13688 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013689 case BO_PtrMemD:
13690 case BO_PtrMemI:
13691 case BO_Assign:
13692 case BO_MulAssign:
13693 case BO_DivAssign:
13694 case BO_RemAssign:
13695 case BO_AddAssign:
13696 case BO_SubAssign:
13697 case BO_ShlAssign:
13698 case BO_ShrAssign:
13699 case BO_AndAssign:
13700 case BO_XorAssign:
13701 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000013702 // C99 6.6/3 allows assignments within unevaluated subexpressions of
13703 // constant expressions, but they can never be ICEs because an ICE cannot
13704 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013705 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013706
John McCalle3027922010-08-25 11:45:40 +000013707 case BO_Mul:
13708 case BO_Div:
13709 case BO_Rem:
13710 case BO_Add:
13711 case BO_Sub:
13712 case BO_Shl:
13713 case BO_Shr:
13714 case BO_LT:
13715 case BO_GT:
13716 case BO_LE:
13717 case BO_GE:
13718 case BO_EQ:
13719 case BO_NE:
13720 case BO_And:
13721 case BO_Xor:
13722 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000013723 case BO_Comma:
13724 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000013725 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13726 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000013727 if (Exp->getOpcode() == BO_Div ||
13728 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000013729 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000013730 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000013731 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000013732 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000013733 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013734 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013735 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000013736 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000013737 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013738 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013739 }
13740 }
13741 }
John McCalle3027922010-08-25 11:45:40 +000013742 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013743 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000013744 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
13745 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000013746 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013747 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013748 } else {
13749 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013750 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013751 }
13752 }
Richard Smith9e575da2012-12-28 13:25:52 +000013753 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000013754 }
John McCalle3027922010-08-25 11:45:40 +000013755 case BO_LAnd:
13756 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000013757 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13758 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013759 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000013760 // Rare case where the RHS has a comma "side-effect"; we need
13761 // to actually check the condition to see whether the side
13762 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000013763 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000013764 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000013765 return RHSResult;
13766 return NoDiag();
13767 }
13768
Richard Smith9e575da2012-12-28 13:25:52 +000013769 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000013770 }
13771 }
Reid Klecknere540d972018-11-01 17:51:48 +000013772 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000013773 }
13774 case Expr::ImplicitCastExprClass:
13775 case Expr::CStyleCastExprClass:
13776 case Expr::CXXFunctionalCastExprClass:
13777 case Expr::CXXStaticCastExprClass:
13778 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000013779 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000013780 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013781 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000013782 if (isa<ExplicitCastExpr>(E)) {
13783 if (const FloatingLiteral *FL
13784 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
13785 unsigned DestWidth = Ctx.getIntWidth(E->getType());
13786 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
13787 APSInt IgnoredVal(DestWidth, !DestSigned);
13788 bool Ignored;
13789 // If the value does not fit in the destination type, the behavior is
13790 // undefined, so we are not required to treat it as a constant
13791 // expression.
13792 if (FL->getValue().convertToInteger(IgnoredVal,
13793 llvm::APFloat::rmTowardZero,
13794 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013795 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000013796 return NoDiag();
13797 }
13798 }
Eli Friedman76d4e432011-09-29 21:49:34 +000013799 switch (cast<CastExpr>(E)->getCastKind()) {
13800 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000013801 case CK_AtomicToNonAtomic:
13802 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000013803 case CK_NoOp:
13804 case CK_IntegralToBoolean:
13805 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000013806 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000013807 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013808 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000013809 }
John McCall864e3962010-05-07 05:32:02 +000013810 }
John McCallc07a0c72011-02-17 10:25:35 +000013811 case Expr::BinaryConditionalOperatorClass: {
13812 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
13813 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013814 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000013815 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013816 if (FalseResult.Kind == IK_NotICE) return FalseResult;
13817 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
13818 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000013819 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000013820 return FalseResult;
13821 }
John McCall864e3962010-05-07 05:32:02 +000013822 case Expr::ConditionalOperatorClass: {
13823 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
13824 // If the condition (ignoring parens) is a __builtin_constant_p call,
13825 // then only the true side is actually considered in an integer constant
13826 // expression, and it is fully evaluated. This is an important GNU
13827 // extension. See GCC PR38377 for discussion.
13828 if (const CallExpr *CallCE
13829 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000013830 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000013831 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000013832 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013833 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000013834 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000013835
Richard Smithf57d8cb2011-12-09 22:58:01 +000013836 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
13837 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000013838
Richard Smith9e575da2012-12-28 13:25:52 +000013839 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000013840 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013841 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000013842 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013843 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000013844 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013845 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000013846 return NoDiag();
13847 // Rare case where the diagnostics depend on which side is evaluated
13848 // Note that if we get here, CondResult is 0, and at least one of
13849 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000013850 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000013851 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000013852 return TrueResult;
13853 }
13854 case Expr::CXXDefaultArgExprClass:
13855 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000013856 case Expr::CXXDefaultInitExprClass:
13857 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013858 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000013859 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013860 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000013861 case Expr::BuiltinBitCastExprClass: {
13862 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13863 return ICEDiag(IK_NotICE, E->getBeginLoc());
13864 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13865 }
John McCall864e3962010-05-07 05:32:02 +000013866 }
13867
David Blaikiee4d798f2012-01-20 21:50:17 +000013868 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000013869}
13870
Richard Smithf57d8cb2011-12-09 22:58:01 +000013871/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000013872static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013873 const Expr *E,
13874 llvm::APSInt *Value,
13875 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000013876 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000013877 if (Loc) *Loc = E->getExprLoc();
13878 return false;
13879 }
13880
Richard Smith66e05fe2012-01-18 05:21:49 +000013881 APValue Result;
13882 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000013883 return false;
13884
Richard Smith98710fc2014-11-13 23:03:19 +000013885 if (!Result.isInt()) {
13886 if (Loc) *Loc = E->getExprLoc();
13887 return false;
13888 }
13889
Richard Smith66e05fe2012-01-18 05:21:49 +000013890 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000013891 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013892}
13893
Craig Toppera31a8822013-08-22 07:09:37 +000013894bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13895 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013896 assert(!isValueDependent() &&
13897 "Expression evaluator can't be called on a dependent expression.");
13898
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013899 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000013900 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013901
Richard Smith9e575da2012-12-28 13:25:52 +000013902 ICEDiag D = CheckICE(this, Ctx);
13903 if (D.Kind != IK_ICE) {
13904 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000013905 return false;
13906 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000013907 return true;
13908}
13909
Craig Toppera31a8822013-08-22 07:09:37 +000013910bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013911 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013912 assert(!isValueDependent() &&
13913 "Expression evaluator can't be called on a dependent expression.");
13914
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013915 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000013916 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13917
13918 if (!isIntegerConstantExpr(Ctx, Loc))
13919 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000013920
Richard Smith5c40f092015-12-04 03:00:44 +000013921 // The only possible side-effects here are due to UB discovered in the
13922 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13923 // required to treat the expression as an ICE, so we produce the folded
13924 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000013925 EvalResult ExprResult;
13926 Expr::EvalStatus Status;
13927 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13928 Info.InConstantContext = true;
13929
13930 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000013931 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000013932
13933 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000013934 return true;
13935}
Richard Smith66e05fe2012-01-18 05:21:49 +000013936
Craig Toppera31a8822013-08-22 07:09:37 +000013937bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013938 assert(!isValueDependent() &&
13939 "Expression evaluator can't be called on a dependent expression.");
13940
Richard Smith9e575da2012-12-28 13:25:52 +000013941 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000013942}
13943
Craig Toppera31a8822013-08-22 07:09:37 +000013944bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000013945 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013946 assert(!isValueDependent() &&
13947 "Expression evaluator can't be called on a dependent expression.");
13948
Richard Smith66e05fe2012-01-18 05:21:49 +000013949 // We support this checking in C++98 mode in order to diagnose compatibility
13950 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013951 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000013952
Richard Smith98a0a492012-02-14 21:38:30 +000013953 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000013954 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013955 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000013956 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000013957 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000013958
13959 APValue Scratch;
Richard Smith457226e2019-09-23 03:48:44 +000013960 bool IsConstExpr =
13961 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
13962 // FIXME: We don't produce a diagnostic for this, but the callers that
13963 // call us on arbitrary full-expressions should generally not care.
Richard Smithda1b4342019-09-27 01:26:47 +000013964 Info.discardCleanups() && !Status.HasSideEffects;
Richard Smith66e05fe2012-01-18 05:21:49 +000013965
13966 if (!Diags.empty()) {
13967 IsConstExpr = false;
13968 if (Loc) *Loc = Diags[0].first;
13969 } else if (!IsConstExpr) {
13970 // FIXME: This shouldn't happen.
13971 if (Loc) *Loc = getExprLoc();
13972 }
13973
13974 return IsConstExpr;
13975}
Richard Smith253c2a32012-01-27 01:14:48 +000013976
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013977bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13978 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000013979 ArrayRef<const Expr*> Args,
13980 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013981 assert(!isValueDependent() &&
13982 "Expression evaluator can't be called on a dependent expression.");
13983
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013984 Expr::EvalStatus Status;
13985 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013986 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013987
George Burgess IV177399e2017-01-09 04:12:14 +000013988 LValue ThisVal;
13989 const LValue *ThisPtr = nullptr;
13990 if (This) {
13991#ifndef NDEBUG
13992 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13993 assert(MD && "Don't provide `this` for non-methods.");
13994 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13995#endif
13996 if (EvaluateObjectArgument(Info, This, ThisVal))
13997 ThisPtr = &ThisVal;
13998 if (Info.EvalStatus.HasSideEffects)
13999 return false;
14000 }
14001
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014002 ArgVector ArgValues(Args.size());
14003 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14004 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000014005 if ((*I)->isValueDependent() ||
14006 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014007 // If evaluation fails, throw away the argument entirely.
14008 ArgValues[I - Args.begin()] = APValue();
14009 if (Info.EvalStatus.HasSideEffects)
14010 return false;
14011 }
14012
14013 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000014014 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014015 ArgValues.data());
Richard Smith457226e2019-09-23 03:48:44 +000014016 return Evaluate(Value, Info, this) && Info.discardCleanups() &&
14017 !Info.EvalStatus.HasSideEffects;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014018}
14019
Richard Smith253c2a32012-01-27 01:14:48 +000014020bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014021 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000014022 PartialDiagnosticAt> &Diags) {
14023 // FIXME: It would be useful to check constexpr function templates, but at the
14024 // moment the constant expression evaluator cannot cope with the non-rigorous
14025 // ASTs which we build for dependent expressions.
14026 if (FD->isDependentContext())
14027 return true;
14028
14029 Expr::EvalStatus Status;
14030 Status.Diag = &Diags;
14031
Richard Smith045b2272019-09-10 21:24:09 +000014032 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000014033 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014034 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000014035
Nandor Licker950b70d2019-09-13 09:46:16 +000014036 // The constexpr VM attempts to compile all methods to bytecode here.
14037 if (Info.EnableNewConstInterp) {
14038 auto &InterpCtx = Info.Ctx.getInterpContext();
14039 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
14040 case interp::InterpResult::Success:
14041 case interp::InterpResult::Fail:
14042 return Diags.empty();
14043 case interp::InterpResult::Bail:
14044 break;
14045 }
14046 }
14047
Richard Smith253c2a32012-01-27 01:14:48 +000014048 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000014049 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000014050
Richard Smith7525ff62013-05-09 07:14:00 +000014051 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000014052 // is a temporary being used as the 'this' pointer.
14053 LValue This;
14054 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000014055 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000014056
Richard Smith253c2a32012-01-27 01:14:48 +000014057 ArrayRef<const Expr*> Args;
14058
Richard Smith2e312c82012-03-03 22:46:17 +000014059 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000014060 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14061 // Evaluate the call as a constant initializer, to allow the construction
14062 // of objects of non-literal types.
14063 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000014064 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14065 } else {
14066 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000014067 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000014068 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000014069 }
Richard Smith253c2a32012-01-27 01:14:48 +000014070
14071 return Diags.empty();
14072}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014073
14074bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14075 const FunctionDecl *FD,
14076 SmallVectorImpl<
14077 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014078 assert(!E->isValueDependent() &&
14079 "Expression evaluator can't be called on a dependent expression.");
14080
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014081 Expr::EvalStatus Status;
14082 Status.Diag = &Diags;
14083
14084 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000014085 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014086 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014087 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014088
14089 // Fabricate a call stack frame to give the arguments a plausible cover story.
14090 ArrayRef<const Expr*> Args;
14091 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014092 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014093 (void)Success;
14094 assert(Success &&
14095 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000014096 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014097
14098 APValue ResultScratch;
14099 Evaluate(ResultScratch, Info, E);
14100 return Diags.empty();
14101}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014102
14103bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14104 unsigned Type) const {
14105 if (!getType()->isPointerType())
14106 return false;
14107
14108 Expr::EvalStatus Status;
14109 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000014110 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014111}