blob: fbec3ae582b5e0035b040d8c7797740ad91952ae [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
Richard Smithb228a862012-02-15 02:18:13 +000069static bool IsGlobalLValue(APValue::LValueBase B);
70
John McCall93d91dc2010-05-07 17:22:02 +000071namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000072 struct LValue;
Nandor Licker950b70d2019-09-13 09:46:16 +000073 class CallStackFrame;
74 class EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000075
Eric Fiselier708afb52019-05-16 21:04:15 +000076 using SourceLocExprScopeGuard =
77 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
78
Richard Smithb228a862012-02-15 02:18:13 +000079 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000080 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000081 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000082 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000083 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000084 //
85 // extern int arr[]; void f() { extern int arr[3]; };
86 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000087 //
88 // For now, we take the array bound from the most recent declaration.
89 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
90 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
91 QualType T = Redecl->getType();
92 if (!T->isIncompleteArrayType())
93 return T;
94 }
95 return D->getType();
96 }
Richard Smith84401042013-06-03 05:03:02 +000097
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000098 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000099 return B.getTypeInfoType();
100
Richard Smith84401042013-06-03 05:03:02 +0000101 const Expr *Base = B.get<const Expr*>();
102
103 // For a materialized temporary, the type of the temporary we materialized
104 // may not be the type of the expression.
105 if (const MaterializeTemporaryExpr *MTE =
106 dyn_cast<MaterializeTemporaryExpr>(Base)) {
107 SmallVector<const Expr *, 2> CommaLHSs;
108 SmallVector<SubobjectAdjustment, 2> Adjustments;
109 const Expr *Temp = MTE->GetTemporaryExpr();
110 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
111 Adjustments);
112 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000113 // for it directly. Otherwise use the type after adjustment.
114 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000115 return Inner->getType();
116 }
117
118 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000119 }
120
Richard Smithd62306a2011-11-10 06:34:14 +0000121 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000122 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000123 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000124 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000125 }
126 /// Get an LValue path entry, which is known to not be an array index, as a
127 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000128 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000129 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000130 }
131 /// Determine whether this LValue path entry for a base class names a virtual
132 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000133 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000134 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000135 }
136
Richard Smith457226e2019-09-23 03:48:44 +0000137 /// Given an expression, determine the type used to store the result of
138 /// evaluating that expression.
139 static QualType getStorageType(ASTContext &Ctx, Expr *E) {
140 if (E->isRValue())
141 return E->getType();
142 return Ctx.getLValueReferenceType(E->getType());
143 }
144
George Burgess IVe3763372016-12-22 02:50:20 +0000145 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
146 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
147 const FunctionDecl *Callee = CE->getDirectCallee();
148 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
149 }
150
151 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
152 /// This will look through a single cast.
153 ///
154 /// Returns null if we couldn't unwrap a function with alloc_size.
155 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
156 if (!E->getType()->isPointerType())
157 return nullptr;
158
159 E = E->IgnoreParens();
160 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000161 // probably be a cast of some kind. In exotic cases, we might also see a
162 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000163 if (const auto *FE = dyn_cast<FullExpr>(E))
164 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000165
George Burgess IVe3763372016-12-22 02:50:20 +0000166 if (const auto *Cast = dyn_cast<CastExpr>(E))
167 E = Cast->getSubExpr()->IgnoreParens();
168
169 if (const auto *CE = dyn_cast<CallExpr>(E))
170 return getAllocSizeAttr(CE) ? CE : nullptr;
171 return nullptr;
172 }
173
174 /// Determines whether or not the given Base contains a call to a function
175 /// with the alloc_size attribute.
176 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
177 const auto *E = Base.dyn_cast<const Expr *>();
178 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
179 }
180
Richard Smith6f4f0f12017-10-20 22:56:25 +0000181 /// The bound to claim that an array of unknown bound has.
182 /// The value in MostDerivedArraySize is undefined in this case. So, set it
183 /// to an arbitrary value that's likely to loudly break things if it's used.
184 static const uint64_t AssumedSizeForUnsizedArray =
185 std::numeric_limits<uint64_t>::max() / 2;
186
George Burgess IVe3763372016-12-22 02:50:20 +0000187 /// Determines if an LValue with the given LValueBase will have an unsized
188 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000189 /// Find the path length and type of the most-derived subobject in the given
190 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000191 static unsigned
192 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
193 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000194 uint64_t &ArraySize, QualType &Type, bool &IsArray,
195 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000196 // This only accepts LValueBases from APValues, and APValues don't support
197 // arrays that lack size info.
198 assert(!isBaseAnAllocSizeCall(Base) &&
199 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000200 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000201 Type = getType(Base);
202
Richard Smith80815602011-11-07 05:07:52 +0000203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000204 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000208 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getSize().getZExtValue();
212 } else {
213 assert(I == 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
Richard Smith66c96992012-02-18 22:04:06 +0000217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000222 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 } else if (const FieldDecl *FD = getAsField(Path[I])) {
224 Type = FD->getType();
225 ArraySize = 0;
226 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000227 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000228 } else {
Richard Smith80815602011-11-07 05:07:52 +0000229 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000230 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000231 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000232 }
Richard Smith80815602011-11-07 05:07:52 +0000233 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000234 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000235 }
236
Richard Smith96e0c102011-11-04 02:25:55 +0000237 /// A path from a glvalue to a subobject of that glvalue.
238 struct SubobjectDesignator {
239 /// True if the subobject was named in a manner not supported by C++11. Such
240 /// lvalues can still be folded, but they are not core constant expressions
241 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000242 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000243
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000245 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000246
Daniel Jasperffdee092017-05-02 19:21:42 +0000247 /// Indicator of whether the first entry is an unsized array.
248 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000249
George Burgess IVa51c4072015-10-16 01:49:01 +0000250 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000251 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000252
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 /// The length of the path to the most-derived object of which this is a
254 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000255 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000256
George Burgess IVa51c4072015-10-16 01:49:01 +0000257 /// The size of the array of which the most-derived object is an element.
258 /// This will always be 0 if the most-derived object is not an array
259 /// element. 0 is not an indicator of whether or not the most-derived object
260 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000261 ///
262 /// If the current array is an unsized array, the value of this is
263 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 uint64_t MostDerivedArraySize;
265
266 /// The type of the most derived object referred to by this address.
267 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000268
Richard Smith80815602011-11-07 05:07:52 +0000269 typedef APValue::LValuePathEntry PathEntry;
270
Richard Smith96e0c102011-11-04 02:25:55 +0000271 /// The entries on the path from the glvalue to the designated subobject.
272 SmallVector<PathEntry, 8> Entries;
273
Richard Smitha8105bc2012-01-06 16:39:00 +0000274 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000275
Richard Smitha8105bc2012-01-06 16:39:00 +0000276 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000277 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000279 MostDerivedPathLength(0), MostDerivedArraySize(0),
280 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000281
282 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000284 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000285 MostDerivedPathLength(0), MostDerivedArraySize(0) {
286 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000287 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000288 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000289 ArrayRef<PathEntry> VEntries = V.getLValuePath();
290 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000291 if (V.getLValueBase()) {
292 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000293 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000294 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000295 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000296 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000297 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000298 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000299 }
Richard Smith80815602011-11-07 05:07:52 +0000300 }
301 }
302
Richard Smith31c69a32019-05-21 23:15:20 +0000303 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
304 unsigned NewLength) {
305 if (Invalid)
306 return;
307
308 assert(Base && "cannot truncate path for null pointer");
309 assert(NewLength <= Entries.size() && "not a truncation");
310
311 if (NewLength == Entries.size())
312 return;
313 Entries.resize(NewLength);
314
315 bool IsArray = false;
316 bool FirstIsUnsizedArray = false;
317 MostDerivedPathLength = findMostDerivedSubobject(
318 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
319 FirstIsUnsizedArray);
320 MostDerivedIsArrayElement = IsArray;
321 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
322 }
323
Richard Smith96e0c102011-11-04 02:25:55 +0000324 void setInvalid() {
325 Invalid = true;
326 Entries.clear();
327 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000328
George Burgess IVe3763372016-12-22 02:50:20 +0000329 /// Determine whether the most derived subobject is an array without a
330 /// known bound.
331 bool isMostDerivedAnUnsizedArray() const {
332 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000333 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000334 }
335
336 /// Determine what the most derived array's size is. Results in an assertion
337 /// failure if the most derived array lacks a size.
338 uint64_t getMostDerivedArraySize() const {
339 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
340 return MostDerivedArraySize;
341 }
342
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 /// Determine whether this is a one-past-the-end pointer.
344 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000345 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000346 if (IsOnePastTheEnd)
347 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000348 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000349 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
350 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000351 return true;
352 return false;
353 }
354
Richard Smith06f71b52018-08-04 00:57:17 +0000355 /// Get the range of valid index adjustments in the form
356 /// {maximum value that can be subtracted from this pointer,
357 /// maximum value that can be added to this pointer}
358 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
359 if (Invalid || isMostDerivedAnUnsizedArray())
360 return {0, 0};
361
362 // [expr.add]p4: For the purposes of these operators, a pointer to a
363 // nonarray object behaves the same as a pointer to the first element of
364 // an array of length one with the type of the object as its element type.
365 bool IsArray = MostDerivedPathLength == Entries.size() &&
366 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000367 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
368 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000369 uint64_t ArraySize =
370 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
371 return {ArrayIndex, ArraySize - ArrayIndex};
372 }
373
Richard Smitha8105bc2012-01-06 16:39:00 +0000374 /// Check that this refers to a valid subobject.
375 bool isValidSubobject() const {
376 if (Invalid)
377 return false;
378 return !isOnePastTheEnd();
379 }
380 /// Check that this refers to a valid subobject, and if not, produce a
381 /// relevant diagnostic and set the designator as invalid.
382 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
383
Richard Smith06f71b52018-08-04 00:57:17 +0000384 /// Get the type of the designated object.
385 QualType getType(ASTContext &Ctx) const {
386 assert(!Invalid && "invalid designator has no subobject type");
387 return MostDerivedPathLength == Entries.size()
388 ? MostDerivedType
389 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
390 }
391
Richard Smitha8105bc2012-01-06 16:39:00 +0000392 /// Update this designator to refer to the first element within this array.
393 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000394 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000395
396 // This is a most-derived object.
397 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000398 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000399 MostDerivedArraySize = CAT->getSize().getZExtValue();
400 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000401 }
George Burgess IVe3763372016-12-22 02:50:20 +0000402 /// Update this designator to refer to the first element within the array of
403 /// elements of type T. This is an array of unknown size.
404 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000405 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000406
407 MostDerivedType = ElemTy;
408 MostDerivedIsArrayElement = true;
409 // The value in MostDerivedArraySize is undefined in this case. So, set it
410 // to an arbitrary value that's likely to loudly break things if it's
411 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000412 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000413 MostDerivedPathLength = Entries.size();
414 }
Richard Smith96e0c102011-11-04 02:25:55 +0000415 /// Update this designator to refer to the given base or member of this
416 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000417 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000418 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000419
420 // If this isn't a base class, it's a new most-derived object.
421 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
422 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000423 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000424 MostDerivedArraySize = 0;
425 MostDerivedPathLength = Entries.size();
426 }
Richard Smith96e0c102011-11-04 02:25:55 +0000427 }
Richard Smith66c96992012-02-18 22:04:06 +0000428 /// Update this designator to refer to the given complex component.
429 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000430 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000431
432 // This is technically a most-derived object, though in practice this
433 // is unlikely to matter.
434 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000435 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000436 MostDerivedArraySize = 2;
437 MostDerivedPathLength = Entries.size();
438 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000439 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000440 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
441 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000442 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000443 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
444 if (Invalid || !N) return;
445 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
446 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000447 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000448 // Can't verify -- trust that the user is doing the right thing (or if
449 // not, trust that the caller will catch the bad behavior).
450 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000451 Entries.back() = PathEntry::ArrayIndex(
452 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000453 return;
454 }
455
456 // [expr.add]p4: For the purposes of these operators, a pointer to a
457 // nonarray object behaves the same as a pointer to the first element of
458 // an array of length one with the type of the object as its element type.
459 bool IsArray = MostDerivedPathLength == Entries.size() &&
460 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000461 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
462 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000463 uint64_t ArraySize =
464 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
465
466 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
467 // Calculate the actual index in a wide enough type, so we can include
468 // it in the note.
469 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
470 (llvm::APInt&)N += ArrayIndex;
471 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
472 diagnosePointerArithmetic(Info, E, N);
473 setInvalid();
474 return;
475 }
476
477 ArrayIndex += TruncatedN;
478 assert(ArrayIndex <= ArraySize &&
479 "bounds check succeeded for out-of-bounds index");
480
481 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000482 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000483 else
484 IsOnePastTheEnd = (ArrayIndex != 0);
485 }
Richard Smith96e0c102011-11-04 02:25:55 +0000486 };
487
Richard Smith254a73d2011-10-28 22:34:42 +0000488 /// A stack frame in the constexpr call stack.
Nandor Licker950b70d2019-09-13 09:46:16 +0000489 class CallStackFrame : public interp::Frame {
490 public:
Richard Smith254a73d2011-10-28 22:34:42 +0000491 EvalInfo &Info;
492
493 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000494 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000495
Richard Smithf6f003a2011-12-16 19:06:07 +0000496 /// Callee - The function which was called.
497 const FunctionDecl *Callee;
498
Richard Smithd62306a2011-11-10 06:34:14 +0000499 /// This - The binding for the this pointer in this call, if any.
500 const LValue *This;
501
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000502 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000503 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000504 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000505
Eric Fiselier708afb52019-05-16 21:04:15 +0000506 /// Source location information about the default argument or default
507 /// initializer expression we're evaluating, if any.
508 CurrentSourceLocExprScope CurSourceLocExprScope;
509
Eli Friedman4830ec82012-06-25 21:21:08 +0000510 // Note that we intentionally use std::map here so that references to
511 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000512 typedef std::pair<const void *, unsigned> MapKeyTy;
513 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000514 /// Temporaries - Temporary lvalues materialized within this stack frame.
515 MapTy Temporaries;
516
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000517 /// CallLoc - The location of the call expression for this call.
518 SourceLocation CallLoc;
519
520 /// Index - The call index of this call.
521 unsigned Index;
522
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000523 /// The stack of integers for tracking version numbers for temporaries.
524 SmallVector<unsigned, 2> TempVersionStack = {1};
525 unsigned CurTempVersion = TempVersionStack.back();
526
527 unsigned getTempVersion() const { return TempVersionStack.back(); }
528
529 void pushTempVersion() {
530 TempVersionStack.push_back(++CurTempVersion);
531 }
532
533 void popTempVersion() {
534 TempVersionStack.pop_back();
535 }
536
Faisal Vali051e3a22017-02-16 04:12:21 +0000537 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000538 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000539 // (We should cache this map rather than recomputing it repeatedly.)
540 // But let's try this and see how it goes; we can look into caching the map
541 // as a later change.
542
543 /// LambdaCaptureFields - Mapping from captured variables/this to
544 /// corresponding data members in the closure class.
545 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
546 FieldDecl *LambdaThisCaptureField;
547
Richard Smithf6f003a2011-12-16 19:06:07 +0000548 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
549 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000550 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000551 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000552
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000553 // Return the temporary for Key whose version number is Version.
554 APValue *getTemporary(const void *Key, unsigned Version) {
555 MapKeyTy KV(Key, Version);
556 auto LB = Temporaries.lower_bound(KV);
557 if (LB != Temporaries.end() && LB->first == KV)
558 return &LB->second;
559 // Pair (Key,Version) wasn't found in the map. Check that no elements
560 // in the map have 'Key' as their key.
561 assert((LB == Temporaries.end() || LB->first.first != Key) &&
562 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
563 "Element with key 'Key' found in map");
564 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000565 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000566
567 // Return the current temporary for Key in the map.
568 APValue *getCurrentTemporary(const void *Key) {
569 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
570 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
571 return &std::prev(UB)->second;
572 return nullptr;
573 }
574
575 // Return the version number of the current temporary for Key.
576 unsigned getCurrentTemporaryVersion(const void *Key) const {
577 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
578 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
579 return std::prev(UB)->first.second;
580 return 0;
581 }
582
Richard Smith457226e2019-09-23 03:48:44 +0000583 /// Allocate storage for an object of type T in this stack frame.
584 /// Populates LV with a handle to the created object. Key identifies
585 /// the temporary within the stack frame, and must not be reused without
586 /// bumping the temporary version number.
587 template<typename KeyT>
588 APValue &createTemporary(const KeyT *Key, QualType T,
589 bool IsLifetimeExtended, LValue &LV);
Nandor Licker950b70d2019-09-13 09:46:16 +0000590
591 void describe(llvm::raw_ostream &OS) override;
592
593 Frame *getCaller() const override { return Caller; }
594 SourceLocation getCallLocation() const override { return CallLoc; }
595 const FunctionDecl *getCallee() const override { return Callee; }
Richard Smith254a73d2011-10-28 22:34:42 +0000596 };
597
Richard Smith852c9db2013-04-20 22:23:05 +0000598 /// Temporarily override 'this'.
599 class ThisOverrideRAII {
600 public:
601 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
602 : Frame(Frame), OldThis(Frame.This) {
603 if (Enable)
604 Frame.This = NewThis;
605 }
606 ~ThisOverrideRAII() {
607 Frame.This = OldThis;
608 }
609 private:
610 CallStackFrame &Frame;
611 const LValue *OldThis;
612 };
Richard Smith457226e2019-09-23 03:48:44 +0000613}
Richard Smith852c9db2013-04-20 22:23:05 +0000614
Richard Smith457226e2019-09-23 03:48:44 +0000615static bool HandleDestructorCall(EvalInfo &Info, APValue::LValueBase LVBase,
616 APValue &Value, QualType T);
617
618namespace {
Richard Smith08d6a2c2013-07-24 07:11:57 +0000619 /// A cleanup, and a flag indicating whether it is lifetime-extended.
620 class Cleanup {
621 llvm::PointerIntPair<APValue*, 1, bool> Value;
Richard Smith457226e2019-09-23 03:48:44 +0000622 APValue::LValueBase Base;
623 QualType T;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000624
625 public:
Richard Smith457226e2019-09-23 03:48:44 +0000626 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
627 bool IsLifetimeExtended)
628 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
Richard Smith08d6a2c2013-07-24 07:11:57 +0000629
630 bool isLifetimeExtended() const { return Value.getInt(); }
Richard Smith457226e2019-09-23 03:48:44 +0000631 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
632 if (RunDestructors && T.isDestructedType())
633 return HandleDestructorCall(Info, Base, *Value.getPointer(), T);
Richard Smith08d6a2c2013-07-24 07:11:57 +0000634 *Value.getPointer() = APValue();
Richard Smith457226e2019-09-23 03:48:44 +0000635 return true;
636 }
637
638 bool hasSideEffect() {
639 return T.isDestructedType();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000640 }
641 };
642
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000643 /// A reference to an object whose construction we are currently evaluating.
644 struct ObjectUnderConstruction {
645 APValue::LValueBase Base;
646 ArrayRef<APValue::LValuePathEntry> Path;
647 friend bool operator==(const ObjectUnderConstruction &LHS,
648 const ObjectUnderConstruction &RHS) {
649 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
650 }
651 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
652 return llvm::hash_combine(Obj.Base, Obj.Path);
653 }
654 };
Richard Smith457226e2019-09-23 03:48:44 +0000655 enum class ConstructionPhase {
656 None,
657 Bases,
658 AfterBases,
659 Destroying,
660 DestroyingBases
661 };
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000662}
663
664namespace llvm {
665template<> struct DenseMapInfo<ObjectUnderConstruction> {
666 using Base = DenseMapInfo<APValue::LValueBase>;
667 static ObjectUnderConstruction getEmptyKey() {
668 return {Base::getEmptyKey(), {}}; }
669 static ObjectUnderConstruction getTombstoneKey() {
670 return {Base::getTombstoneKey(), {}};
671 }
672 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
673 return hash_value(Object);
674 }
675 static bool isEqual(const ObjectUnderConstruction &LHS,
676 const ObjectUnderConstruction &RHS) {
677 return LHS == RHS;
678 }
679};
680}
681
682namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000683 /// EvalInfo - This is a private struct used by the evaluator to capture
684 /// information about a subexpression as it is folded. It retains information
685 /// about the AST context, but also maintains information about the folded
686 /// expression.
687 ///
688 /// If an expression could be evaluated, it is still possible it is not a C
689 /// "integer constant expression" or constant expression. If not, this struct
690 /// captures information about how and why not.
691 ///
692 /// One bit of information passed *into* the request for constant folding
693 /// indicates whether the subexpression is "evaluated" or not according to C
694 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
695 /// evaluate the expression regardless of what the RHS is, but C only allows
696 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000697 class EvalInfo : public interp::State {
698 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000699 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000700
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000701 /// EvalStatus - Contains information about the evaluation.
702 Expr::EvalStatus &EvalStatus;
703
704 /// CurrentCall - The top of the constexpr call stack.
705 CallStackFrame *CurrentCall;
706
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000707 /// CallStackDepth - The number of calls in the call stack right now.
708 unsigned CallStackDepth;
709
Richard Smithb228a862012-02-15 02:18:13 +0000710 /// NextCallIndex - The next call index to assign.
711 unsigned NextCallIndex;
712
Richard Smitha3d3bd22013-05-08 02:12:03 +0000713 /// StepsLeft - The remaining number of evaluation steps we're permitted
714 /// to perform. This is essentially a limit for the number of statements
715 /// we will evaluate.
716 unsigned StepsLeft;
717
Nandor Licker950b70d2019-09-13 09:46:16 +0000718 /// Force the use of the experimental new constant interpreter, bailing out
719 /// with an error if a feature is not supported.
720 bool ForceNewConstInterp;
721
722 /// Enable the experimental new constant interpreter.
723 bool EnableNewConstInterp;
724
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000725 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000726 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000727 CallStackFrame BottomFrame;
728
Richard Smith08d6a2c2013-07-24 07:11:57 +0000729 /// A stack of values whose lifetimes end at the end of some surrounding
730 /// evaluation frame.
731 llvm::SmallVector<Cleanup, 16> CleanupStack;
732
Richard Smithd62306a2011-11-10 06:34:14 +0000733 /// EvaluatingDecl - This is the declaration whose initializer is being
734 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000735 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000736
737 /// EvaluatingDeclValue - This is the value being constructed for the
738 /// declaration whose initializer is being evaluated, if any.
739 APValue *EvaluatingDeclValue;
740
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000741 /// Set of objects that are currently being constructed.
742 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
743 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000744
745 struct EvaluatingConstructorRAII {
746 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000747 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000748 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000749 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
750 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000751 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000752 DidInsert =
753 EI.ObjectsUnderConstruction
754 .insert({Object, HasBases ? ConstructionPhase::Bases
755 : ConstructionPhase::AfterBases})
756 .second;
757 }
758 void finishedConstructingBases() {
759 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000760 }
761 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000762 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000763 }
764 };
765
Richard Smith457226e2019-09-23 03:48:44 +0000766 struct EvaluatingDestructorRAII {
767 EvalInfo &EI;
768 ObjectUnderConstruction Object;
769 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
770 : EI(EI), Object(Object) {
771 bool DidInsert = EI.ObjectsUnderConstruction
772 .insert({Object, ConstructionPhase::Destroying})
773 .second;
774 (void)DidInsert;
775 assert(DidInsert && "destroyed object multiple times");
776 }
777 void startedDestroyingBases() {
778 EI.ObjectsUnderConstruction[Object] =
779 ConstructionPhase::DestroyingBases;
780 }
781 ~EvaluatingDestructorRAII() {
782 EI.ObjectsUnderConstruction.erase(Object);
783 }
784 };
785
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000786 ConstructionPhase
Richard Smith457226e2019-09-23 03:48:44 +0000787 isEvaluatingCtorDtor(APValue::LValueBase Base,
788 ArrayRef<APValue::LValuePathEntry> Path) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000789 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000790 }
791
Richard Smith37be3362019-05-04 04:00:45 +0000792 /// If we're currently speculatively evaluating, the outermost call stack
793 /// depth at which we can mutate state, otherwise 0.
794 unsigned SpeculativeEvaluationDepth = 0;
795
Richard Smith410306b2016-12-12 02:53:20 +0000796 /// The current array initialization index, if we're performing array
797 /// initialization.
798 uint64_t ArrayInitIndex = -1;
799
Richard Smith357362d2011-12-13 06:39:58 +0000800 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
801 /// notes attached to it will also be stored, otherwise they will not be.
802 bool HasActiveDiagnostic;
803
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000804 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000805 /// fold (not just why it's not strictly a constant expression)?
806 bool HasFoldFailureDiagnostic;
807
Fangrui Song407659a2018-11-30 23:41:18 +0000808 /// Whether or not we're in a context where the front end requires a
809 /// constant value.
810 bool InConstantContext;
811
Richard Smith045b2272019-09-10 21:24:09 +0000812 /// Whether we're checking that an expression is a potential constant
813 /// expression. If so, do not fail on constructs that could become constant
814 /// later on (such as a use of an undefined global).
815 bool CheckingPotentialConstantExpression = false;
816
817 /// Whether we're checking for an expression that has undefined behavior.
818 /// If so, we will produce warnings if we encounter an operation that is
819 /// always undefined.
820 bool CheckingForUndefinedBehavior = false;
821
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 enum EvaluationMode {
823 /// Evaluate as a constant expression. Stop if we find that the expression
824 /// is not a constant expression.
825 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000826
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000827 /// Evaluate as a constant expression. Stop if we find that the expression
828 /// is not a constant expression. Some expressions can be retried in the
829 /// optimizer if we don't constant fold them here, but in an unevaluated
830 /// context we try to fold them immediately since the optimizer never
831 /// gets a chance to look at it.
832 EM_ConstantExpressionUnevaluated,
833
Richard Smith045b2272019-09-10 21:24:09 +0000834 /// Fold the expression to a constant. Stop if we hit a side-effect that
835 /// we can't model.
836 EM_ConstantFold,
837
838 /// Evaluate in any way we know how. Don't worry about side-effects that
839 /// can't be modeled.
840 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000841 } EvalMode;
842
843 /// Are we checking whether the expression is a potential constant
844 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000845 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000846 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000847 }
848
849 /// Are we checking an expression for overflow?
850 // FIXME: We should check for any kind of undefined or suspicious behavior
851 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000852 bool checkingForUndefinedBehavior() const override {
853 return CheckingForUndefinedBehavior;
854 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000855
856 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000857 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
858 CallStackDepth(0), NextCallIndex(1),
859 StepsLeft(getLangOpts().ConstexprStepLimit),
860 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
861 EnableNewConstInterp(ForceNewConstInterp ||
862 getLangOpts().EnableNewConstInterp),
863 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
864 EvaluatingDecl((const ValueDecl *)nullptr),
865 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
866 HasFoldFailureDiagnostic(false), InConstantContext(false),
867 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000868
Richard Smith457226e2019-09-23 03:48:44 +0000869 ~EvalInfo() {
870 discardCleanups();
871 }
872
Richard Smith7525ff62013-05-09 07:14:00 +0000873 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
874 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000875 EvaluatingDeclValue = &Value;
876 }
877
Richard Smith357362d2011-12-13 06:39:58 +0000878 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000879 // Don't perform any constexpr calls (other than the call we're checking)
880 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000881 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000882 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000883 if (NextCallIndex == 0) {
884 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000885 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000886 return false;
887 }
Richard Smith357362d2011-12-13 06:39:58 +0000888 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
889 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000890 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000891 << getLangOpts().ConstexprCallDepth;
892 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000893 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000894
Richard Smith37be3362019-05-04 04:00:45 +0000895 std::pair<CallStackFrame *, unsigned>
896 getCallFrameAndDepth(unsigned CallIndex) {
897 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000898 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
899 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000900 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000901 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000902 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000903 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000904 --Depth;
905 }
906 if (Frame->Index == CallIndex)
907 return {Frame, Depth};
908 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000909 }
910
Richard Smitha3d3bd22013-05-08 02:12:03 +0000911 bool nextStep(const Stmt *S) {
912 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000913 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000914 return false;
915 }
916 --StepsLeft;
917 return true;
918 }
919
Richard Smith457226e2019-09-23 03:48:44 +0000920 void performLifetimeExtension() {
921 // Disable the cleanups for lifetime-extended temporaries.
922 CleanupStack.erase(
923 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
924 [](Cleanup &C) { return C.isLifetimeExtended(); }),
925 CleanupStack.end());
926 }
927
928 /// Throw away any remaining cleanups at the end of evaluation. If any
929 /// cleanups would have had a side-effect, note that as an unmodeled
930 /// side-effect and return false. Otherwise, return true.
931 bool discardCleanups() {
932 for (Cleanup &C : CleanupStack)
933 if (C.hasSideEffect())
934 if (!noteSideEffect())
935 return false;
936 return true;
937 }
938
Richard Smith357362d2011-12-13 06:39:58 +0000939 private:
Nandor Licker950b70d2019-09-13 09:46:16 +0000940 interp::Frame *getCurrentFrame() override { return CurrentCall; }
941 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
942
943 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
944 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
945
946 void setFoldFailureDiagnostic(bool Flag) override {
947 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +0000948 }
949
Nandor Licker950b70d2019-09-13 09:46:16 +0000950 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +0000951
Nandor Licker950b70d2019-09-13 09:46:16 +0000952 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +0000953
Nandor Licker950b70d2019-09-13 09:46:16 +0000954 // If we have a prior diagnostic, it will be noting that the expression
955 // isn't a constant expression. This diagnostic is more important,
956 // unless we require this evaluation to produce a constant expression.
957 //
958 // FIXME: We might want to show both diagnostics to the user in
959 // EM_ConstantFold mode.
960 bool hasPriorDiagnostic() override {
961 if (!EvalStatus.Diag->empty()) {
962 switch (EvalMode) {
963 case EM_ConstantFold:
964 case EM_IgnoreSideEffects:
965 if (!HasFoldFailureDiagnostic)
966 break;
967 // We've already failed to fold something. Keep that diagnostic.
968 LLVM_FALLTHROUGH;
969 case EM_ConstantExpression:
970 case EM_ConstantExpressionUnevaluated:
971 setActiveDiagnostic(false);
972 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +0000973 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000974 }
Nandor Licker950b70d2019-09-13 09:46:16 +0000975 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000976 }
Nandor Licker950b70d2019-09-13 09:46:16 +0000977
978 unsigned getCallStackDepth() override { return CallStackDepth; }
979
Faisal Valie690b7a2016-07-02 22:34:24 +0000980 public:
Richard Smith6d4c6582013-11-05 22:18:15 +0000981 /// Should we continue evaluation after encountering a side-effect that we
982 /// couldn't model?
983 bool keepEvaluatingAfterSideEffect() {
984 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000985 case EM_IgnoreSideEffects:
986 return true;
987
Richard Smith6d4c6582013-11-05 22:18:15 +0000988 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000989 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000990 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +0000991 // By default, assume any side effect might be valid in some other
992 // evaluation of this expression from a different context.
993 return checkingPotentialConstantExpression() ||
994 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +0000995 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000996 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000997 }
998
999 /// Note that we have had a side-effect, and determine whether we should
1000 /// keep evaluating.
1001 bool noteSideEffect() {
1002 EvalStatus.HasSideEffects = true;
1003 return keepEvaluatingAfterSideEffect();
1004 }
1005
Richard Smithce8eca52015-12-08 03:21:47 +00001006 /// Should we continue evaluation after encountering undefined behavior?
1007 bool keepEvaluatingAfterUndefinedBehavior() {
1008 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +00001009 case EM_IgnoreSideEffects:
1010 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001011 return true;
1012
Richard Smithce8eca52015-12-08 03:21:47 +00001013 case EM_ConstantExpression:
1014 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +00001015 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +00001016 }
1017 llvm_unreachable("Missed EvalMode case");
1018 }
1019
1020 /// Note that we hit something that was technically undefined behavior, but
1021 /// that we can evaluate past it (such as signed overflow or floating-point
1022 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +00001023 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +00001024 EvalStatus.HasUndefinedBehavior = true;
1025 return keepEvaluatingAfterUndefinedBehavior();
1026 }
1027
Richard Smith253c2a32012-01-27 01:14:48 +00001028 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001029 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +00001030 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +00001031 if (!StepsLeft)
1032 return false;
1033
1034 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001035 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001036 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001037 case EM_ConstantFold:
1038 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +00001039 return checkingPotentialConstantExpression() ||
1040 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001041 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001042 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001043 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001044
George Burgess IV8c892b52016-05-25 22:31:54 +00001045 /// Notes that we failed to evaluate an expression that other expressions
1046 /// directly depend on, and determine if we should keep evaluating. This
1047 /// should only be called if we actually intend to keep evaluating.
1048 ///
1049 /// Call noteSideEffect() instead if we may be able to ignore the value that
1050 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1051 ///
1052 /// (Foo(), 1) // use noteSideEffect
1053 /// (Foo() || true) // use noteSideEffect
1054 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001055 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001056 // Failure when evaluating some expression often means there is some
1057 // subexpression whose evaluation was skipped. Therefore, (because we
1058 // don't track whether we skipped an expression when unwinding after an
1059 // evaluation failure) every evaluation failure that bubbles up from a
1060 // subexpression implies that a side-effect has potentially happened. We
1061 // skip setting the HasSideEffects flag to true until we decide to
1062 // continue evaluating after that point, which happens here.
1063 bool KeepGoing = keepEvaluatingAfterFailure();
1064 EvalStatus.HasSideEffects |= KeepGoing;
1065 return KeepGoing;
1066 }
1067
Richard Smith410306b2016-12-12 02:53:20 +00001068 class ArrayInitLoopIndex {
1069 EvalInfo &Info;
1070 uint64_t OuterIndex;
1071
1072 public:
1073 ArrayInitLoopIndex(EvalInfo &Info)
1074 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1075 Info.ArrayInitIndex = 0;
1076 }
1077 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1078
1079 operator uint64_t&() { return Info.ArrayInitIndex; }
1080 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001081 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001082
1083 /// Object used to treat all foldable expressions as constant expressions.
1084 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001085 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001086 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001087 bool HadNoPriorDiags;
1088 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001089
Richard Smith6d4c6582013-11-05 22:18:15 +00001090 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1091 : Info(Info),
1092 Enabled(Enabled),
1093 HadNoPriorDiags(Info.EvalStatus.Diag &&
1094 Info.EvalStatus.Diag->empty() &&
1095 !Info.EvalStatus.HasSideEffects),
1096 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001097 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001099 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001100 void keepDiagnostics() { Enabled = false; }
1101 ~FoldConstant() {
1102 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001103 !Info.EvalStatus.HasSideEffects)
1104 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001105 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001106 }
1107 };
Richard Smith17100ba2012-02-16 02:46:34 +00001108
James Y Knight892b09b2018-10-10 02:53:43 +00001109 /// RAII object used to set the current evaluation mode to ignore
1110 /// side-effects.
1111 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001112 EvalInfo &Info;
1113 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001114 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001115 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001116 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001117 }
1118
James Y Knight892b09b2018-10-10 02:53:43 +00001119 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001120 };
1121
George Burgess IV8c892b52016-05-25 22:31:54 +00001122 /// RAII object used to optionally suppress diagnostics and side-effects from
1123 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001124 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001125 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001126 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001127 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001128
George Burgess IV8c892b52016-05-25 22:31:54 +00001129 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001130 Info = Other.Info;
1131 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001132 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001133 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001134 }
1135
1136 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001137 if (!Info)
1138 return;
1139
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001140 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001141 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001142 }
1143
Richard Smith17100ba2012-02-16 02:46:34 +00001144 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001145 SpeculativeEvaluationRAII() = default;
1146
1147 SpeculativeEvaluationRAII(
1148 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001149 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001150 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001151 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001152 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001153 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001154
1155 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1156 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1157 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001158 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001159
1160 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1161 maybeRestoreState();
1162 moveFromAndCancel(std::move(Other));
1163 return *this;
1164 }
1165
1166 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001167 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001168
1169 /// RAII object wrapping a full-expression or block scope, and handling
1170 /// the ending of the lifetime of temporaries created within it.
1171 template<bool IsFullExpression>
1172 class ScopeRAII {
1173 EvalInfo &Info;
1174 unsigned OldStackSize;
1175 public:
1176 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001177 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1178 // Push a new temporary version. This is needed to distinguish between
1179 // temporaries created in different iterations of a loop.
1180 Info.CurrentCall->pushTempVersion();
1181 }
Richard Smith457226e2019-09-23 03:48:44 +00001182 bool destroy(bool RunDestructors = true) {
1183 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1184 OldStackSize = -1U;
1185 return OK;
1186 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001187 ~ScopeRAII() {
Richard Smith457226e2019-09-23 03:48:44 +00001188 if (OldStackSize != -1U)
1189 destroy(false);
Richard Smith08d6a2c2013-07-24 07:11:57 +00001190 // Body moved to a static method to encourage the compiler to inline away
1191 // instances of this class.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001192 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001193 }
1194 private:
Richard Smith457226e2019-09-23 03:48:44 +00001195 static bool cleanup(EvalInfo &Info, bool RunDestructors, unsigned OldStackSize) {
1196 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1197 // for a full-expression scope.
1198 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1199 if (!(IsFullExpression && Info.CleanupStack[I-1].isLifetimeExtended())) {
1200 if (!Info.CleanupStack[I-1].endLifetime(Info, RunDestructors))
1201 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001202 }
1203 }
Richard Smith457226e2019-09-23 03:48:44 +00001204
1205 // Compact lifetime-extended cleanups.
1206 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1207 if (IsFullExpression)
1208 NewEnd =
1209 std::remove_if(NewEnd, Info.CleanupStack.end(),
1210 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1211 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1212 return true;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001213 }
1214 };
1215 typedef ScopeRAII<false> BlockScopeRAII;
1216 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001217}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001218
Richard Smitha8105bc2012-01-06 16:39:00 +00001219bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1220 CheckSubobjectKind CSK) {
1221 if (Invalid)
1222 return false;
1223 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001224 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001225 << CSK;
1226 setInvalid();
1227 return false;
1228 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001229 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1230 // must actually be at least one array element; even a VLA cannot have a
1231 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001232 return true;
1233}
1234
Richard Smith6f4f0f12017-10-20 22:56:25 +00001235void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1236 const Expr *E) {
1237 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1238 // Do not set the designator as invalid: we can represent this situation,
1239 // and correct handling of __builtin_object_size requires us to do so.
1240}
1241
Richard Smitha8105bc2012-01-06 16:39:00 +00001242void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001243 const Expr *E,
1244 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001245 // If we're complaining, we must be able to statically determine the size of
1246 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001247 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001248 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001249 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001250 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001251 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001252 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001253 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001254 setInvalid();
1255}
1256
Richard Smithf6f003a2011-12-16 19:06:07 +00001257CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1258 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001259 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001260 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1261 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001262 Info.CurrentCall = this;
1263 ++Info.CallStackDepth;
1264}
1265
1266CallStackFrame::~CallStackFrame() {
1267 assert(Info.CurrentCall == this && "calls retired out of order");
1268 --Info.CallStackDepth;
1269 Info.CurrentCall = Caller;
1270}
1271
Richard Smithc667cdc2019-09-18 17:37:44 +00001272static bool isRead(AccessKinds AK) {
1273 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1274}
1275
Richard Smithdebad642019-05-12 09:39:08 +00001276static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001277 switch (AK) {
1278 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001279 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001280 case AK_MemberCall:
1281 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001282 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001283 return false;
1284 case AK_Assign:
1285 case AK_Increment:
1286 case AK_Decrement:
1287 return true;
1288 }
1289 llvm_unreachable("unknown access kind");
1290}
1291
1292/// Is this an access per the C++ definition?
1293static bool isFormalAccess(AccessKinds AK) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001294 return isRead(AK) || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001295}
1296
Richard Smithf6f003a2011-12-16 19:06:07 +00001297namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001298 struct ComplexValue {
1299 private:
1300 bool IsInt;
1301
1302 public:
1303 APSInt IntReal, IntImag;
1304 APFloat FloatReal, FloatImag;
1305
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001306 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001307
1308 void makeComplexFloat() { IsInt = false; }
1309 bool isComplexFloat() const { return !IsInt; }
1310 APFloat &getComplexFloatReal() { return FloatReal; }
1311 APFloat &getComplexFloatImag() { return FloatImag; }
1312
1313 void makeComplexInt() { IsInt = true; }
1314 bool isComplexInt() const { return IsInt; }
1315 APSInt &getComplexIntReal() { return IntReal; }
1316 APSInt &getComplexIntImag() { return IntImag; }
1317
Richard Smith2e312c82012-03-03 22:46:17 +00001318 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001319 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001320 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001321 else
Richard Smith2e312c82012-03-03 22:46:17 +00001322 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001323 }
Richard Smith2e312c82012-03-03 22:46:17 +00001324 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001325 assert(v.isComplexFloat() || v.isComplexInt());
1326 if (v.isComplexFloat()) {
1327 makeComplexFloat();
1328 FloatReal = v.getComplexFloatReal();
1329 FloatImag = v.getComplexFloatImag();
1330 } else {
1331 makeComplexInt();
1332 IntReal = v.getComplexIntReal();
1333 IntImag = v.getComplexIntImag();
1334 }
1335 }
John McCall93d91dc2010-05-07 17:22:02 +00001336 };
John McCall45d55e42010-05-07 21:00:08 +00001337
1338 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001339 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001340 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001341 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001342 bool IsNullPtr : 1;
1343 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001344
Richard Smithce40ad62011-11-12 22:28:03 +00001345 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001346 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001347 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001348 SubobjectDesignator &getLValueDesignator() { return Designator; }
1349 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001350 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001351
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001352 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1353 unsigned getLValueVersion() const { return Base.getVersion(); }
1354
Richard Smith2e312c82012-03-03 22:46:17 +00001355 void moveInto(APValue &V) const {
1356 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001357 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001358 else {
1359 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001360 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001361 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001362 }
John McCall45d55e42010-05-07 21:00:08 +00001363 }
Richard Smith2e312c82012-03-03 22:46:17 +00001364 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001365 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001366 Base = V.getLValueBase();
1367 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001368 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001369 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001370 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001371 }
1372
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001373 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001374#ifndef NDEBUG
1375 // We only allow a few types of invalid bases. Enforce that here.
1376 if (BInvalid) {
1377 const auto *E = B.get<const Expr *>();
1378 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1379 "Unexpected type of invalid base");
1380 }
1381#endif
1382
Richard Smithce40ad62011-11-12 22:28:03 +00001383 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001384 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001385 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001386 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001387 IsNullPtr = false;
1388 }
1389
1390 void setNull(QualType PointerTy, uint64_t TargetVal) {
1391 Base = (Expr *)nullptr;
1392 Offset = CharUnits::fromQuantity(TargetVal);
1393 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001394 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1395 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001396 }
1397
George Burgess IV3a03fab2015-09-04 21:28:13 +00001398 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001399 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001400 }
1401
Hubert Tong147b7432018-12-12 16:53:43 +00001402 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001403 // Check that this LValue is not based on a null pointer. If it is, produce
1404 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001405 template <typename GenDiagType>
1406 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001407 if (Designator.Invalid)
1408 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001409 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001410 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001411 Designator.setInvalid();
1412 return false;
1413 }
1414 return true;
1415 }
1416
Hubert Tong147b7432018-12-12 16:53:43 +00001417 public:
1418 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1419 CheckSubobjectKind CSK) {
1420 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1421 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1422 });
1423 }
1424
1425 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1426 AccessKinds AK) {
1427 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1428 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1429 });
1430 }
1431
Richard Smitha8105bc2012-01-06 16:39:00 +00001432 // Check this LValue refers to an object. If not, set the designator to be
1433 // invalid and emit a diagnostic.
1434 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001435 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001436 Designator.checkSubobject(Info, E, CSK);
1437 }
1438
1439 void addDecl(EvalInfo &Info, const Expr *E,
1440 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001441 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1442 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001443 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001444 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1445 if (!Designator.Entries.empty()) {
1446 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1447 Designator.setInvalid();
1448 return;
1449 }
Richard Smithefdb5032017-11-15 03:03:56 +00001450 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1451 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1452 Designator.FirstEntryIsAnUnsizedArray = true;
1453 Designator.addUnsizedArrayUnchecked(ElemTy);
1454 }
George Burgess IVe3763372016-12-22 02:50:20 +00001455 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001456 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001457 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1458 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001459 }
Richard Smith66c96992012-02-18 22:04:06 +00001460 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001461 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1462 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001463 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001464 void clearIsNullPointer() {
1465 IsNullPtr = false;
1466 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001467 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1468 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001469 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1470 // but we're not required to diagnose it and it's valid in C++.)
1471 if (!Index)
1472 return;
1473
1474 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1475 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1476 // offsets.
1477 uint64_t Offset64 = Offset.getQuantity();
1478 uint64_t ElemSize64 = ElementSize.getQuantity();
1479 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1480 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1481
1482 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001483 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001484 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001485 }
1486 void adjustOffset(CharUnits N) {
1487 Offset += N;
1488 if (N.getQuantity())
1489 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001490 }
John McCall45d55e42010-05-07 21:00:08 +00001491 };
Richard Smith027bf112011-11-17 22:56:20 +00001492
1493 struct MemberPtr {
1494 MemberPtr() {}
1495 explicit MemberPtr(const ValueDecl *Decl) :
1496 DeclAndIsDerivedMember(Decl, false), Path() {}
1497
1498 /// The member or (direct or indirect) field referred to by this member
1499 /// pointer, or 0 if this is a null member pointer.
1500 const ValueDecl *getDecl() const {
1501 return DeclAndIsDerivedMember.getPointer();
1502 }
1503 /// Is this actually a member of some type derived from the relevant class?
1504 bool isDerivedMember() const {
1505 return DeclAndIsDerivedMember.getInt();
1506 }
1507 /// Get the class which the declaration actually lives in.
1508 const CXXRecordDecl *getContainingRecord() const {
1509 return cast<CXXRecordDecl>(
1510 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1511 }
1512
Richard Smith2e312c82012-03-03 22:46:17 +00001513 void moveInto(APValue &V) const {
1514 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001515 }
Richard Smith2e312c82012-03-03 22:46:17 +00001516 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001517 assert(V.isMemberPointer());
1518 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1519 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1520 Path.clear();
1521 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1522 Path.insert(Path.end(), P.begin(), P.end());
1523 }
1524
1525 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1526 /// whether the member is a member of some class derived from the class type
1527 /// of the member pointer.
1528 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1529 /// Path - The path of base/derived classes from the member declaration's
1530 /// class (exclusive) to the class type of the member pointer (inclusive).
1531 SmallVector<const CXXRecordDecl*, 4> Path;
1532
1533 /// Perform a cast towards the class of the Decl (either up or down the
1534 /// hierarchy).
1535 bool castBack(const CXXRecordDecl *Class) {
1536 assert(!Path.empty());
1537 const CXXRecordDecl *Expected;
1538 if (Path.size() >= 2)
1539 Expected = Path[Path.size() - 2];
1540 else
1541 Expected = getContainingRecord();
1542 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1543 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1544 // if B does not contain the original member and is not a base or
1545 // derived class of the class containing the original member, the result
1546 // of the cast is undefined.
1547 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1548 // (D::*). We consider that to be a language defect.
1549 return false;
1550 }
1551 Path.pop_back();
1552 return true;
1553 }
1554 /// Perform a base-to-derived member pointer cast.
1555 bool castToDerived(const CXXRecordDecl *Derived) {
1556 if (!getDecl())
1557 return true;
1558 if (!isDerivedMember()) {
1559 Path.push_back(Derived);
1560 return true;
1561 }
1562 if (!castBack(Derived))
1563 return false;
1564 if (Path.empty())
1565 DeclAndIsDerivedMember.setInt(false);
1566 return true;
1567 }
1568 /// Perform a derived-to-base member pointer cast.
1569 bool castToBase(const CXXRecordDecl *Base) {
1570 if (!getDecl())
1571 return true;
1572 if (Path.empty())
1573 DeclAndIsDerivedMember.setInt(true);
1574 if (isDerivedMember()) {
1575 Path.push_back(Base);
1576 return true;
1577 }
1578 return castBack(Base);
1579 }
1580 };
Richard Smith357362d2011-12-13 06:39:58 +00001581
Richard Smith7bb00672012-02-01 01:42:44 +00001582 /// Compare two member pointers, which are assumed to be of the same type.
1583 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1584 if (!LHS.getDecl() || !RHS.getDecl())
1585 return !LHS.getDecl() && !RHS.getDecl();
1586 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1587 return false;
1588 return LHS.Path == RHS.Path;
1589 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001590}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001591
Richard Smith2e312c82012-03-03 22:46:17 +00001592static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001593static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1594 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001595 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001596static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1597 bool InvalidBaseOK = false);
1598static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1599 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001600static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1601 EvalInfo &Info);
1602static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001603static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001604static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001605 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001606static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001607static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001608static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1609 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001610static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001611
Leonard Chand3f3e162019-01-18 21:04:25 +00001612/// Evaluate an integer or fixed point expression into an APResult.
1613static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1614 EvalInfo &Info);
1615
1616/// Evaluate only a fixed point expression into an APResult.
1617static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1618 EvalInfo &Info);
1619
Chris Lattner05706e882008-07-11 18:11:29 +00001620//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001621// Misc utilities
1622//===----------------------------------------------------------------------===//
1623
Richard Smithd6cc1982017-01-31 02:23:02 +00001624/// Negate an APSInt in place, converting it to a signed form if necessary, and
1625/// preserving its value (by extending by up to one bit as needed).
1626static void negateAsSigned(APSInt &Int) {
1627 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1628 Int = Int.extend(Int.getBitWidth() + 1);
1629 Int.setIsSigned(true);
1630 }
1631 Int = -Int;
1632}
1633
Richard Smith457226e2019-09-23 03:48:44 +00001634template<typename KeyT>
1635APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1636 bool IsLifetimeExtended, LValue &LV) {
1637 unsigned Version = Info.CurrentCall->getTempVersion();
1638 APValue::LValueBase Base(Key, Index, Version);
1639 LV.set(Base);
1640 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1641 assert(Result.isAbsent() && "temporary created multiple times");
1642 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1643 return Result;
1644}
1645
Richard Smith84401042013-06-03 05:03:02 +00001646/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001647void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001648 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001649 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1650 !isa<CXXConstructorDecl>(Callee) &&
1651 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001652
1653 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001654 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001655
Nandor Licker950b70d2019-09-13 09:46:16 +00001656 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001657 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001658 This->moveInto(Val);
1659 Val.printPretty(Out, Info.Ctx,
1660 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001661 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001662 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001663 IsMemberCall = false;
1664 }
1665
Nandor Licker950b70d2019-09-13 09:46:16 +00001666 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1667 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001668 if (ArgIndex > (unsigned)IsMemberCall)
1669 Out << ", ";
1670
1671 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001672 const APValue &Arg = Arguments[ArgIndex];
1673 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001674
1675 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001676 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001677 }
1678
1679 Out << ')';
1680}
1681
Richard Smithd9f663b2013-04-22 15:31:51 +00001682/// Evaluate an expression to see if it had side-effects, and discard its
1683/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001684/// \return \c true if the caller should keep evaluating.
1685static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001686 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001687 if (!Evaluate(Scratch, Info, E))
1688 // We don't need the value, but we might have skipped a side effect here.
1689 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001690 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001691}
1692
Richard Smithd62306a2011-11-10 06:34:14 +00001693/// Should this call expression be treated as a string literal?
1694static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001695 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001696 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1697 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1698}
1699
Richard Smithce40ad62011-11-12 22:28:03 +00001700static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001701 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1702 // constant expression of pointer type that evaluates to...
1703
1704 // ... a null pointer value, or a prvalue core constant expression of type
1705 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001706 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001707
Richard Smithce40ad62011-11-12 22:28:03 +00001708 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1709 // ... the address of an object with static storage duration,
1710 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1711 return VD->hasGlobalStorage();
1712 // ... the address of a function,
1713 return isa<FunctionDecl>(D);
1714 }
1715
Richard Smithee0ce3022019-05-17 07:06:46 +00001716 if (B.is<TypeInfoLValue>())
1717 return true;
1718
Richard Smithce40ad62011-11-12 22:28:03 +00001719 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001720 switch (E->getStmtClass()) {
1721 default:
1722 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001723 case Expr::CompoundLiteralExprClass: {
1724 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1725 return CLE->isFileScope() && CLE->isLValue();
1726 }
Richard Smithe6c01442013-06-05 00:46:14 +00001727 case Expr::MaterializeTemporaryExprClass:
1728 // A materialized temporary might have been lifetime-extended to static
1729 // storage duration.
1730 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001731 // A string literal has static storage duration.
1732 case Expr::StringLiteralClass:
1733 case Expr::PredefinedExprClass:
1734 case Expr::ObjCStringLiteralClass:
1735 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001736 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001737 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001738 case Expr::ObjCBoxedExprClass:
1739 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001740 case Expr::CallExprClass:
1741 return IsStringLiteralCall(cast<CallExpr>(E));
1742 // For GCC compatibility, &&label has static storage duration.
1743 case Expr::AddrLabelExprClass:
1744 return true;
1745 // A Block literal expression may be used as the initialization value for
1746 // Block variables at global or local static scope.
1747 case Expr::BlockExprClass:
1748 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001749 case Expr::ImplicitValueInitExprClass:
1750 // FIXME:
1751 // We can never form an lvalue with an implicit value initialization as its
1752 // base through expression evaluation, so these only appear in one case: the
1753 // implicit variable declaration we invent when checking whether a constexpr
1754 // constructor can produce a constant expression. We must assume that such
1755 // an expression might be a global lvalue.
1756 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001757 }
John McCall95007602010-05-10 23:27:23 +00001758}
1759
Richard Smith06f71b52018-08-04 00:57:17 +00001760static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1761 return LVal.Base.dyn_cast<const ValueDecl*>();
1762}
1763
1764static bool IsLiteralLValue(const LValue &Value) {
1765 if (Value.getLValueCallIndex())
1766 return false;
1767 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1768 return E && !isa<MaterializeTemporaryExpr>(E);
1769}
1770
1771static bool IsWeakLValue(const LValue &Value) {
1772 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1773 return Decl && Decl->isWeak();
1774}
1775
1776static bool isZeroSized(const LValue &Value) {
1777 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1778 if (Decl && isa<VarDecl>(Decl)) {
1779 QualType Ty = Decl->getType();
1780 if (Ty->isArrayType())
1781 return Ty->isIncompleteType() ||
1782 Decl->getASTContext().getTypeSize(Ty) == 0;
1783 }
1784 return false;
1785}
1786
1787static bool HasSameBase(const LValue &A, const LValue &B) {
1788 if (!A.getLValueBase())
1789 return !B.getLValueBase();
1790 if (!B.getLValueBase())
1791 return false;
1792
1793 if (A.getLValueBase().getOpaqueValue() !=
1794 B.getLValueBase().getOpaqueValue()) {
1795 const Decl *ADecl = GetLValueBaseDecl(A);
1796 if (!ADecl)
1797 return false;
1798 const Decl *BDecl = GetLValueBaseDecl(B);
1799 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1800 return false;
1801 }
1802
1803 return IsGlobalLValue(A.getLValueBase()) ||
1804 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1805 A.getLValueVersion() == B.getLValueVersion());
1806}
1807
Richard Smithb228a862012-02-15 02:18:13 +00001808static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1809 assert(Base && "no location for a null lvalue");
1810 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1811 if (VD)
1812 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001813 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1814 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1815 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001816}
1817
Richard Smith80815602011-11-07 05:07:52 +00001818/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001819/// value for an address or reference constant expression. Return true if we
1820/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001821static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001822 QualType Type, const LValue &LVal,
1823 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001824 bool IsReferenceType = Type->isReferenceType();
1825
Richard Smith357362d2011-12-13 06:39:58 +00001826 APValue::LValueBase Base = LVal.getLValueBase();
1827 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1828
Richard Smith0dea49e2012-02-18 04:58:18 +00001829 // Check that the object is a global. Note that the fake 'this' object we
1830 // manufacture when checking potential constant expressions is conservatively
1831 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001832 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001833 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001834 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001835 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001836 << IsReferenceType << !Designator.Entries.empty()
1837 << !!VD << VD;
1838 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001839 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001840 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001841 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001842 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001843 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001844 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001845 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001846 LVal.getLValueCallIndex() == 0) &&
1847 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001848
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001849 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1850 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001851 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001852 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001853 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001854
Hans Wennborg82dd8772014-06-25 22:19:48 +00001855 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001856 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001857 return false;
1858 }
1859 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1860 // __declspec(dllimport) must be handled very carefully:
1861 // We must never initialize an expression with the thunk in C++.
1862 // Doing otherwise would allow the same id-expression to yield
1863 // different addresses for the same function in different translation
1864 // units. However, this means that we must dynamically initialize the
1865 // expression with the contents of the import address table at runtime.
1866 //
1867 // The C language has no notion of ODR; furthermore, it has no notion of
1868 // dynamic initialization. This means that we are permitted to
1869 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001870 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1871 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001872 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001873 }
1874 }
1875
Richard Smitha8105bc2012-01-06 16:39:00 +00001876 // Allow address constant expressions to be past-the-end pointers. This is
1877 // an extension: the standard requires them to point to an object.
1878 if (!IsReferenceType)
1879 return true;
1880
1881 // A reference constant expression must refer to an object.
1882 if (!Base) {
1883 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001884 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001885 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001886 }
1887
Richard Smith357362d2011-12-13 06:39:58 +00001888 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001889 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001890 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001891 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001892 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001893 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001894 }
1895
Richard Smith80815602011-11-07 05:07:52 +00001896 return true;
1897}
1898
Reid Klecknercd016d82017-07-07 22:04:29 +00001899/// Member pointers are constant expressions unless they point to a
1900/// non-virtual dllimport member function.
1901static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1902 SourceLocation Loc,
1903 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001904 const APValue &Value,
1905 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001906 const ValueDecl *Member = Value.getMemberPointerDecl();
1907 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1908 if (!FD)
1909 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001910 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1911 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001912}
1913
Richard Smithfddd3842011-12-30 21:15:51 +00001914/// Check that this core constant expression is of literal type, and if not,
1915/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001916static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001917 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001918 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001919 return true;
1920
Richard Smith7525ff62013-05-09 07:14:00 +00001921 // C++1y: A constant initializer for an object o [...] may also invoke
1922 // constexpr constructors for o and its subobjects even if those objects
1923 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001924 //
1925 // C++11 missed this detail for aggregates, so classes like this:
1926 // struct foo_t { union { int i; volatile int j; } u; };
1927 // are not (obviously) initializable like so:
1928 // __attribute__((__require_constant_initialization__))
1929 // static const foo_t x = {{0}};
1930 // because "i" is a subobject with non-literal initialization (due to the
1931 // volatile member of the union). See:
1932 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1933 // Therefore, we use the C++1y behavior.
1934 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001935 return true;
1936
Richard Smithfddd3842011-12-30 21:15:51 +00001937 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001938 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001939 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001940 << E->getType();
1941 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001942 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001943 return false;
1944}
1945
Richard Smithc667cdc2019-09-18 17:37:44 +00001946enum class CheckEvaluationResultKind {
1947 ConstantExpression,
1948 FullyInitialized,
1949};
1950
Reid Kleckner1a840d22018-05-10 18:57:35 +00001951static bool
Richard Smithc667cdc2019-09-18 17:37:44 +00001952CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
1953 SourceLocation DiagLoc, QualType Type,
1954 const APValue &Value, Expr::ConstExprUsage Usage,
1955 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00001956 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001957 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001958 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00001959 if (SubobjectLoc.isValid())
1960 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00001961 return false;
1962 }
1963
Richard Smith77be48a2014-07-31 06:31:19 +00001964 // We allow _Atomic(T) to be initialized from anything that T can be
1965 // initialized from.
1966 if (const AtomicType *AT = Type->getAs<AtomicType>())
1967 Type = AT->getValueType();
1968
Richard Smithb228a862012-02-15 02:18:13 +00001969 // Core issue 1454: For a literal constant expression of array or class type,
1970 // each subobject of its value shall have been initialized by a constant
1971 // expression.
1972 if (Value.isArray()) {
1973 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1974 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001975 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1976 Value.getArrayInitializedElt(I), Usage,
1977 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00001978 return false;
1979 }
1980 if (!Value.hasArrayFiller())
1981 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00001982 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1983 Value.getArrayFiller(), Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00001984 }
Richard Smithb228a862012-02-15 02:18:13 +00001985 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001986 return CheckEvaluationResult(
1987 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
1988 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00001989 }
1990 if (Value.isStruct()) {
1991 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1992 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1993 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001994 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001995 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
1996 Value.getStructBase(BaseIndex), Usage,
1997 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00001998 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001999 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002000 }
2001 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002002 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002003 if (I->isUnnamedBitfield())
2004 continue;
2005
Richard Smithc667cdc2019-09-18 17:37:44 +00002006 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2007 Value.getStructField(I->getFieldIndex()),
2008 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00002009 return false;
2010 }
2011 }
2012
Richard Smithc667cdc2019-09-18 17:37:44 +00002013 if (Value.isLValue() &&
2014 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00002015 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002016 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002017 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002018 }
2019
Richard Smithc667cdc2019-09-18 17:37:44 +00002020 if (Value.isMemberPointer() &&
2021 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00002022 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002023
Richard Smithb228a862012-02-15 02:18:13 +00002024 // Everything else is fine.
2025 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002026}
2027
Richard Smithc667cdc2019-09-18 17:37:44 +00002028/// Check that this core constant expression value is a valid value for a
2029/// constant expression. If not, report an appropriate diagnostic. Does not
2030/// check that the expression is of literal type.
2031static bool
2032CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2033 const APValue &Value,
2034 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2035 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2036 Info, DiagLoc, Type, Value, Usage);
2037}
2038
2039/// Check that this evaluated value is fully-initialized and can be loaded by
2040/// an lvalue-to-rvalue conversion.
2041static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2042 QualType Type, const APValue &Value) {
2043 return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
2044 Info, DiagLoc, Type, Value,
2045 Expr::EvaluateForCodeGen);
2046}
2047
Richard Smith2e312c82012-03-03 22:46:17 +00002048static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002049 // A null base expression indicates a null pointer. These are always
2050 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002051 if (!Value.getLValueBase()) {
2052 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002053 return true;
2054 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002055
Richard Smith027bf112011-11-17 22:56:20 +00002056 // We have a non-null base. These are generally known to be true, but if it's
2057 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002058 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002059 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002060 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002061}
2062
Richard Smith2e312c82012-03-03 22:46:17 +00002063static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002064 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002065 case APValue::None:
2066 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002067 return false;
2068 case APValue::Int:
2069 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002070 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002071 case APValue::FixedPoint:
2072 Result = Val.getFixedPoint().getBoolValue();
2073 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002074 case APValue::Float:
2075 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002076 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002077 case APValue::ComplexInt:
2078 Result = Val.getComplexIntReal().getBoolValue() ||
2079 Val.getComplexIntImag().getBoolValue();
2080 return true;
2081 case APValue::ComplexFloat:
2082 Result = !Val.getComplexFloatReal().isZero() ||
2083 !Val.getComplexFloatImag().isZero();
2084 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002085 case APValue::LValue:
2086 return EvalPointerValueAsBool(Val, Result);
2087 case APValue::MemberPointer:
2088 Result = Val.getMemberPointerDecl();
2089 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002090 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002091 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002092 case APValue::Struct:
2093 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002094 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002095 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002096 }
2097
Richard Smith11562c52011-10-28 17:51:58 +00002098 llvm_unreachable("unknown APValue kind");
2099}
2100
2101static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2102 EvalInfo &Info) {
2103 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002104 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002105 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002106 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002107 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002108}
2109
Richard Smith357362d2011-12-13 06:39:58 +00002110template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002111static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002112 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002113 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002114 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002115 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002116}
2117
2118static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2119 QualType SrcType, const APFloat &Value,
2120 QualType DestType, APSInt &Result) {
2121 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002122 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002123 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002124
Richard Smith357362d2011-12-13 06:39:58 +00002125 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002126 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002127 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2128 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002129 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002130 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002131}
2132
Richard Smith357362d2011-12-13 06:39:58 +00002133static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2134 QualType SrcType, QualType DestType,
2135 APFloat &Result) {
2136 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002137 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002138 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2139 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002140 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002141}
2142
Richard Smith911e1422012-01-30 22:27:01 +00002143static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2144 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002145 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002146 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002147 // Figure out if this is a truncate, extend or noop cast.
2148 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002149 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002150 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002151 if (DestType->isBooleanType())
2152 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002153 return Result;
2154}
2155
Richard Smith357362d2011-12-13 06:39:58 +00002156static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2157 QualType SrcType, const APSInt &Value,
2158 QualType DestType, APFloat &Result) {
2159 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002160 Result.convertFromAPInt(Value, Value.isSigned(),
2161 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002162 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002163}
2164
Richard Smith49ca8aa2013-08-06 07:09:20 +00002165static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2166 APValue &Value, const FieldDecl *FD) {
2167 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2168
2169 if (!Value.isInt()) {
2170 // Trying to store a pointer-cast-to-integer into a bitfield.
2171 // FIXME: In this case, we should provide the diagnostic for casting
2172 // a pointer to an integer.
2173 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002174 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002175 return false;
2176 }
2177
2178 APSInt &Int = Value.getInt();
2179 unsigned OldBitWidth = Int.getBitWidth();
2180 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2181 if (NewBitWidth < OldBitWidth)
2182 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2183 return true;
2184}
2185
Eli Friedman803acb32011-12-22 03:51:45 +00002186static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2187 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002188 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002189 if (!Evaluate(SVal, Info, E))
2190 return false;
2191 if (SVal.isInt()) {
2192 Res = SVal.getInt();
2193 return true;
2194 }
2195 if (SVal.isFloat()) {
2196 Res = SVal.getFloat().bitcastToAPInt();
2197 return true;
2198 }
2199 if (SVal.isVector()) {
2200 QualType VecTy = E->getType();
2201 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2202 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2203 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2204 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2205 Res = llvm::APInt::getNullValue(VecSize);
2206 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2207 APValue &Elt = SVal.getVectorElt(i);
2208 llvm::APInt EltAsInt;
2209 if (Elt.isInt()) {
2210 EltAsInt = Elt.getInt();
2211 } else if (Elt.isFloat()) {
2212 EltAsInt = Elt.getFloat().bitcastToAPInt();
2213 } else {
2214 // Don't try to handle vectors of anything other than int or float
2215 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002216 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002217 return false;
2218 }
2219 unsigned BaseEltSize = EltAsInt.getBitWidth();
2220 if (BigEndian)
2221 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2222 else
2223 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2224 }
2225 return true;
2226 }
2227 // Give up if the input isn't an int, float, or vector. For example, we
2228 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002229 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002230 return false;
2231}
2232
Richard Smith43e77732013-05-07 04:50:00 +00002233/// Perform the given integer operation, which is known to need at most BitWidth
2234/// bits, and check for overflow in the original type (if that type was not an
2235/// unsigned type).
2236template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002237static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2238 const APSInt &LHS, const APSInt &RHS,
2239 unsigned BitWidth, Operation Op,
2240 APSInt &Result) {
2241 if (LHS.isUnsigned()) {
2242 Result = Op(LHS, RHS);
2243 return true;
2244 }
Richard Smith43e77732013-05-07 04:50:00 +00002245
2246 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002247 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002248 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002249 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002250 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002251 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002252 << Result.toString(10) << E->getType();
2253 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002254 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002255 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002256 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002257}
2258
2259/// Perform the given binary integer operation.
2260static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2261 BinaryOperatorKind Opcode, APSInt RHS,
2262 APSInt &Result) {
2263 switch (Opcode) {
2264 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002265 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002266 return false;
2267 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002268 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2269 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002270 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002271 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2272 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002273 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002274 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2275 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002276 case BO_And: Result = LHS & RHS; return true;
2277 case BO_Xor: Result = LHS ^ RHS; return true;
2278 case BO_Or: Result = LHS | RHS; return true;
2279 case BO_Div:
2280 case BO_Rem:
2281 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002282 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002283 return false;
2284 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002285 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2286 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2287 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002288 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2289 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002290 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2291 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002292 return true;
2293 case BO_Shl: {
2294 if (Info.getLangOpts().OpenCL)
2295 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2296 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2297 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2298 RHS.isUnsigned());
2299 else if (RHS.isSigned() && RHS.isNegative()) {
2300 // During constant-folding, a negative shift is an opposite shift. Such
2301 // a shift is not a constant expression.
2302 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2303 RHS = -RHS;
2304 goto shift_right;
2305 }
2306 shift_left:
2307 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2308 // the shifted type.
2309 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2310 if (SA != RHS) {
2311 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2312 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002313 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002314 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2315 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002316 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2317 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002318 if (LHS.isNegative())
2319 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2320 else if (LHS.countLeadingZeros() < SA)
2321 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2322 }
2323 Result = LHS << SA;
2324 return true;
2325 }
2326 case BO_Shr: {
2327 if (Info.getLangOpts().OpenCL)
2328 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2329 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2330 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2331 RHS.isUnsigned());
2332 else if (RHS.isSigned() && RHS.isNegative()) {
2333 // During constant-folding, a negative shift is an opposite shift. Such a
2334 // shift is not a constant expression.
2335 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2336 RHS = -RHS;
2337 goto shift_left;
2338 }
2339 shift_right:
2340 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2341 // shifted type.
2342 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2343 if (SA != RHS)
2344 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2345 << RHS << E->getType() << LHS.getBitWidth();
2346 Result = LHS >> SA;
2347 return true;
2348 }
2349
2350 case BO_LT: Result = LHS < RHS; return true;
2351 case BO_GT: Result = LHS > RHS; return true;
2352 case BO_LE: Result = LHS <= RHS; return true;
2353 case BO_GE: Result = LHS >= RHS; return true;
2354 case BO_EQ: Result = LHS == RHS; return true;
2355 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002356 case BO_Cmp:
2357 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002358 }
2359}
2360
Richard Smith861b5b52013-05-07 23:34:45 +00002361/// Perform the given binary floating-point operation, in-place, on LHS.
2362static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2363 APFloat &LHS, BinaryOperatorKind Opcode,
2364 const APFloat &RHS) {
2365 switch (Opcode) {
2366 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002367 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002368 return false;
2369 case BO_Mul:
2370 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2371 break;
2372 case BO_Add:
2373 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2374 break;
2375 case BO_Sub:
2376 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2377 break;
2378 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002379 // [expr.mul]p4:
2380 // If the second operand of / or % is zero the behavior is undefined.
2381 if (RHS.isZero())
2382 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002383 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2384 break;
2385 }
2386
Richard Smith9e52c432019-07-06 21:05:52 +00002387 // [expr.pre]p4:
2388 // If during the evaluation of an expression, the result is not
2389 // mathematically defined [...], the behavior is undefined.
2390 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2391 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002392 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002393 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002394 }
Richard Smith861b5b52013-05-07 23:34:45 +00002395 return true;
2396}
2397
Richard Smitha8105bc2012-01-06 16:39:00 +00002398/// Cast an lvalue referring to a base subobject to a derived class, by
2399/// truncating the lvalue's path to the given length.
2400static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2401 const RecordDecl *TruncatedType,
2402 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002403 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002404
2405 // Check we actually point to a derived class object.
2406 if (TruncatedElements == D.Entries.size())
2407 return true;
2408 assert(TruncatedElements >= D.MostDerivedPathLength &&
2409 "not casting to a derived class");
2410 if (!Result.checkSubobject(Info, E, CSK_Derived))
2411 return false;
2412
2413 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002414 const RecordDecl *RD = TruncatedType;
2415 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002416 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002417 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2418 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002419 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002420 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002421 else
Richard Smithd62306a2011-11-10 06:34:14 +00002422 Result.Offset -= Layout.getBaseClassOffset(Base);
2423 RD = Base;
2424 }
Richard Smith027bf112011-11-17 22:56:20 +00002425 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002426 return true;
2427}
2428
John McCalld7bca762012-05-01 00:38:49 +00002429static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002430 const CXXRecordDecl *Derived,
2431 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002432 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002433 if (!RL) {
2434 if (Derived->isInvalidDecl()) return false;
2435 RL = &Info.Ctx.getASTRecordLayout(Derived);
2436 }
2437
Richard Smithd62306a2011-11-10 06:34:14 +00002438 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002439 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002440 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002441}
2442
Richard Smitha8105bc2012-01-06 16:39:00 +00002443static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002444 const CXXRecordDecl *DerivedDecl,
2445 const CXXBaseSpecifier *Base) {
2446 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2447
John McCalld7bca762012-05-01 00:38:49 +00002448 if (!Base->isVirtual())
2449 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002450
Richard Smitha8105bc2012-01-06 16:39:00 +00002451 SubobjectDesignator &D = Obj.Designator;
2452 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002453 return false;
2454
Richard Smitha8105bc2012-01-06 16:39:00 +00002455 // Extract most-derived object and corresponding type.
2456 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2457 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2458 return false;
2459
2460 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002461 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002462 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2463 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002464 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002465 return true;
2466}
2467
Richard Smith84401042013-06-03 05:03:02 +00002468static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2469 QualType Type, LValue &Result) {
2470 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2471 PathE = E->path_end();
2472 PathI != PathE; ++PathI) {
2473 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2474 *PathI))
2475 return false;
2476 Type = (*PathI)->getType();
2477 }
2478 return true;
2479}
2480
Richard Smith921f1322019-05-13 23:35:21 +00002481/// Cast an lvalue referring to a derived class to a known base subobject.
2482static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2483 const CXXRecordDecl *DerivedRD,
2484 const CXXRecordDecl *BaseRD) {
2485 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2486 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2487 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2488 llvm_unreachable("Class must be derived from the passed in base class!");
2489
2490 for (CXXBasePathElement &Elem : Paths.front())
2491 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2492 return false;
2493 return true;
2494}
2495
Richard Smithd62306a2011-11-10 06:34:14 +00002496/// Update LVal to refer to the given field, which must be a member of the type
2497/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002498static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002499 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002500 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002501 if (!RL) {
2502 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002503 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002504 }
Richard Smithd62306a2011-11-10 06:34:14 +00002505
2506 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002507 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002508 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002509 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002510}
2511
Richard Smith1b78b3d2012-01-25 22:15:11 +00002512/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002513static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002514 LValue &LVal,
2515 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002516 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002517 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002518 return false;
2519 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002520}
2521
Richard Smithd62306a2011-11-10 06:34:14 +00002522/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002523static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2524 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002525 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2526 // extension.
2527 if (Type->isVoidType() || Type->isFunctionType()) {
2528 Size = CharUnits::One();
2529 return true;
2530 }
2531
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002532 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002533 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002534 return false;
2535 }
2536
Richard Smithd62306a2011-11-10 06:34:14 +00002537 if (!Type->isConstantSizeType()) {
2538 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002539 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002540 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002541 return false;
2542 }
2543
2544 Size = Info.Ctx.getTypeSizeInChars(Type);
2545 return true;
2546}
2547
2548/// Update a pointer value to model pointer arithmetic.
2549/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002550/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002551/// \param LVal - The pointer value to be updated.
2552/// \param EltTy - The pointee type represented by LVal.
2553/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002554static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2555 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002556 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002557 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002558 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002559 return false;
2560
Yaxun Liu402804b2016-12-15 08:09:08 +00002561 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002562 return true;
2563}
2564
Richard Smithd6cc1982017-01-31 02:23:02 +00002565static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2566 LValue &LVal, QualType EltTy,
2567 int64_t Adjustment) {
2568 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2569 APSInt::get(Adjustment));
2570}
2571
Richard Smith66c96992012-02-18 22:04:06 +00002572/// Update an lvalue to refer to a component of a complex number.
2573/// \param Info - Information about the ongoing evaluation.
2574/// \param LVal - The lvalue to be updated.
2575/// \param EltTy - The complex number's component type.
2576/// \param Imag - False for the real component, true for the imaginary.
2577static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2578 LValue &LVal, QualType EltTy,
2579 bool Imag) {
2580 if (Imag) {
2581 CharUnits SizeOfComponent;
2582 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2583 return false;
2584 LVal.Offset += SizeOfComponent;
2585 }
2586 LVal.addComplex(Info, E, EltTy, Imag);
2587 return true;
2588}
2589
Richard Smith27908702011-10-24 17:54:18 +00002590/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002591///
2592/// \param Info Information about the ongoing evaluation.
2593/// \param E An expression to be used when printing diagnostics.
2594/// \param VD The variable whose initializer should be obtained.
2595/// \param Frame The frame in which the variable was created. Must be null
2596/// if this variable is not local to the evaluation.
2597/// \param Result Filled in with a pointer to the value of the variable.
2598static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2599 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002600 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002601
Richard Smith254a73d2011-10-28 22:34:42 +00002602 // If this is a parameter to an active constexpr function call, perform
2603 // argument substitution.
2604 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002605 // Assume arguments of a potential constant expression are unknown
2606 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002607 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002608 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002609 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002610 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002611 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002612 }
Richard Smith3229b742013-05-05 21:17:10 +00002613 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002614 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002615 }
Richard Smith27908702011-10-24 17:54:18 +00002616
Richard Smithd9f663b2013-04-22 15:31:51 +00002617 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002618 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002619 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2620 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002621 if (!Result) {
2622 // Assume variables referenced within a lambda's call operator that were
2623 // not declared within the call operator are captures and during checking
2624 // of a potential constant expression, assume they are unknown constant
2625 // expressions.
2626 assert(isLambdaCallOperator(Frame->Callee) &&
2627 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2628 "missing value for local variable");
2629 if (Info.checkingPotentialConstantExpression())
2630 return false;
2631 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002632 Info.FFDiag(E->getBeginLoc(),
2633 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002634 << "captures not currently allowed";
2635 return false;
2636 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002637 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002638 }
2639
Richard Smithd0b4dd62011-12-19 06:19:21 +00002640 // Dig out the initializer, and use the declaration which it's attached to.
2641 const Expr *Init = VD->getAnyInitializer(VD);
2642 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002643 // If we're checking a potential constant expression, the variable could be
2644 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002645 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002646 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002647 return false;
2648 }
2649
Richard Smithd62306a2011-11-10 06:34:14 +00002650 // If we're currently evaluating the initializer of this declaration, use that
2651 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002652 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002653 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002654 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002655 }
2656
Richard Smithcecf1842011-11-01 21:06:14 +00002657 // Never evaluate the initializer of a weak variable. We can't be sure that
2658 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002659 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002660 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002661 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002662 }
Richard Smithcecf1842011-11-01 21:06:14 +00002663
Richard Smithd0b4dd62011-12-19 06:19:21 +00002664 // Check that we can fold the initializer. In C++, we will have already done
2665 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002666 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002667 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002668 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002669 Notes.size() + 1) << VD;
2670 Info.Note(VD->getLocation(), diag::note_declared_at);
2671 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002672 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002673 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002674 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002675 Notes.size() + 1) << VD;
2676 Info.Note(VD->getLocation(), diag::note_declared_at);
2677 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002678 }
Richard Smith27908702011-10-24 17:54:18 +00002679
Richard Smith3229b742013-05-05 21:17:10 +00002680 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002681 return true;
Richard Smith27908702011-10-24 17:54:18 +00002682}
2683
Richard Smith11562c52011-10-28 17:51:58 +00002684static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002685 Qualifiers Quals = T.getQualifiers();
2686 return Quals.hasConst() && !Quals.hasVolatile();
2687}
2688
Richard Smithe97cbd72011-11-11 04:05:33 +00002689/// Get the base index of the given base class within an APValue representing
2690/// the given derived class.
2691static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2692 const CXXRecordDecl *Base) {
2693 Base = Base->getCanonicalDecl();
2694 unsigned Index = 0;
2695 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2696 E = Derived->bases_end(); I != E; ++I, ++Index) {
2697 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2698 return Index;
2699 }
2700
2701 llvm_unreachable("base class missing from derived class's bases list");
2702}
2703
Richard Smith3da88fa2013-04-26 14:36:30 +00002704/// Extract the value of a character from a string literal.
2705static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2706 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002707 assert(!isa<SourceLocExpr>(Lit) &&
2708 "SourceLocExpr should have already been converted to a StringLiteral");
2709
Akira Hatanakabc332642017-01-31 02:31:39 +00002710 // FIXME: Support MakeStringConstant
2711 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2712 std::string Str;
2713 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2714 assert(Index <= Str.size() && "Index too large");
2715 return APSInt::getUnsigned(Str.c_str()[Index]);
2716 }
2717
Alexey Bataevec474782014-10-09 08:45:04 +00002718 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2719 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002720 const StringLiteral *S = cast<StringLiteral>(Lit);
2721 const ConstantArrayType *CAT =
2722 Info.Ctx.getAsConstantArrayType(S->getType());
2723 assert(CAT && "string literal isn't an array");
2724 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002725 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002726
2727 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002728 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002729 if (Index < S->getLength())
2730 Value = S->getCodeUnit(Index);
2731 return Value;
2732}
2733
Richard Smith3da88fa2013-04-26 14:36:30 +00002734// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002735//
2736// FIXME: This is inefficient; we should probably introduce something similar
2737// to the LLVM ConstantDataArray to make this cheaper.
2738static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002739 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 const ConstantArrayType *CAT =
2741 Info.Ctx.getAsConstantArrayType(S->getType());
2742 assert(CAT && "string literal isn't an array");
2743 QualType CharType = CAT->getElementType();
2744 assert(CharType->isIntegerType() && "unexpected character type");
2745
2746 unsigned Elts = CAT->getSize().getZExtValue();
2747 Result = APValue(APValue::UninitArray(),
2748 std::min(S->getLength(), Elts), Elts);
2749 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2750 CharType->isUnsignedIntegerType());
2751 if (Result.hasArrayFiller())
2752 Result.getArrayFiller() = APValue(Value);
2753 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2754 Value = S->getCodeUnit(I);
2755 Result.getArrayInitializedElt(I) = APValue(Value);
2756 }
2757}
2758
2759// Expand an array so that it has more than Index filled elements.
2760static void expandArray(APValue &Array, unsigned Index) {
2761 unsigned Size = Array.getArraySize();
2762 assert(Index < Size);
2763
2764 // Always at least double the number of elements for which we store a value.
2765 unsigned OldElts = Array.getArrayInitializedElts();
2766 unsigned NewElts = std::max(Index+1, OldElts * 2);
2767 NewElts = std::min(Size, std::max(NewElts, 8u));
2768
2769 // Copy the data across.
2770 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2771 for (unsigned I = 0; I != OldElts; ++I)
2772 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2773 for (unsigned I = OldElts; I != NewElts; ++I)
2774 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2775 if (NewValue.hasArrayFiller())
2776 NewValue.getArrayFiller() = Array.getArrayFiller();
2777 Array.swap(NewValue);
2778}
2779
Richard Smithb01fe402014-09-16 01:24:02 +00002780/// Determine whether a type would actually be read by an lvalue-to-rvalue
2781/// conversion. If it's of class type, we may assume that the copy operation
2782/// is trivial. Note that this is never true for a union type with fields
2783/// (because the copy always "reads" the active member) and always true for
2784/// a non-class type.
2785static bool isReadByLvalueToRvalueConversion(QualType T) {
2786 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2787 if (!RD || (RD->isUnion() && !RD->field_empty()))
2788 return true;
2789 if (RD->isEmpty())
2790 return false;
2791
2792 for (auto *Field : RD->fields())
2793 if (isReadByLvalueToRvalueConversion(Field->getType()))
2794 return true;
2795
2796 for (auto &BaseSpec : RD->bases())
2797 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2798 return true;
2799
2800 return false;
2801}
2802
2803/// Diagnose an attempt to read from any unreadable field within the specified
2804/// type, which might be a class type.
2805static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2806 QualType T) {
2807 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2808 if (!RD)
2809 return false;
2810
2811 if (!RD->hasMutableFields())
2812 return false;
2813
2814 for (auto *Field : RD->fields()) {
2815 // If we're actually going to read this field in some way, then it can't
2816 // be mutable. If we're in a union, then assigning to a mutable field
2817 // (even an empty one) can change the active member, so that's not OK.
2818 // FIXME: Add core issue number for the union case.
2819 if (Field->isMutable() &&
2820 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002821 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002822 Info.Note(Field->getLocation(), diag::note_declared_at);
2823 return true;
2824 }
2825
2826 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2827 return true;
2828 }
2829
2830 for (auto &BaseSpec : RD->bases())
2831 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2832 return true;
2833
2834 // All mutable fields were empty, and thus not actually read.
2835 return false;
2836}
2837
Richard Smithdebad642019-05-12 09:39:08 +00002838static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2839 APValue::LValueBase Base) {
2840 // A temporary we created.
2841 if (Base.getCallIndex())
2842 return true;
2843
2844 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2845 if (!Evaluating)
2846 return false;
2847
2848 // The variable whose initializer we're evaluating.
2849 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2850 if (declaresSameEntity(Evaluating, BaseD))
2851 return true;
2852
2853 // A temporary lifetime-extended by the variable whose initializer we're
2854 // evaluating.
2855 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2856 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2857 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2858 return true;
2859
2860 return false;
2861}
2862
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002863namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002864/// A handle to a complete object (an object that is not a subobject of
2865/// another object).
2866struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002867 /// The identity of the object.
2868 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002869 /// The value of the complete object.
2870 APValue *Value;
2871 /// The type of the complete object.
2872 QualType Type;
2873
Craig Topper36250ad2014-05-12 05:36:57 +00002874 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002875 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2876 : Base(Base), Value(Value), Type(Type) {}
2877
2878 bool mayReadMutableMembers(EvalInfo &Info) const {
2879 // In C++14 onwards, it is permitted to read a mutable member whose
2880 // lifetime began within the evaluation.
2881 // FIXME: Should we also allow this in C++11?
2882 if (!Info.getLangOpts().CPlusPlus14)
2883 return false;
2884 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002885 }
2886
Richard Smithdebad642019-05-12 09:39:08 +00002887 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002888};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002889} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002890
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002891static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2892 bool IsMutable = false) {
2893 // C++ [basic.type.qualifier]p1:
2894 // - A const object is an object of type const T or a non-mutable subobject
2895 // of a const object.
2896 if (ObjType.isConstQualified() && !IsMutable)
2897 SubobjType.addConst();
2898 // - A volatile object is an object of type const T or a subobject of a
2899 // volatile object.
2900 if (ObjType.isVolatileQualified())
2901 SubobjType.addVolatile();
2902 return SubobjType;
2903}
2904
Richard Smith3da88fa2013-04-26 14:36:30 +00002905/// Find the designated sub-object of an rvalue.
2906template<typename SubobjectHandler>
2907typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002908findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002909 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002910 if (Sub.Invalid)
2911 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002912 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002913 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002914 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002915 Info.FFDiag(E, Sub.isOnePastTheEnd()
2916 ? diag::note_constexpr_access_past_end
2917 : diag::note_constexpr_access_unsized_array)
2918 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002919 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002920 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002921 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002922 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002923
Richard Smith3229b742013-05-05 21:17:10 +00002924 APValue *O = Obj.Value;
2925 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002926 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002927 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002928
Richard Smithd62306a2011-11-10 06:34:14 +00002929 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002930 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00002931 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithc667cdc2019-09-18 17:37:44 +00002932 if (O->isAbsent() ||
2933 (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
2934 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002935 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002936 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00002937 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00002938 return handler.failed();
2939 }
2940
Richard Smith457226e2019-09-23 03:48:44 +00002941 // C++ [class.ctor]p5, C++ [class.dtor]p5:
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002942 // const and volatile semantics are not applied on an object under
Richard Smith457226e2019-09-23 03:48:44 +00002943 // {con,de}struction.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002944 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2945 ObjType->isRecordType() &&
Richard Smith457226e2019-09-23 03:48:44 +00002946 Info.isEvaluatingCtorDtor(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002947 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2948 Sub.Entries.begin() + I)) !=
2949 ConstructionPhase::None) {
2950 ObjType = Info.Ctx.getCanonicalType(ObjType);
2951 ObjType.removeLocalConst();
2952 ObjType.removeLocalVolatile();
2953 }
2954
2955 // If this is our last pass, check that the final object type is OK.
2956 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2957 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00002958 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002959 if (Info.getLangOpts().CPlusPlus) {
2960 int DiagKind;
2961 SourceLocation Loc;
2962 const NamedDecl *Decl = nullptr;
2963 if (VolatileField) {
2964 DiagKind = 2;
2965 Loc = VolatileField->getLocation();
2966 Decl = VolatileField;
2967 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
2968 DiagKind = 1;
2969 Loc = VD->getLocation();
2970 Decl = VD;
2971 } else {
2972 DiagKind = 0;
2973 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
2974 Loc = E->getExprLoc();
2975 }
2976 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2977 << handler.AccessKind << DiagKind << Decl;
2978 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
2979 } else {
2980 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2981 }
2982 return handler.failed();
2983 }
2984
Richard Smithb01fe402014-09-16 01:24:02 +00002985 // If we are reading an object of class type, there may still be more
2986 // things we need to check: if there are any mutable subobjects, we
2987 // cannot perform this read. (This only happens when performing a trivial
2988 // copy or assignment.)
Richard Smithc667cdc2019-09-18 17:37:44 +00002989 if (ObjType->isRecordType() && isRead(handler.AccessKind) &&
Richard Smithdebad642019-05-12 09:39:08 +00002990 !Obj.mayReadMutableMembers(Info) &&
2991 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002992 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002993 }
Richard Smithb01fe402014-09-16 01:24:02 +00002994
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002995 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00002996 if (!handler.found(*O, ObjType))
2997 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002998
Richard Smith49ca8aa2013-08-06 07:09:20 +00002999 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003000 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003001 LastField && LastField->isBitField() &&
3002 !truncateBitfieldValue(Info, E, *O, LastField))
3003 return false;
3004
3005 return true;
3006 }
3007
Craig Topper36250ad2014-05-12 05:36:57 +00003008 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003009 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003010 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003011 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003012 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003013 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003014 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003015 // Note, it should not be possible to form a pointer with a valid
3016 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003017 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003018 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003019 << handler.AccessKind;
3020 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003021 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003022 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003023 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003024
3025 ObjType = CAT->getElementType();
3026
Richard Smith3da88fa2013-04-26 14:36:30 +00003027 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003028 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00003029 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003030 expandArray(*O, Index);
3031 O = &O->getArrayInitializedElt(Index);
3032 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003033 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003034 } else if (ObjType->isAnyComplexType()) {
3035 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003036 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003037 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003038 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003039 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003040 << handler.AccessKind;
3041 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003042 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003043 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003044 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003045
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003046 ObjType = getSubobjectType(
3047 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003048
Richard Smith66c96992012-02-18 22:04:06 +00003049 assert(I == N - 1 && "extracting subobject of scalar?");
3050 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003051 return handler.found(Index ? O->getComplexIntImag()
3052 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003053 } else {
3054 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003055 return handler.found(Index ? O->getComplexFloatImag()
3056 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003057 }
Richard Smithd62306a2011-11-10 06:34:14 +00003058 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithc667cdc2019-09-18 17:37:44 +00003059 if (Field->isMutable() && isRead(handler.AccessKind) &&
Richard Smithdebad642019-05-12 09:39:08 +00003060 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003061 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003062 << Field;
3063 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003064 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003065 }
3066
Richard Smithd62306a2011-11-10 06:34:14 +00003067 // Next subobject is a class, struct or union field.
3068 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3069 if (RD->isUnion()) {
3070 const FieldDecl *UnionField = O->getUnionField();
3071 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003072 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003073 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003074 << handler.AccessKind << Field << !UnionField << UnionField;
3075 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003076 }
Richard Smithd62306a2011-11-10 06:34:14 +00003077 O = &O->getUnionValue();
3078 } else
3079 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003080
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003081 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003082 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003083 if (Field->getType().isVolatileQualified())
3084 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003085 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003086 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003087 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3088 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3089 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003090
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003091 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003092 }
3093 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003094}
3095
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003096namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003097struct ExtractSubobjectHandler {
3098 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003099 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003100 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003101 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003102
3103 typedef bool result_type;
3104 bool failed() { return false; }
3105 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003106 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003107 if (AccessKind == AK_ReadObjectRepresentation)
3108 return true;
3109 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003110 }
3111 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003112 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003113 return true;
3114 }
3115 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003116 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003117 return true;
3118 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003119};
Richard Smith3229b742013-05-05 21:17:10 +00003120} // end anonymous namespace
3121
Richard Smith3da88fa2013-04-26 14:36:30 +00003122/// Extract the designated sub-object of an rvalue.
3123static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003124 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003125 const SubobjectDesignator &Sub, APValue &Result,
3126 AccessKinds AK = AK_Read) {
3127 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3128 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003129 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003130}
3131
Richard Smith3229b742013-05-05 21:17:10 +00003132namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003133struct ModifySubobjectHandler {
3134 EvalInfo &Info;
3135 APValue &NewVal;
3136 const Expr *E;
3137
3138 typedef bool result_type;
3139 static const AccessKinds AccessKind = AK_Assign;
3140
3141 bool checkConst(QualType QT) {
3142 // Assigning to a const object has undefined behavior.
3143 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003144 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003145 return false;
3146 }
3147 return true;
3148 }
3149
3150 bool failed() { return false; }
3151 bool found(APValue &Subobj, QualType SubobjType) {
3152 if (!checkConst(SubobjType))
3153 return false;
3154 // We've been given ownership of NewVal, so just swap it in.
3155 Subobj.swap(NewVal);
3156 return true;
3157 }
3158 bool found(APSInt &Value, QualType SubobjType) {
3159 if (!checkConst(SubobjType))
3160 return false;
3161 if (!NewVal.isInt()) {
3162 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003163 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003164 return false;
3165 }
3166 Value = NewVal.getInt();
3167 return true;
3168 }
3169 bool found(APFloat &Value, QualType SubobjType) {
3170 if (!checkConst(SubobjType))
3171 return false;
3172 Value = NewVal.getFloat();
3173 return true;
3174 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003175};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003176} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003177
Richard Smith3229b742013-05-05 21:17:10 +00003178const AccessKinds ModifySubobjectHandler::AccessKind;
3179
Richard Smith3da88fa2013-04-26 14:36:30 +00003180/// Update the designated sub-object of an rvalue to the given value.
3181static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003182 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003183 const SubobjectDesignator &Sub,
3184 APValue &NewVal) {
3185 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003186 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003187}
3188
Richard Smith84f6dcf2012-02-02 01:16:57 +00003189/// Find the position where two subobject designators diverge, or equivalently
3190/// the length of the common initial subsequence.
3191static unsigned FindDesignatorMismatch(QualType ObjType,
3192 const SubobjectDesignator &A,
3193 const SubobjectDesignator &B,
3194 bool &WasArrayIndex) {
3195 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3196 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003197 if (!ObjType.isNull() &&
3198 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003199 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003200 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003201 WasArrayIndex = true;
3202 return I;
3203 }
Richard Smith66c96992012-02-18 22:04:06 +00003204 if (ObjType->isAnyComplexType())
3205 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3206 else
3207 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003208 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003209 if (A.Entries[I].getAsBaseOrMember() !=
3210 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003211 WasArrayIndex = false;
3212 return I;
3213 }
3214 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3215 // Next subobject is a field.
3216 ObjType = FD->getType();
3217 else
3218 // Next subobject is a base class.
3219 ObjType = QualType();
3220 }
3221 }
3222 WasArrayIndex = false;
3223 return I;
3224}
3225
3226/// Determine whether the given subobject designators refer to elements of the
3227/// same array object.
3228static bool AreElementsOfSameArray(QualType ObjType,
3229 const SubobjectDesignator &A,
3230 const SubobjectDesignator &B) {
3231 if (A.Entries.size() != B.Entries.size())
3232 return false;
3233
George Burgess IVa51c4072015-10-16 01:49:01 +00003234 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003235 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3236 // A is a subobject of the array element.
3237 return false;
3238
3239 // If A (and B) designates an array element, the last entry will be the array
3240 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3241 // of length 1' case, and the entire path must match.
3242 bool WasArrayIndex;
3243 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3244 return CommonLength >= A.Entries.size() - IsArray;
3245}
3246
Richard Smith3229b742013-05-05 21:17:10 +00003247/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003248static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3249 AccessKinds AK, const LValue &LVal,
3250 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003251 if (LVal.InvalidBase) {
3252 Info.FFDiag(E);
3253 return CompleteObject();
3254 }
3255
Richard Smith3229b742013-05-05 21:17:10 +00003256 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003257 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003258 return CompleteObject();
3259 }
3260
Craig Topper36250ad2014-05-12 05:36:57 +00003261 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003262 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003263 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003264 std::tie(Frame, Depth) =
3265 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003266 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003267 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003268 << AK << LVal.Base.is<const ValueDecl*>();
3269 NoteLValueLocation(Info, LVal.Base);
3270 return CompleteObject();
3271 }
Richard Smith3229b742013-05-05 21:17:10 +00003272 }
3273
Richard Smith7bd54ab2019-05-15 20:22:21 +00003274 bool IsAccess = isFormalAccess(AK);
3275
Richard Smith3229b742013-05-05 21:17:10 +00003276 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3277 // is not a constant expression (even if the object is non-volatile). We also
3278 // apply this rule to C++98, in order to conform to the expected 'volatile'
3279 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003280 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003281 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003282 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003283 << AK << LValType;
3284 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003285 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003286 return CompleteObject();
3287 }
3288
3289 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003290 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003291 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003292
3293 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3294 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3295 // In C++11, constexpr, non-volatile variables initialized with constant
3296 // expressions are constant expressions too. Inside constexpr functions,
3297 // parameters are constant expressions even if they're non-const.
3298 // In C++1y, objects local to a constant expression (those with a Frame) are
3299 // both readable and writable inside constant expressions.
3300 // In C, such things can also be folded, although they are not ICEs.
3301 const VarDecl *VD = dyn_cast<VarDecl>(D);
3302 if (VD) {
3303 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3304 VD = VDef;
3305 }
3306 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003307 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003308 return CompleteObject();
3309 }
3310
Richard Smith3229b742013-05-05 21:17:10 +00003311 // Unless we're looking at a local variable or argument in a constexpr call,
3312 // the variable we're reading must be const.
3313 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003314 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003315 declaresSameEntity(
3316 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003317 // OK, we can read and modify an object if we're in the process of
3318 // evaluating its initializer, because its lifetime began in this
3319 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003320 } else if (isModification(AK)) {
3321 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003322 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003323 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003324 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003325 // OK, we can read this variable.
3326 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003327 // In OpenCL if a variable is in constant address space it is a const
3328 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003329 if (!(BaseType.isConstQualified() ||
3330 (Info.getLangOpts().OpenCL &&
3331 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003332 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003333 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003334 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003335 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003336 Info.Note(VD->getLocation(), diag::note_declared_at);
3337 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003338 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003339 }
3340 return CompleteObject();
3341 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003342 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003343 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003344 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3345 // We support folding of const floating-point types, in order to make
3346 // static const data members of such types (supported as an extension)
3347 // more useful.
3348 if (Info.getLangOpts().CPlusPlus11) {
3349 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3350 Info.Note(VD->getLocation(), diag::note_declared_at);
3351 } else {
3352 Info.CCEDiag(E);
3353 }
George Burgess IVb5316982016-12-27 05:33:20 +00003354 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3355 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3356 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003357 } else {
3358 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003359 if (Info.checkingPotentialConstantExpression() &&
3360 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3361 // The definition of this variable could be constexpr. We can't
3362 // access it right now, but may be able to in future.
3363 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003364 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003365 Info.Note(VD->getLocation(), diag::note_declared_at);
3366 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003367 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003368 }
3369 return CompleteObject();
3370 }
3371 }
3372
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003373 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003374 return CompleteObject();
3375 } else {
3376 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3377
3378 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003379 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003380 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003381 assert(MTE->getStorageDuration() == SD_Static &&
3382 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003383
Richard Smithe6c01442013-06-05 00:46:14 +00003384 // Per C++1y [expr.const]p2:
3385 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3386 // - a [...] glvalue of integral or enumeration type that refers to
3387 // a non-volatile const object [...]
3388 // [...]
3389 // - a [...] glvalue of literal type that refers to a non-volatile
3390 // object whose lifetime began within the evaluation of e.
3391 //
3392 // C++11 misses the 'began within the evaluation of e' check and
3393 // instead allows all temporaries, including things like:
3394 // int &&r = 1;
3395 // int x = ++r;
3396 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003397 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003398 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3399 const ValueDecl *ED = MTE->getExtendingDecl();
3400 if (!(BaseType.isConstQualified() &&
3401 BaseType->isIntegralOrEnumerationType()) &&
3402 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003403 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003404 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003405 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003406 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3407 return CompleteObject();
3408 }
3409
3410 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3411 assert(BaseVal && "got reference to unevaluated temporary");
3412 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003413 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003414 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003415 APValue Val;
3416 LVal.moveInto(Val);
3417 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3418 << AK
3419 << Val.getAsString(Info.Ctx,
3420 Info.Ctx.getLValueReferenceType(LValType));
3421 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003422 return CompleteObject();
3423 }
3424 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003425 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003426 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003427 }
Richard Smith7525ff62013-05-09 07:14:00 +00003428 }
3429
Richard Smith9defb7d2018-02-21 03:38:30 +00003430 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003431 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003432 //
3433 // FIXME: Not all local state is mutable. Allow local constant subobjects
3434 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003435 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3436 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003437 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003438 return CompleteObject();
3439
Richard Smithdebad642019-05-12 09:39:08 +00003440 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003441}
3442
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003443/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003444/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3445/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003446///
3447/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003448/// \param Conv - The expression for which we are performing the conversion.
3449/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003450/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3451/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003452/// \param LVal - The glvalue on which we are attempting to perform this action.
3453/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003454/// \param WantObjectRepresentation - If true, we're looking for the object
3455/// representation rather than the value, and in particular,
3456/// there is no requirement that the result be fully initialized.
3457static bool
3458handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3459 const LValue &LVal, APValue &RVal,
3460 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003461 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003462 return false;
3463
Richard Smith3229b742013-05-05 21:17:10 +00003464 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003465 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003466
Richard Smithc667cdc2019-09-18 17:37:44 +00003467 AccessKinds AK =
3468 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3469
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003470 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003471 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3472 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3473 // initializer until now for such expressions. Such an expression can't be
3474 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003475 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003476 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003477 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003478 }
Richard Smith3229b742013-05-05 21:17:10 +00003479 APValue Lit;
3480 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3481 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003482 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003483 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003484 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003485 // Special-case character extraction so we don't have to construct an
3486 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003487 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003488 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003489 if (LVal.Designator.Entries.empty()) {
3490 // Fail for now for LValue to RValue conversion of an array.
3491 // (This shouldn't show up in C/C++, but it could be triggered by a
3492 // weird EvaluateAsRValue call from a tool.)
3493 Info.FFDiag(Conv);
3494 return false;
3495 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003496 if (LVal.Designator.isOnePastTheEnd()) {
3497 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003498 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003499 else
3500 Info.FFDiag(Conv);
3501 return false;
3502 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003503 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003504 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3505 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003506 }
Richard Smith11562c52011-10-28 17:51:58 +00003507 }
3508
Richard Smithc667cdc2019-09-18 17:37:44 +00003509 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3510 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003511}
3512
3513/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003514static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003515 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003516 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003517 return false;
3518
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003519 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003520 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003521 return false;
3522 }
3523
Richard Smith3229b742013-05-05 21:17:10 +00003524 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003525 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3526}
3527
3528namespace {
3529struct CompoundAssignSubobjectHandler {
3530 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003531 const Expr *E;
3532 QualType PromotedLHSType;
3533 BinaryOperatorKind Opcode;
3534 const APValue &RHS;
3535
3536 static const AccessKinds AccessKind = AK_Assign;
3537
3538 typedef bool result_type;
3539
3540 bool checkConst(QualType QT) {
3541 // Assigning to a const object has undefined behavior.
3542 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003543 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003544 return false;
3545 }
3546 return true;
3547 }
3548
3549 bool failed() { return false; }
3550 bool found(APValue &Subobj, QualType SubobjType) {
3551 switch (Subobj.getKind()) {
3552 case APValue::Int:
3553 return found(Subobj.getInt(), SubobjType);
3554 case APValue::Float:
3555 return found(Subobj.getFloat(), SubobjType);
3556 case APValue::ComplexInt:
3557 case APValue::ComplexFloat:
3558 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003559 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003560 return false;
3561 case APValue::LValue:
3562 return foundPointer(Subobj, SubobjType);
3563 default:
3564 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003565 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003566 return false;
3567 }
3568 }
3569 bool found(APSInt &Value, QualType SubobjType) {
3570 if (!checkConst(SubobjType))
3571 return false;
3572
Tan S. B.9f935e82018-12-18 07:38:06 +00003573 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003574 // We don't support compound assignment on integer-cast-to-pointer
3575 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003576 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003577 return false;
3578 }
3579
Tan S. B.9f935e82018-12-18 07:38:06 +00003580 if (RHS.isInt()) {
3581 APSInt LHS =
3582 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3583 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3584 return false;
3585 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3586 return true;
3587 } else if (RHS.isFloat()) {
3588 APFloat FValue(0.0);
3589 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3590 FValue) &&
3591 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3592 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3593 Value);
3594 }
3595
3596 Info.FFDiag(E);
3597 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003598 }
3599 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003600 return checkConst(SubobjType) &&
3601 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3602 Value) &&
3603 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3604 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003605 }
3606 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3607 if (!checkConst(SubobjType))
3608 return false;
3609
3610 QualType PointeeType;
3611 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3612 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003613
3614 if (PointeeType.isNull() || !RHS.isInt() ||
3615 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003616 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003617 return false;
3618 }
3619
Richard Smithd6cc1982017-01-31 02:23:02 +00003620 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003621 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003622 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003623
3624 LValue LVal;
3625 LVal.setFrom(Info.Ctx, Subobj);
3626 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3627 return false;
3628 LVal.moveInto(Subobj);
3629 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003630 }
Richard Smith43e77732013-05-07 04:50:00 +00003631};
3632} // end anonymous namespace
3633
3634const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3635
3636/// Perform a compound assignment of LVal <op>= RVal.
3637static bool handleCompoundAssignment(
3638 EvalInfo &Info, const Expr *E,
3639 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3640 BinaryOperatorKind Opcode, const APValue &RVal) {
3641 if (LVal.Designator.Invalid)
3642 return false;
3643
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003644 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003645 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003646 return false;
3647 }
3648
3649 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3650 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3651 RVal };
3652 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3653}
3654
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003655namespace {
3656struct IncDecSubobjectHandler {
3657 EvalInfo &Info;
3658 const UnaryOperator *E;
3659 AccessKinds AccessKind;
3660 APValue *Old;
3661
Richard Smith243ef902013-05-05 23:31:59 +00003662 typedef bool result_type;
3663
3664 bool checkConst(QualType QT) {
3665 // Assigning to a const object has undefined behavior.
3666 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003667 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003668 return false;
3669 }
3670 return true;
3671 }
3672
3673 bool failed() { return false; }
3674 bool found(APValue &Subobj, QualType SubobjType) {
3675 // Stash the old value. Also clear Old, so we don't clobber it later
3676 // if we're post-incrementing a complex.
3677 if (Old) {
3678 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003679 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003680 }
3681
3682 switch (Subobj.getKind()) {
3683 case APValue::Int:
3684 return found(Subobj.getInt(), SubobjType);
3685 case APValue::Float:
3686 return found(Subobj.getFloat(), SubobjType);
3687 case APValue::ComplexInt:
3688 return found(Subobj.getComplexIntReal(),
3689 SubobjType->castAs<ComplexType>()->getElementType()
3690 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3691 case APValue::ComplexFloat:
3692 return found(Subobj.getComplexFloatReal(),
3693 SubobjType->castAs<ComplexType>()->getElementType()
3694 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3695 case APValue::LValue:
3696 return foundPointer(Subobj, SubobjType);
3697 default:
3698 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003699 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003700 return false;
3701 }
3702 }
3703 bool found(APSInt &Value, QualType SubobjType) {
3704 if (!checkConst(SubobjType))
3705 return false;
3706
3707 if (!SubobjType->isIntegerType()) {
3708 // We don't support increment / decrement on integer-cast-to-pointer
3709 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003710 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003711 return false;
3712 }
3713
3714 if (Old) *Old = APValue(Value);
3715
3716 // bool arithmetic promotes to int, and the conversion back to bool
3717 // doesn't reduce mod 2^n, so special-case it.
3718 if (SubobjType->isBooleanType()) {
3719 if (AccessKind == AK_Increment)
3720 Value = 1;
3721 else
3722 Value = !Value;
3723 return true;
3724 }
3725
3726 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003727 if (AccessKind == AK_Increment) {
3728 ++Value;
3729
3730 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3731 APSInt ActualValue(Value, /*IsUnsigned*/true);
3732 return HandleOverflow(Info, E, ActualValue, SubobjType);
3733 }
3734 } else {
3735 --Value;
3736
3737 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3738 unsigned BitWidth = Value.getBitWidth();
3739 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3740 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003741 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003742 }
3743 }
3744 return true;
3745 }
3746 bool found(APFloat &Value, QualType SubobjType) {
3747 if (!checkConst(SubobjType))
3748 return false;
3749
3750 if (Old) *Old = APValue(Value);
3751
3752 APFloat One(Value.getSemantics(), 1);
3753 if (AccessKind == AK_Increment)
3754 Value.add(One, APFloat::rmNearestTiesToEven);
3755 else
3756 Value.subtract(One, APFloat::rmNearestTiesToEven);
3757 return true;
3758 }
3759 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3760 if (!checkConst(SubobjType))
3761 return false;
3762
3763 QualType PointeeType;
3764 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3765 PointeeType = PT->getPointeeType();
3766 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003767 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003768 return false;
3769 }
3770
3771 LValue LVal;
3772 LVal.setFrom(Info.Ctx, Subobj);
3773 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3774 AccessKind == AK_Increment ? 1 : -1))
3775 return false;
3776 LVal.moveInto(Subobj);
3777 return true;
3778 }
Richard Smith243ef902013-05-05 23:31:59 +00003779};
3780} // end anonymous namespace
3781
3782/// Perform an increment or decrement on LVal.
3783static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3784 QualType LValType, bool IsIncrement, APValue *Old) {
3785 if (LVal.Designator.Invalid)
3786 return false;
3787
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003788 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003789 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003790 return false;
3791 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003792
3793 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3794 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3795 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3796 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3797}
3798
Richard Smithe97cbd72011-11-11 04:05:33 +00003799/// Build an lvalue for the object argument of a member function call.
3800static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3801 LValue &This) {
3802 if (Object->getType()->isPointerType())
3803 return EvaluatePointer(Object, This, Info);
3804
3805 if (Object->isGLValue())
3806 return EvaluateLValue(Object, This, Info);
3807
Richard Smithd9f663b2013-04-22 15:31:51 +00003808 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003809 return EvaluateTemporary(Object, This, Info);
3810
Faisal Valie690b7a2016-07-02 22:34:24 +00003811 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003812 return false;
3813}
3814
3815/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3816/// lvalue referring to the result.
3817///
3818/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003819/// \param LV - An lvalue referring to the base of the member pointer.
3820/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003821/// \param IncludeMember - Specifies whether the member itself is included in
3822/// the resulting LValue subobject designator. This is not possible when
3823/// creating a bound member function.
3824/// \return The field or method declaration to which the member pointer refers,
3825/// or 0 if evaluation fails.
3826static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003827 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003828 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003829 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003830 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003831 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003832 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003833 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003834
3835 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3836 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003837 if (!MemPtr.getDecl()) {
3838 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003839 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003840 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003841 }
Richard Smith253c2a32012-01-27 01:14:48 +00003842
Richard Smith027bf112011-11-17 22:56:20 +00003843 if (MemPtr.isDerivedMember()) {
3844 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003845 // The end of the derived-to-base path for the base object must match the
3846 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003847 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003848 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003849 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003850 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003851 }
Richard Smith027bf112011-11-17 22:56:20 +00003852 unsigned PathLengthToMember =
3853 LV.Designator.Entries.size() - MemPtr.Path.size();
3854 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3855 const CXXRecordDecl *LVDecl = getAsBaseClass(
3856 LV.Designator.Entries[PathLengthToMember + I]);
3857 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003858 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003859 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003860 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003861 }
Richard Smith027bf112011-11-17 22:56:20 +00003862 }
3863
3864 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003865 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003866 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003867 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003868 } else if (!MemPtr.Path.empty()) {
3869 // Extend the LValue path with the member pointer's path.
3870 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3871 MemPtr.Path.size() + IncludeMember);
3872
3873 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003874 if (const PointerType *PT = LVType->getAs<PointerType>())
3875 LVType = PT->getPointeeType();
3876 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3877 assert(RD && "member pointer access on non-class-type expression");
3878 // The first class in the path is that of the lvalue.
3879 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3880 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003881 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003882 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003883 RD = Base;
3884 }
3885 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003886 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3887 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003888 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003889 }
3890
3891 // Add the member. Note that we cannot build bound member functions here.
3892 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003893 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003894 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003895 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003896 } else if (const IndirectFieldDecl *IFD =
3897 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003898 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003899 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003900 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003901 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003902 }
Richard Smith027bf112011-11-17 22:56:20 +00003903 }
3904
3905 return MemPtr.getDecl();
3906}
3907
Richard Smith84401042013-06-03 05:03:02 +00003908static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3909 const BinaryOperator *BO,
3910 LValue &LV,
3911 bool IncludeMember = true) {
3912 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3913
3914 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003915 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003916 MemberPtr MemPtr;
3917 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3918 }
Craig Topper36250ad2014-05-12 05:36:57 +00003919 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003920 }
3921
3922 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3923 BO->getRHS(), IncludeMember);
3924}
3925
Richard Smith027bf112011-11-17 22:56:20 +00003926/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3927/// the provided lvalue, which currently refers to the base object.
3928static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3929 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003930 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003931 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003932 return false;
3933
Richard Smitha8105bc2012-01-06 16:39:00 +00003934 QualType TargetQT = E->getType();
3935 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3936 TargetQT = PT->getPointeeType();
3937
3938 // Check this cast lands within the final derived-to-base subobject path.
3939 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003940 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003941 << D.MostDerivedType << TargetQT;
3942 return false;
3943 }
3944
Richard Smith027bf112011-11-17 22:56:20 +00003945 // Check the type of the final cast. We don't need to check the path,
3946 // since a cast can only be formed if the path is unique.
3947 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003948 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3949 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003950 if (NewEntriesSize == D.MostDerivedPathLength)
3951 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3952 else
Richard Smith027bf112011-11-17 22:56:20 +00003953 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003954 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003955 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003956 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003957 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003958 }
Richard Smith027bf112011-11-17 22:56:20 +00003959
3960 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003961 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003962}
3963
Richard Smithc667cdc2019-09-18 17:37:44 +00003964/// Get the value to use for a default-initialized object of type T.
3965static APValue getDefaultInitValue(QualType T) {
3966 if (auto *RD = T->getAsCXXRecordDecl()) {
3967 if (RD->isUnion())
3968 return APValue((const FieldDecl*)nullptr);
3969
3970 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
3971 std::distance(RD->field_begin(), RD->field_end()));
3972
3973 unsigned Index = 0;
3974 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
3975 End = RD->bases_end(); I != End; ++I, ++Index)
3976 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
3977
3978 for (const auto *I : RD->fields()) {
3979 if (I->isUnnamedBitfield())
3980 continue;
3981 Struct.getStructField(I->getFieldIndex()) =
3982 getDefaultInitValue(I->getType());
3983 }
3984 return Struct;
3985 }
3986
3987 if (auto *AT =
3988 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
3989 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
3990 if (Array.hasArrayFiller())
3991 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
3992 return Array;
3993 }
3994
3995 return APValue::IndeterminateValue();
3996}
3997
Mike Stump876387b2009-10-27 22:09:17 +00003998namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003999enum EvalStmtResult {
4000 /// Evaluation failed.
4001 ESR_Failed,
4002 /// Hit a 'return' statement.
4003 ESR_Returned,
4004 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004005 ESR_Succeeded,
4006 /// Hit a 'continue' statement.
4007 ESR_Continue,
4008 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004009 ESR_Break,
4010 /// Still scanning for 'case' or 'default' statement.
4011 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004012};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004013}
Richard Smith254a73d2011-10-28 22:34:42 +00004014
Richard Smith97fcf4b2016-08-14 23:15:52 +00004015static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4016 // We don't need to evaluate the initializer for a static local.
4017 if (!VD->hasLocalStorage())
4018 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004019
Richard Smith97fcf4b2016-08-14 23:15:52 +00004020 LValue Result;
Richard Smith457226e2019-09-23 03:48:44 +00004021 APValue &Val =
4022 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
Richard Smithd9f663b2013-04-22 15:31:51 +00004023
Richard Smith97fcf4b2016-08-14 23:15:52 +00004024 const Expr *InitE = VD->getInit();
4025 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00004026 Val = getDefaultInitValue(VD->getType());
4027 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00004028 }
Richard Smith51f03172013-06-20 03:00:05 +00004029
Richard Smith97fcf4b2016-08-14 23:15:52 +00004030 if (InitE->isValueDependent())
4031 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004032
Richard Smith97fcf4b2016-08-14 23:15:52 +00004033 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4034 // Wipe out any partially-computed value, to allow tracking that this
4035 // evaluation failed.
4036 Val = APValue();
4037 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004038 }
4039
4040 return true;
4041}
4042
Richard Smith97fcf4b2016-08-14 23:15:52 +00004043static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4044 bool OK = true;
4045
4046 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4047 OK &= EvaluateVarDecl(Info, VD);
4048
4049 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4050 for (auto *BD : DD->bindings())
4051 if (auto *VD = BD->getHoldingVar())
4052 OK &= EvaluateDecl(Info, VD);
4053
4054 return OK;
4055}
4056
4057
Richard Smith4e18ca52013-05-06 05:56:11 +00004058/// Evaluate a condition (either a variable declaration or an expression).
4059static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4060 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004061 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004062 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4063 return false;
Richard Smith457226e2019-09-23 03:48:44 +00004064 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4065 return false;
4066 return Scope.destroy();
Richard Smith4e18ca52013-05-06 05:56:11 +00004067}
4068
Richard Smith89210072016-04-04 23:29:43 +00004069namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004070/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004071/// statement should be stored.
4072struct StmtResult {
4073 /// The APValue that should be filled in with the returned value.
4074 APValue &Value;
4075 /// The location containing the result, if any (used to support RVO).
4076 const LValue *Slot;
4077};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004078
4079struct TempVersionRAII {
4080 CallStackFrame &Frame;
4081
4082 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4083 Frame.pushTempVersion();
4084 }
4085
4086 ~TempVersionRAII() {
4087 Frame.popTempVersion();
4088 }
4089};
4090
Richard Smith89210072016-04-04 23:29:43 +00004091}
Richard Smith52a980a2015-08-28 02:43:42 +00004092
4093static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004094 const Stmt *S,
4095 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004096
4097/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004098static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004099 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004100 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004101 BlockScopeRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004102
4103 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4104 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4105 ESR = ESR_Failed;
4106
4107 switch (ESR) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004108 case ESR_Break:
4109 return ESR_Succeeded;
4110 case ESR_Succeeded:
4111 case ESR_Continue:
4112 return ESR_Continue;
4113 case ESR_Failed:
4114 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004115 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004116 return ESR;
4117 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004118 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004119}
4120
Richard Smith496ddcf2013-05-12 17:32:42 +00004121/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004122static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004123 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004124 BlockScopeRAII Scope(Info);
4125
Richard Smith496ddcf2013-05-12 17:32:42 +00004126 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004127 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004128 {
Richard Smitha547eb22016-07-14 00:11:03 +00004129 if (const Stmt *Init = SS->getInit()) {
4130 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004131 if (ESR != ESR_Succeeded) {
4132 if (ESR != ESR_Failed && !Scope.destroy())
4133 ESR = ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004134 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004135 }
Richard Smitha547eb22016-07-14 00:11:03 +00004136 }
Richard Smith457226e2019-09-23 03:48:44 +00004137
4138 FullExpressionRAII CondScope(Info);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004139 if (SS->getConditionVariable() &&
4140 !EvaluateDecl(Info, SS->getConditionVariable()))
4141 return ESR_Failed;
4142 if (!EvaluateInteger(SS->getCond(), Value, Info))
4143 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004144 if (!CondScope.destroy())
4145 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004146 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004147
4148 // Find the switch case corresponding to the value of the condition.
4149 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004150 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004151 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4152 SC = SC->getNextSwitchCase()) {
4153 if (isa<DefaultStmt>(SC)) {
4154 Found = SC;
4155 continue;
4156 }
4157
4158 const CaseStmt *CS = cast<CaseStmt>(SC);
4159 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4160 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4161 : LHS;
4162 if (LHS <= Value && Value <= RHS) {
4163 Found = SC;
4164 break;
4165 }
4166 }
4167
4168 if (!Found)
Richard Smith457226e2019-09-23 03:48:44 +00004169 return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
Richard Smith496ddcf2013-05-12 17:32:42 +00004170
4171 // Search the switch body for the switch case and evaluate it from there.
Richard Smith457226e2019-09-23 03:48:44 +00004172 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4173 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4174 return ESR_Failed;
4175
4176 switch (ESR) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004177 case ESR_Break:
4178 return ESR_Succeeded;
4179 case ESR_Succeeded:
4180 case ESR_Continue:
4181 case ESR_Failed:
4182 case ESR_Returned:
4183 return ESR;
4184 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004185 // This can only happen if the switch case is nested within a statement
4186 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004187 Info.FFDiag(Found->getBeginLoc(),
4188 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004189 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004190 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004191 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004192}
4193
Richard Smith254a73d2011-10-28 22:34:42 +00004194// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004195static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004196 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004197 if (!Info.nextStep(S))
4198 return ESR_Failed;
4199
Richard Smith496ddcf2013-05-12 17:32:42 +00004200 // If we're hunting down a 'case' or 'default' label, recurse through
4201 // substatements until we hit the label.
4202 if (Case) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004203 switch (S->getStmtClass()) {
4204 case Stmt::CompoundStmtClass:
4205 // FIXME: Precompute which substatement of a compound statement we
4206 // would jump to, and go straight there rather than performing a
4207 // linear scan each time.
4208 case Stmt::LabelStmtClass:
4209 case Stmt::AttributedStmtClass:
4210 case Stmt::DoStmtClass:
4211 break;
4212
4213 case Stmt::CaseStmtClass:
4214 case Stmt::DefaultStmtClass:
4215 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004216 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004217 break;
4218
4219 case Stmt::IfStmtClass: {
4220 // FIXME: Precompute which side of an 'if' we would jump to, and go
4221 // straight there rather than scanning both sides.
4222 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004223
4224 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4225 // preceded by our switch label.
4226 BlockScopeRAII Scope(Info);
4227
Richard Smith397a6862019-09-20 23:08:59 +00004228 // Step into the init statement in case it brings an (uninitialized)
4229 // variable into scope.
4230 if (const Stmt *Init = IS->getInit()) {
4231 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4232 if (ESR != ESR_CaseNotFound) {
4233 assert(ESR != ESR_Succeeded);
4234 return ESR;
4235 }
4236 }
4237
4238 // Condition variable must be initialized if it exists.
4239 // FIXME: We can skip evaluating the body if there's a condition
4240 // variable, as there can't be any case labels within it.
4241 // (The same is true for 'for' statements.)
4242
Richard Smith496ddcf2013-05-12 17:32:42 +00004243 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
Richard Smith457226e2019-09-23 03:48:44 +00004244 if (ESR == ESR_Failed)
Richard Smith496ddcf2013-05-12 17:32:42 +00004245 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004246 if (ESR != ESR_CaseNotFound)
4247 return Scope.destroy() ? ESR : ESR_Failed;
4248 if (!IS->getElse())
4249 return ESR_CaseNotFound;
4250
4251 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4252 if (ESR == ESR_Failed)
4253 return ESR;
4254 if (ESR != ESR_CaseNotFound)
4255 return Scope.destroy() ? ESR : ESR_Failed;
4256 return ESR_CaseNotFound;
Richard Smith496ddcf2013-05-12 17:32:42 +00004257 }
4258
4259 case Stmt::WhileStmtClass: {
4260 EvalStmtResult ESR =
4261 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4262 if (ESR != ESR_Continue)
4263 return ESR;
4264 break;
4265 }
4266
4267 case Stmt::ForStmtClass: {
4268 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith397a6862019-09-20 23:08:59 +00004269 BlockScopeRAII Scope(Info);
4270
4271 // Step into the init statement in case it brings an (uninitialized)
4272 // variable into scope.
4273 if (const Stmt *Init = FS->getInit()) {
4274 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4275 if (ESR != ESR_CaseNotFound) {
4276 assert(ESR != ESR_Succeeded);
4277 return ESR;
4278 }
4279 }
4280
Richard Smith496ddcf2013-05-12 17:32:42 +00004281 EvalStmtResult ESR =
4282 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4283 if (ESR != ESR_Continue)
4284 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004285 if (FS->getInc()) {
4286 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004287 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004288 return ESR_Failed;
4289 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004290 break;
4291 }
4292
Richard Smithc667cdc2019-09-18 17:37:44 +00004293 case Stmt::DeclStmtClass: {
4294 // Start the lifetime of any uninitialized variables we encounter. They
4295 // might be used by the selected branch of the switch.
4296 const DeclStmt *DS = cast<DeclStmt>(S);
4297 for (const auto *D : DS->decls()) {
4298 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4299 if (VD->hasLocalStorage() && !VD->getInit())
4300 if (!EvaluateVarDecl(Info, VD))
4301 return ESR_Failed;
4302 // FIXME: If the variable has initialization that can't be jumped
4303 // over, bail out of any immediately-surrounding compound-statement
4304 // too. There can't be any case labels here.
4305 }
4306 }
4307 return ESR_CaseNotFound;
4308 }
4309
Richard Smith496ddcf2013-05-12 17:32:42 +00004310 default:
4311 return ESR_CaseNotFound;
4312 }
4313 }
4314
Richard Smith254a73d2011-10-28 22:34:42 +00004315 switch (S->getStmtClass()) {
4316 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004317 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004318 // Don't bother evaluating beyond an expression-statement which couldn't
4319 // be evaluated.
Richard Smith457226e2019-09-23 03:48:44 +00004320 // FIXME: Do we need the FullExpressionRAII object here?
4321 // VisitExprWithCleanups should create one when necessary.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004322 FullExpressionRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004323 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
Richard Smithd9f663b2013-04-22 15:31:51 +00004324 return ESR_Failed;
4325 return ESR_Succeeded;
4326 }
4327
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004328 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004329 return ESR_Failed;
4330
4331 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004332 return ESR_Succeeded;
4333
Richard Smithd9f663b2013-04-22 15:31:51 +00004334 case Stmt::DeclStmtClass: {
4335 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004336 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004337 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004338 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004339 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004340 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004341 if (!Scope.destroy())
4342 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004343 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004344 return ESR_Succeeded;
4345 }
4346
Richard Smith357362d2011-12-13 06:39:58 +00004347 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004348 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004349 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004350 if (RetExpr &&
4351 !(Result.Slot
4352 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4353 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004354 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004355 return Scope.destroy() ? ESR_Returned : ESR_Failed;
Richard Smith357362d2011-12-13 06:39:58 +00004356 }
Richard Smith254a73d2011-10-28 22:34:42 +00004357
4358 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004359 BlockScopeRAII Scope(Info);
4360
Richard Smith254a73d2011-10-28 22:34:42 +00004361 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004362 for (const auto *BI : CS->body()) {
4363 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004364 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004365 Case = nullptr;
Richard Smith457226e2019-09-23 03:48:44 +00004366 else if (ESR != ESR_CaseNotFound) {
4367 if (ESR != ESR_Failed && !Scope.destroy())
4368 return ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004369 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004370 }
Richard Smith254a73d2011-10-28 22:34:42 +00004371 }
Richard Smith457226e2019-09-23 03:48:44 +00004372 if (Case)
4373 return ESR_CaseNotFound;
4374 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004375 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004376
4377 case Stmt::IfStmtClass: {
4378 const IfStmt *IS = cast<IfStmt>(S);
4379
4380 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004381 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004382 if (const Stmt *Init = IS->getInit()) {
4383 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004384 if (ESR != ESR_Succeeded) {
4385 if (ESR != ESR_Failed && !Scope.destroy())
4386 return ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004387 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004388 }
Richard Smitha547eb22016-07-14 00:11:03 +00004389 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004390 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004391 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004392 return ESR_Failed;
4393
4394 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4395 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
Richard Smith457226e2019-09-23 03:48:44 +00004396 if (ESR != ESR_Succeeded) {
4397 if (ESR != ESR_Failed && !Scope.destroy())
4398 return ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004399 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004400 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004401 }
Richard Smith457226e2019-09-23 03:48:44 +00004402 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004403 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004404
4405 case Stmt::WhileStmtClass: {
4406 const WhileStmt *WS = cast<WhileStmt>(S);
4407 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004408 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004409 bool Continue;
4410 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4411 Continue))
4412 return ESR_Failed;
4413 if (!Continue)
4414 break;
4415
4416 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004417 if (ESR != ESR_Continue) {
4418 if (ESR != ESR_Failed && !Scope.destroy())
4419 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004420 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004421 }
4422 if (!Scope.destroy())
4423 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004424 }
4425 return ESR_Succeeded;
4426 }
4427
4428 case Stmt::DoStmtClass: {
4429 const DoStmt *DS = cast<DoStmt>(S);
4430 bool Continue;
4431 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004432 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004433 if (ESR != ESR_Continue)
4434 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004435 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004436
Richard Smith08d6a2c2013-07-24 07:11:57 +00004437 FullExpressionRAII CondScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004438 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4439 !CondScope.destroy())
Richard Smith4e18ca52013-05-06 05:56:11 +00004440 return ESR_Failed;
4441 } while (Continue);
4442 return ESR_Succeeded;
4443 }
4444
4445 case Stmt::ForStmtClass: {
4446 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith457226e2019-09-23 03:48:44 +00004447 BlockScopeRAII ForScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004448 if (FS->getInit()) {
4449 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004450 if (ESR != ESR_Succeeded) {
4451 if (ESR != ESR_Failed && !ForScope.destroy())
4452 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004453 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004454 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004455 }
4456 while (true) {
Richard Smith457226e2019-09-23 03:48:44 +00004457 BlockScopeRAII IterScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004458 bool Continue = true;
4459 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4460 FS->getCond(), Continue))
4461 return ESR_Failed;
4462 if (!Continue)
4463 break;
4464
4465 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004466 if (ESR != ESR_Continue) {
4467 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4468 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004469 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004470 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004471
Richard Smith08d6a2c2013-07-24 07:11:57 +00004472 if (FS->getInc()) {
4473 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004474 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004475 return ESR_Failed;
4476 }
Richard Smith457226e2019-09-23 03:48:44 +00004477
4478 if (!IterScope.destroy())
4479 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004480 }
Richard Smith457226e2019-09-23 03:48:44 +00004481 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004482 }
4483
Richard Smith896e0d72013-05-06 06:51:17 +00004484 case Stmt::CXXForRangeStmtClass: {
4485 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004486 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004487
Richard Smith8baa5002018-09-28 18:44:09 +00004488 // Evaluate the init-statement if present.
4489 if (FS->getInit()) {
4490 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004491 if (ESR != ESR_Succeeded) {
4492 if (ESR != ESR_Failed && !Scope.destroy())
4493 return ESR_Failed;
Richard Smith8baa5002018-09-28 18:44:09 +00004494 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004495 }
Richard Smith8baa5002018-09-28 18:44:09 +00004496 }
4497
Richard Smith896e0d72013-05-06 06:51:17 +00004498 // Initialize the __range variable.
4499 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004500 if (ESR != ESR_Succeeded) {
4501 if (ESR != ESR_Failed && !Scope.destroy())
4502 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004503 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004504 }
Richard Smith896e0d72013-05-06 06:51:17 +00004505
4506 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004507 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004508 if (ESR != ESR_Succeeded) {
4509 if (ESR != ESR_Failed && !Scope.destroy())
4510 return ESR_Failed;
Richard Smith01694c32016-03-20 10:33:40 +00004511 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004512 }
Richard Smith01694c32016-03-20 10:33:40 +00004513 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004514 if (ESR != ESR_Succeeded) {
4515 if (ESR != ESR_Failed && !Scope.destroy())
4516 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004517 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004518 }
Richard Smith896e0d72013-05-06 06:51:17 +00004519
4520 while (true) {
4521 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004522 {
4523 bool Continue = true;
4524 FullExpressionRAII CondExpr(Info);
4525 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4526 return ESR_Failed;
4527 if (!Continue)
4528 break;
4529 }
Richard Smith896e0d72013-05-06 06:51:17 +00004530
4531 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004532 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004533 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004534 if (ESR != ESR_Succeeded) {
4535 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4536 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004537 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004538 }
Richard Smith896e0d72013-05-06 06:51:17 +00004539
4540 // Loop body.
4541 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004542 if (ESR != ESR_Continue) {
4543 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4544 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004545 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004546 }
Richard Smith896e0d72013-05-06 06:51:17 +00004547
4548 // Increment: ++__begin
4549 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4550 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004551
4552 if (!InnerScope.destroy())
4553 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004554 }
4555
Richard Smith457226e2019-09-23 03:48:44 +00004556 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004557 }
4558
Richard Smith496ddcf2013-05-12 17:32:42 +00004559 case Stmt::SwitchStmtClass:
4560 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4561
Richard Smith4e18ca52013-05-06 05:56:11 +00004562 case Stmt::ContinueStmtClass:
4563 return ESR_Continue;
4564
4565 case Stmt::BreakStmtClass:
4566 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004567
4568 case Stmt::LabelStmtClass:
4569 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4570
4571 case Stmt::AttributedStmtClass:
4572 // As a general principle, C++11 attributes can be ignored without
4573 // any semantic impact.
4574 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4575 Case);
4576
4577 case Stmt::CaseStmtClass:
4578 case Stmt::DefaultStmtClass:
4579 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004580 case Stmt::CXXTryStmtClass:
4581 // Evaluate try blocks by evaluating all sub statements.
4582 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004583 }
4584}
4585
Richard Smithcc36f692011-12-22 02:22:31 +00004586/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4587/// default constructor. If so, we'll fold it whether or not it's marked as
4588/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4589/// so we need special handling.
4590static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004591 const CXXConstructorDecl *CD,
4592 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004593 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4594 return false;
4595
Richard Smith66e05fe2012-01-18 05:21:49 +00004596 // Value-initialization does not call a trivial default constructor, so such a
4597 // call is a core constant expression whether or not the constructor is
4598 // constexpr.
4599 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004600 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004601 // FIXME: If DiagDecl is an implicitly-declared special member function,
4602 // we should be much more explicit about why it's not constexpr.
4603 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4604 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4605 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004606 } else {
4607 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4608 }
4609 }
4610 return true;
4611}
4612
Richard Smith357362d2011-12-13 06:39:58 +00004613/// CheckConstexprFunction - Check that a function can be called in a constant
4614/// expression.
4615static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4616 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004617 const FunctionDecl *Definition,
4618 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004619 // Potential constant expressions can contain calls to declared, but not yet
4620 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004621 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004622 Declaration->isConstexpr())
4623 return false;
4624
James Y Knightc7d3e602018-10-05 17:49:48 +00004625 // Bail out if the function declaration itself is invalid. We will
4626 // have produced a relevant diagnostic while parsing it, so just
4627 // note the problematic sub-expression.
4628 if (Declaration->isInvalidDecl()) {
4629 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004630 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004631 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004632
Richard Smithd9c6b032019-05-09 19:45:49 +00004633 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004634 // constant expression (prior to C++20). We can still constant-fold such a
4635 // call.
4636 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4637 cast<CXXMethodDecl>(Declaration)->isVirtual())
4638 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4639
4640 if (Definition && Definition->isInvalidDecl()) {
4641 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004642 return false;
4643 }
4644
Richard Smith357362d2011-12-13 06:39:58 +00004645 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004646 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004647 return true;
4648
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004649 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004650 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004651
Richard Smith5179eb72016-06-28 19:03:57 +00004652 // If this function is not constexpr because it is an inherited
4653 // non-constexpr constructor, diagnose that directly.
4654 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4655 if (CD && CD->isInheritingConstructor()) {
4656 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004657 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004658 DiagDecl = CD = Inherited;
4659 }
4660
4661 // FIXME: If DiagDecl is an implicitly-declared special member function
4662 // or an inheriting constructor, we should be much more explicit about why
4663 // it's not constexpr.
4664 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004665 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004666 << CD->getInheritedConstructor().getConstructor()->getParent();
4667 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004668 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004669 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004670 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4671 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004672 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004673 }
4674 return false;
4675}
4676
Richard Smithdebad642019-05-12 09:39:08 +00004677namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004678struct CheckDynamicTypeHandler {
4679 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004680 typedef bool result_type;
4681 bool failed() { return false; }
4682 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4683 bool found(APSInt &Value, QualType SubobjType) { return true; }
4684 bool found(APFloat &Value, QualType SubobjType) { return true; }
4685};
4686} // end anonymous namespace
4687
Richard Smith7bd54ab2019-05-15 20:22:21 +00004688/// Check that we can access the notional vptr of an object / determine its
4689/// dynamic type.
4690static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4691 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004692 if (This.Designator.Invalid)
4693 return false;
4694
Richard Smith7bd54ab2019-05-15 20:22:21 +00004695 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004696
4697 if (!Obj)
4698 return false;
4699
4700 if (!Obj.Value) {
4701 // The object is not usable in constant expressions, so we can't inspect
4702 // its value to see if it's in-lifetime or what the active union members
4703 // are. We can still check for a one-past-the-end lvalue.
4704 if (This.Designator.isOnePastTheEnd() ||
4705 This.Designator.isMostDerivedAnUnsizedArray()) {
4706 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4707 ? diag::note_constexpr_access_past_end
4708 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004709 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004710 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004711 } else if (Polymorphic) {
4712 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004713 // not be able to read a notional 'vptr' value.
4714 APValue Val;
4715 This.moveInto(Val);
4716 QualType StarThisType =
4717 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004718 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4719 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004720 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004721 }
4722 return true;
4723 }
4724
Richard Smith7bd54ab2019-05-15 20:22:21 +00004725 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004726 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4727}
4728
Richard Smith7bd54ab2019-05-15 20:22:21 +00004729/// Check that the pointee of the 'this' pointer in a member function call is
4730/// either within its lifetime or in its period of construction or destruction.
4731static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4732 const LValue &This) {
4733 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4734}
4735
Richard Smith921f1322019-05-13 23:35:21 +00004736struct DynamicType {
4737 /// The dynamic class type of the object.
4738 const CXXRecordDecl *Type;
4739 /// The corresponding path length in the lvalue.
4740 unsigned PathLength;
4741};
4742
4743static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4744 unsigned PathLength) {
4745 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4746 Designator.Entries.size() && "invalid path length");
4747 return (PathLength == Designator.MostDerivedPathLength)
4748 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4749 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4750}
4751
4752/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004753static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4754 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004755 // If we don't have an lvalue denoting an object of class type, there is no
4756 // meaningful dynamic type. (We consider objects of non-class type to have no
4757 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004758 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004759 return None;
4760
Richard Smith7bd54ab2019-05-15 20:22:21 +00004761 // Refuse to compute a dynamic type in the presence of virtual bases. This
4762 // shouldn't happen other than in constant-folding situations, since literal
4763 // types can't have virtual bases.
4764 //
4765 // Note that consumers of DynamicType assume that the type has no virtual
4766 // bases, and will need modifications if this restriction is relaxed.
4767 const CXXRecordDecl *Class =
4768 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4769 if (!Class || Class->getNumVBases()) {
4770 Info.FFDiag(E);
4771 return None;
4772 }
4773
Richard Smith921f1322019-05-13 23:35:21 +00004774 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4775 // binary search here instead. But the overwhelmingly common case is that
4776 // we're not in the middle of a constructor, so it probably doesn't matter
4777 // in practice.
4778 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4779 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4780 PathLength <= Path.size(); ++PathLength) {
Richard Smith457226e2019-09-23 03:48:44 +00004781 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
4782 Path.slice(0, PathLength))) {
Richard Smith921f1322019-05-13 23:35:21 +00004783 case ConstructionPhase::Bases:
Richard Smith457226e2019-09-23 03:48:44 +00004784 case ConstructionPhase::DestroyingBases:
4785 // We're constructing or destroying a base class. This is not the dynamic
4786 // type.
Richard Smith921f1322019-05-13 23:35:21 +00004787 break;
4788
4789 case ConstructionPhase::None:
4790 case ConstructionPhase::AfterBases:
Richard Smith457226e2019-09-23 03:48:44 +00004791 case ConstructionPhase::Destroying:
4792 // We've finished constructing the base classes and not yet started
4793 // destroying them again, so this is the dynamic type.
Richard Smith921f1322019-05-13 23:35:21 +00004794 return DynamicType{getBaseClassType(This.Designator, PathLength),
4795 PathLength};
4796 }
4797 }
4798
4799 // CWG issue 1517: we're constructing a base class of the object described by
4800 // 'This', so that object has not yet begun its period of construction and
4801 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004802 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004803 return None;
4804}
4805
4806/// Perform virtual dispatch.
4807static const CXXMethodDecl *HandleVirtualDispatch(
4808 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4809 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004810 Optional<DynamicType> DynType =
4811 ComputeDynamicType(Info, E, This, AK_MemberCall);
4812 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004813 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004814
4815 // Find the final overrider. It must be declared in one of the classes on the
4816 // path from the dynamic type to the static type.
4817 // FIXME: If we ever allow literal types to have virtual base classes, that
4818 // won't be true.
4819 const CXXMethodDecl *Callee = Found;
4820 unsigned PathLength = DynType->PathLength;
4821 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4822 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004823 const CXXMethodDecl *Overrider =
4824 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4825 if (Overrider) {
4826 Callee = Overrider;
4827 break;
4828 }
4829 }
4830
4831 // C++2a [class.abstract]p6:
4832 // the effect of making a virtual call to a pure virtual function [...] is
4833 // undefined
4834 if (Callee->isPure()) {
4835 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4836 Info.Note(Callee->getLocation(), diag::note_declared_at);
4837 return nullptr;
4838 }
4839
4840 // If necessary, walk the rest of the path to determine the sequence of
4841 // covariant adjustment steps to apply.
4842 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4843 Found->getReturnType())) {
4844 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4845 for (unsigned CovariantPathLength = PathLength + 1;
4846 CovariantPathLength != This.Designator.Entries.size();
4847 ++CovariantPathLength) {
4848 const CXXRecordDecl *NextClass =
4849 getBaseClassType(This.Designator, CovariantPathLength);
4850 const CXXMethodDecl *Next =
4851 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4852 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4853 Next->getReturnType(), CovariantAdjustmentPath.back()))
4854 CovariantAdjustmentPath.push_back(Next->getReturnType());
4855 }
4856 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4857 CovariantAdjustmentPath.back()))
4858 CovariantAdjustmentPath.push_back(Found->getReturnType());
4859 }
4860
4861 // Perform 'this' adjustment.
4862 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4863 return nullptr;
4864
4865 return Callee;
4866}
4867
4868/// Perform the adjustment from a value returned by a virtual function to
4869/// a value of the statically expected type, which may be a pointer or
4870/// reference to a base class of the returned type.
4871static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4872 APValue &Result,
4873 ArrayRef<QualType> Path) {
4874 assert(Result.isLValue() &&
4875 "unexpected kind of APValue for covariant return");
4876 if (Result.isNullPointer())
4877 return true;
4878
4879 LValue LVal;
4880 LVal.setFrom(Info.Ctx, Result);
4881
4882 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4883 for (unsigned I = 1; I != Path.size(); ++I) {
4884 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4885 assert(OldClass && NewClass && "unexpected kind of covariant return");
4886 if (OldClass != NewClass &&
4887 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4888 return false;
4889 OldClass = NewClass;
4890 }
4891
4892 LVal.moveInto(Result);
4893 return true;
4894}
4895
Richard Smith7bd54ab2019-05-15 20:22:21 +00004896/// Determine whether \p Base, which is known to be a direct base class of
4897/// \p Derived, is a public base class.
4898static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4899 const CXXRecordDecl *Base) {
4900 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4901 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4902 if (BaseClass && declaresSameEntity(BaseClass, Base))
4903 return BaseSpec.getAccessSpecifier() == AS_public;
4904 }
4905 llvm_unreachable("Base is not a direct base of Derived");
4906}
4907
4908/// Apply the given dynamic cast operation on the provided lvalue.
4909///
4910/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4911/// to find a suitable target subobject.
4912static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4913 LValue &Ptr) {
4914 // We can't do anything with a non-symbolic pointer value.
4915 SubobjectDesignator &D = Ptr.Designator;
4916 if (D.Invalid)
4917 return false;
4918
4919 // C++ [expr.dynamic.cast]p6:
4920 // If v is a null pointer value, the result is a null pointer value.
4921 if (Ptr.isNullPointer() && !E->isGLValue())
4922 return true;
4923
4924 // For all the other cases, we need the pointer to point to an object within
4925 // its lifetime / period of construction / destruction, and we need to know
4926 // its dynamic type.
4927 Optional<DynamicType> DynType =
4928 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4929 if (!DynType)
4930 return false;
4931
4932 // C++ [expr.dynamic.cast]p7:
4933 // If T is "pointer to cv void", then the result is a pointer to the most
4934 // derived object
4935 if (E->getType()->isVoidPointerType())
4936 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4937
4938 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4939 assert(C && "dynamic_cast target is not void pointer nor class");
4940 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4941
4942 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4943 // C++ [expr.dynamic.cast]p9:
4944 if (!E->isGLValue()) {
4945 // The value of a failed cast to pointer type is the null pointer value
4946 // of the required result type.
4947 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4948 Ptr.setNull(E->getType(), TargetVal);
4949 return true;
4950 }
4951
4952 // A failed cast to reference type throws [...] std::bad_cast.
4953 unsigned DiagKind;
4954 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4955 DynType->Type->isDerivedFrom(C)))
4956 DiagKind = 0;
4957 else if (!Paths || Paths->begin() == Paths->end())
4958 DiagKind = 1;
4959 else if (Paths->isAmbiguous(CQT))
4960 DiagKind = 2;
4961 else {
4962 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4963 DiagKind = 3;
4964 }
4965 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4966 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4967 << Info.Ctx.getRecordType(DynType->Type)
4968 << E->getType().getUnqualifiedType();
4969 return false;
4970 };
4971
4972 // Runtime check, phase 1:
4973 // Walk from the base subobject towards the derived object looking for the
4974 // target type.
4975 for (int PathLength = Ptr.Designator.Entries.size();
4976 PathLength >= (int)DynType->PathLength; --PathLength) {
4977 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4978 if (declaresSameEntity(Class, C))
4979 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4980 // We can only walk across public inheritance edges.
4981 if (PathLength > (int)DynType->PathLength &&
4982 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4983 Class))
4984 return RuntimeCheckFailed(nullptr);
4985 }
4986
4987 // Runtime check, phase 2:
4988 // Search the dynamic type for an unambiguous public base of type C.
4989 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4990 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4991 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4992 Paths.front().Access == AS_public) {
4993 // Downcast to the dynamic type...
4994 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4995 return false;
4996 // ... then upcast to the chosen base class subobject.
4997 for (CXXBasePathElement &Elem : Paths.front())
4998 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4999 return false;
5000 return true;
5001 }
5002
5003 // Otherwise, the runtime check fails.
5004 return RuntimeCheckFailed(&Paths);
5005}
5006
Richard Smith31c69a32019-05-21 23:15:20 +00005007namespace {
5008struct StartLifetimeOfUnionMemberHandler {
5009 const FieldDecl *Field;
5010
5011 static const AccessKinds AccessKind = AK_Assign;
5012
Richard Smith31c69a32019-05-21 23:15:20 +00005013 typedef bool result_type;
5014 bool failed() { return false; }
5015 bool found(APValue &Subobj, QualType SubobjType) {
5016 // We are supposed to perform no initialization but begin the lifetime of
5017 // the object. We interpret that as meaning to do what default
5018 // initialization of the object would do if all constructors involved were
5019 // trivial:
5020 // * All base, non-variant member, and array element subobjects' lifetimes
5021 // begin
5022 // * No variant members' lifetimes begin
5023 // * All scalar subobjects whose lifetimes begin have indeterminate values
5024 assert(SubobjType->isUnionType());
5025 if (!declaresSameEntity(Subobj.getUnionField(), Field))
5026 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5027 return true;
5028 }
5029 bool found(APSInt &Value, QualType SubobjType) {
5030 llvm_unreachable("wrong value kind for union object");
5031 }
5032 bool found(APFloat &Value, QualType SubobjType) {
5033 llvm_unreachable("wrong value kind for union object");
5034 }
5035};
5036} // end anonymous namespace
5037
5038const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5039
5040/// Handle a builtin simple-assignment or a call to a trivial assignment
5041/// operator whose left-hand side might involve a union member access. If it
5042/// does, implicitly start the lifetime of any accessed union elements per
5043/// C++20 [class.union]5.
5044static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5045 const LValue &LHS) {
5046 if (LHS.InvalidBase || LHS.Designator.Invalid)
5047 return false;
5048
5049 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5050 // C++ [class.union]p5:
5051 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00005052 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005053 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005054 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5055 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5056 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5057 if (!FD)
5058 break;
5059
5060 // ... and also contains A.B if B names a union member
5061 if (FD->getParent()->isUnion())
5062 UnionPathLengths.push_back({PathLength - 1, FD});
5063
5064 E = ME->getBase();
5065 --PathLength;
5066 assert(declaresSameEntity(FD,
5067 LHS.Designator.Entries[PathLength]
5068 .getAsBaseOrMember().getPointer()));
5069
5070 // -- If E is of the form A[B] and is interpreted as a built-in array
5071 // subscripting operator, S(E) is [S(the array operand, if any)].
5072 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5073 // Step over an ArrayToPointerDecay implicit cast.
5074 auto *Base = ASE->getBase()->IgnoreImplicit();
5075 if (!Base->getType()->isArrayType())
5076 break;
5077
5078 E = Base;
5079 --PathLength;
5080
5081 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5082 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005083 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005084 if (ICE->getCastKind() == CK_NoOp)
5085 continue;
5086 if (ICE->getCastKind() != CK_DerivedToBase &&
5087 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5088 break;
Richard Smitha481b012019-05-30 20:45:12 +00005089 // Walk path backwards as we walk up from the base to the derived class.
5090 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005091 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005092 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005093 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5094 LHS.Designator.Entries[PathLength]
5095 .getAsBaseOrMember().getPointer()));
5096 }
Richard Smith31c69a32019-05-21 23:15:20 +00005097
5098 // -- Otherwise, S(E) is empty.
5099 } else {
5100 break;
5101 }
5102 }
5103
5104 // Common case: no unions' lifetimes are started.
5105 if (UnionPathLengths.empty())
5106 return true;
5107
5108 // if modification of X [would access an inactive union member], an object
5109 // of the type of X is implicitly created
5110 CompleteObject Obj =
5111 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5112 if (!Obj)
5113 return false;
5114 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5115 llvm::reverse(UnionPathLengths)) {
5116 // Form a designator for the union object.
5117 SubobjectDesignator D = LHS.Designator;
5118 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5119
5120 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5121 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5122 return false;
5123 }
5124
5125 return true;
5126}
5127
Richard Smithbe6dd812014-11-19 21:27:17 +00005128/// Determine if a class has any fields that might need to be copied by a
5129/// trivial copy or move operation.
5130static bool hasFields(const CXXRecordDecl *RD) {
5131 if (!RD || RD->isEmpty())
5132 return false;
5133 for (auto *FD : RD->fields()) {
5134 if (FD->isUnnamedBitfield())
5135 continue;
5136 return true;
5137 }
5138 for (auto &Base : RD->bases())
5139 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5140 return true;
5141 return false;
5142}
5143
Richard Smithd62306a2011-11-10 06:34:14 +00005144namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005145typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005146}
5147
5148/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005149static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5150 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005151 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005152 llvm::SmallBitVector ForbiddenNullArgs;
5153 if (Callee->hasAttr<NonNullAttr>()) {
5154 ForbiddenNullArgs.resize(Args.size());
5155 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5156 if (!Attr->args_size()) {
5157 ForbiddenNullArgs.set();
5158 break;
5159 } else
5160 for (auto Idx : Attr->args()) {
5161 unsigned ASTIdx = Idx.getASTIndex();
5162 if (ASTIdx >= Args.size())
5163 continue;
5164 ForbiddenNullArgs[ASTIdx] = 1;
5165 }
5166 }
5167 }
Richard Smithd62306a2011-11-10 06:34:14 +00005168 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005169 I != E; ++I) {
5170 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5171 // If we're checking for a potential constant expression, evaluate all
5172 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005173 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005174 return false;
5175 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005176 } else if (!ForbiddenNullArgs.empty() &&
5177 ForbiddenNullArgs[I - Args.begin()] &&
5178 ArgValues[I - Args.begin()].isNullPointer()) {
5179 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5180 if (!Info.noteFailure())
5181 return false;
5182 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005183 }
5184 }
5185 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005186}
5187
Richard Smith254a73d2011-10-28 22:34:42 +00005188/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005189static bool HandleFunctionCall(SourceLocation CallLoc,
5190 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005191 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005192 EvalInfo &Info, APValue &Result,
5193 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005194 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005195 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005196 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005197
Richard Smith253c2a32012-01-27 01:14:48 +00005198 if (!Info.CheckCallLimit(CallLoc))
5199 return false;
5200
5201 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005202
5203 // For a trivial copy or move assignment, perform an APValue copy. This is
5204 // essential for unions, where the operations performed by the assignment
5205 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005206 //
5207 // Skip this for non-union classes with no fields; in that case, the defaulted
5208 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005209 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005210 if (MD && MD->isDefaulted() &&
5211 (MD->getParent()->isUnion() ||
5212 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005213 assert(This &&
5214 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5215 LValue RHS;
5216 RHS.setFrom(Info.Ctx, ArgValues[0]);
5217 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005218 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5219 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005220 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005221 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5222 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5223 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005224 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005225 RHSValue))
5226 return false;
5227 This->moveInto(Result);
5228 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005229 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005230 // We're in a lambda; determine the lambda capture field maps unless we're
5231 // just constexpr checking a lambda's call operator. constexpr checking is
5232 // done before the captures have been added to the closure object (unless
5233 // we're inferring constexpr-ness), so we don't have access to them in this
5234 // case. But since we don't need the captures to constexpr check, we can
5235 // just ignore them.
5236 if (!Info.checkingPotentialConstantExpression())
5237 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5238 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005239 }
5240
Richard Smith52a980a2015-08-28 02:43:42 +00005241 StmtResult Ret = {Result, ResultSlot};
5242 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005243 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005244 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005245 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005246 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005247 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005248 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005249}
5250
Richard Smithd62306a2011-11-10 06:34:14 +00005251/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005252static bool HandleConstructorCall(const Expr *E, const LValue &This,
5253 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005254 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005255 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005256 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005257 if (!Info.CheckCallLimit(CallLoc))
5258 return false;
5259
Richard Smith3607ffe2012-02-13 03:54:03 +00005260 const CXXRecordDecl *RD = Definition->getParent();
5261 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005262 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005263 return false;
5264 }
5265
Erik Pilkington42925492017-10-04 00:18:55 +00005266 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005267 Info,
5268 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5269 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005270 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005271
Richard Smith52a980a2015-08-28 02:43:42 +00005272 // FIXME: Creating an APValue just to hold a nonexistent return value is
5273 // wasteful.
5274 APValue RetVal;
5275 StmtResult Ret = {RetVal, nullptr};
5276
Richard Smith5179eb72016-06-28 19:03:57 +00005277 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005278 if (Definition->isDelegatingConstructor()) {
5279 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005280 {
5281 FullExpressionRAII InitScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00005282 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5283 !InitScope.destroy())
Richard Smith9ff62af2013-11-07 18:45:03 +00005284 return false;
5285 }
Richard Smith52a980a2015-08-28 02:43:42 +00005286 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005287 }
5288
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005289 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005290 // essential for unions (or classes with anonymous union members), where the
5291 // operations performed by the constructor cannot be represented by
5292 // ctor-initializers.
5293 //
5294 // Skip this for empty non-union classes; we should not perform an
5295 // lvalue-to-rvalue conversion on them because their copy constructor does not
5296 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005297 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005298 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005299 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005300 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005301 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005302 return handleLValueToRValueConversion(
5303 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005304 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005305 }
5306
5307 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005308 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005309 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005310 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005311
John McCalld7bca762012-05-01 00:38:49 +00005312 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005313 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5314
Richard Smith08d6a2c2013-07-24 07:11:57 +00005315 // A scope for temporaries lifetime-extended by reference members.
5316 BlockScopeRAII LifetimeExtendedScope(Info);
5317
Richard Smith253c2a32012-01-27 01:14:48 +00005318 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005319 unsigned BasesSeen = 0;
5320#ifndef NDEBUG
5321 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5322#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005323 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5324 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5325 // We might be initializing the same field again if this is an indirect
5326 // field initialization.
5327 if (FieldIt == RD->field_end() ||
5328 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5329 assert(Indirect && "fields out of order?");
5330 return;
5331 }
5332
5333 // Default-initialize any fields with no explicit initializer.
5334 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5335 assert(FieldIt != RD->field_end() && "missing field?");
5336 if (!FieldIt->isUnnamedBitfield())
5337 Result.getStructField(FieldIt->getFieldIndex()) =
5338 getDefaultInitValue(FieldIt->getType());
5339 }
5340 ++FieldIt;
5341 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005342 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005343 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005344 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005345 APValue *Value = &Result;
5346
5347 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005348 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005349 if (I->isBaseInitializer()) {
5350 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005351#ifndef NDEBUG
5352 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005353 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005354 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5355 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5356 "base class initializers not in expected order");
5357 ++BaseIt;
5358#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005359 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005360 BaseType->getAsCXXRecordDecl(), &Layout))
5361 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005362 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005363 } else if ((FD = I->getMember())) {
5364 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005365 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005366 if (RD->isUnion()) {
5367 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005368 Value = &Result.getUnionValue();
5369 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005370 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005371 Value = &Result.getStructField(FD->getFieldIndex());
5372 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005373 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005374 // Walk the indirect field decl's chain to find the object to initialize,
5375 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005376 auto IndirectFieldChain = IFD->chain();
5377 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005378 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005379 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5380 // Switch the union field if it differs. This happens if we had
5381 // preceding zero-initialization, and we're now initializing a union
5382 // subobject other than the first.
5383 // FIXME: In this case, the values of the other subobjects are
5384 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005385 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005386 (Value->isUnion() && Value->getUnionField() != FD)) {
5387 if (CD->isUnion())
5388 *Value = APValue(FD);
5389 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005390 // FIXME: This immediately starts the lifetime of all members of an
5391 // anonymous struct. It would be preferable to strictly start member
5392 // lifetime in initialization order.
5393 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005394 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005395 // Store Subobject as its parent before updating it for the last element
5396 // in the chain.
5397 if (C == IndirectFieldChain.back())
5398 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005399 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005400 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005401 if (CD->isUnion())
5402 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005403 else {
5404 if (C == IndirectFieldChain.front() && !RD->isUnion())
5405 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005406 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005407 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005408 }
Richard Smithd62306a2011-11-10 06:34:14 +00005409 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005410 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005411 }
Richard Smith253c2a32012-01-27 01:14:48 +00005412
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005413 // Need to override This for implicit field initializers as in this case
5414 // This refers to innermost anonymous struct/union containing initializer,
5415 // not to currently constructed class.
5416 const Expr *Init = I->getInit();
5417 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5418 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005419 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005420 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5421 (FD && FD->isBitField() &&
5422 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005423 // If we're checking for a potential constant expression, evaluate all
5424 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005425 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005426 return false;
5427 Success = false;
5428 }
Richard Smith921f1322019-05-13 23:35:21 +00005429
5430 // This is the point at which the dynamic type of the object becomes this
5431 // class type.
5432 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5433 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005434 }
5435
Richard Smithc667cdc2019-09-18 17:37:44 +00005436 // Default-initialize any remaining fields.
5437 if (!RD->isUnion()) {
5438 for (; FieldIt != RD->field_end(); ++FieldIt) {
5439 if (!FieldIt->isUnnamedBitfield())
5440 Result.getStructField(FieldIt->getFieldIndex()) =
5441 getDefaultInitValue(FieldIt->getType());
5442 }
5443 }
5444
Richard Smithd9f663b2013-04-22 15:31:51 +00005445 return Success &&
Richard Smith457226e2019-09-23 03:48:44 +00005446 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5447 LifetimeExtendedScope.destroy();
Richard Smithd62306a2011-11-10 06:34:14 +00005448}
5449
Richard Smith5179eb72016-06-28 19:03:57 +00005450static bool HandleConstructorCall(const Expr *E, const LValue &This,
5451 ArrayRef<const Expr*> Args,
5452 const CXXConstructorDecl *Definition,
5453 EvalInfo &Info, APValue &Result) {
5454 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005455 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005456 return false;
5457
5458 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5459 Info, Result);
5460}
5461
Richard Smith457226e2019-09-23 03:48:44 +00005462static bool HandleDestructorCallImpl(EvalInfo &Info, SourceLocation CallLoc,
5463 const LValue &This, APValue &Value,
5464 QualType T) {
5465 // Invent an expression for location purposes.
5466 // FIXME: We shouldn't need to do this.
5467 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5468
5469 // For arrays, destroy elements right-to-left.
5470 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5471 uint64_t Size = CAT->getSize().getZExtValue();
5472 QualType ElemT = CAT->getElementType();
5473
5474 LValue ElemLV = This;
5475 ElemLV.addArray(Info, &LocE, CAT);
5476 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5477 return false;
5478
5479 for (; Size != 0; --Size) {
5480 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5481 if (!HandleDestructorCallImpl(Info, CallLoc, ElemLV, Elem, ElemT) ||
5482 !HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1))
5483 return false;
5484 }
5485
5486 // End the lifetime of this array now.
5487 Value = APValue();
5488 return true;
5489 }
5490
5491 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5492 if (!RD) {
5493 if (T.isDestructedType()) {
5494 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5495 return false;
5496 }
5497
5498 Value = APValue();
5499 return true;
5500 }
5501
5502 if (RD->getNumVBases()) {
5503 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5504 return false;
5505 }
5506
5507 const CXXDestructorDecl *DD = RD->getDestructor();
5508 if (!DD) {
5509 // FIXME: Can we get here for a type with an irrelevant destructor?
5510 Info.FFDiag(CallLoc);
5511 return false;
5512 }
5513
5514 const FunctionDecl *Definition = nullptr;
5515 const Stmt *Body = DD->getBody(Definition);
5516
5517 if ((DD && DD->isTrivial()) ||
5518 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5519 // A trivial destructor just ends the lifetime of the object. Check for
5520 // this case before checking for a body, because we might not bother
5521 // building a body for a trivial destructor. Note that it doesn't matter
5522 // whether the destructor is constexpr in this case; all trivial
5523 // destructors are constexpr.
5524 //
5525 // If an anonymous union would be destroyed, some enclosing destructor must
5526 // have been explicitly defined, and the anonymous union destruction should
5527 // have no effect.
5528 Value = APValue();
5529 return true;
5530 }
5531
5532 if (!Info.CheckCallLimit(CallLoc))
5533 return false;
5534
5535 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5536 return false;
5537
5538 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5539
5540 // We're now in the period of destruction of this object.
5541 unsigned BasesLeft = RD->getNumBases();
5542 EvalInfo::EvaluatingDestructorRAII EvalObj(
5543 Info,
5544 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5545
5546 // FIXME: Creating an APValue just to hold a nonexistent return value is
5547 // wasteful.
5548 APValue RetVal;
5549 StmtResult Ret = {RetVal, nullptr};
5550 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5551 return false;
5552
5553 // A union destructor does not implicitly destroy its members.
5554 if (RD->isUnion())
5555 return true;
5556
5557 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5558
5559 // We don't have a good way to iterate fields in reverse, so collect all the
5560 // fields first and then walk them backwards.
5561 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5562 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5563 if (FD->isUnnamedBitfield())
5564 continue;
5565
5566 LValue Subobject = This;
5567 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5568 return false;
5569
5570 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5571 if (!HandleDestructorCallImpl(Info, CallLoc, Subobject, *SubobjectValue,
5572 FD->getType()))
5573 return false;
5574 }
5575
5576 if (BasesLeft != 0)
5577 EvalObj.startedDestroyingBases();
5578
5579 // Destroy base classes in reverse order.
5580 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5581 --BasesLeft;
5582
5583 QualType BaseType = Base.getType();
5584 LValue Subobject = This;
5585 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5586 BaseType->getAsCXXRecordDecl(), &Layout))
5587 return false;
5588
5589 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5590 if (!HandleDestructorCallImpl(Info, CallLoc, Subobject, *SubobjectValue,
5591 BaseType))
5592 return false;
5593 }
5594 assert(BasesLeft == 0 && "NumBases was wrong?");
5595
5596 // The period of destruction ends now. The object is gone.
5597 Value = APValue();
5598 return true;
5599}
5600
5601static bool HandleDestructorCall(EvalInfo &Info, APValue::LValueBase LVBase,
5602 APValue &Value, QualType T) {
5603 SourceLocation Loc;
5604 if (const ValueDecl *VD = LVBase.dyn_cast<const ValueDecl*>())
5605 Loc = VD->getLocation();
5606 else if (const Expr *E = LVBase.dyn_cast<const Expr*>())
5607 Loc = E->getExprLoc();
5608
5609 LValue LV;
5610 LV.set({LVBase});
5611 return HandleDestructorCallImpl(Info, Loc, LV, Value, T);
5612}
5613
Eli Friedman9a156e52008-11-12 09:44:48 +00005614//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005615// Generic Evaluation
5616//===----------------------------------------------------------------------===//
5617namespace {
5618
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005619class BitCastBuffer {
5620 // FIXME: We're going to need bit-level granularity when we support
5621 // bit-fields.
5622 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5623 // we don't support a host or target where that is the case. Still, we should
5624 // use a more generic type in case we ever do.
5625 SmallVector<Optional<unsigned char>, 32> Bytes;
5626
5627 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5628 "Need at least 8 bit unsigned char");
5629
5630 bool TargetIsLittleEndian;
5631
5632public:
5633 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5634 : Bytes(Width.getQuantity()),
5635 TargetIsLittleEndian(TargetIsLittleEndian) {}
5636
5637 LLVM_NODISCARD
5638 bool readObject(CharUnits Offset, CharUnits Width,
5639 SmallVectorImpl<unsigned char> &Output) const {
5640 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5641 // If a byte of an integer is uninitialized, then the whole integer is
5642 // uninitalized.
5643 if (!Bytes[I.getQuantity()])
5644 return false;
5645 Output.push_back(*Bytes[I.getQuantity()]);
5646 }
5647 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5648 std::reverse(Output.begin(), Output.end());
5649 return true;
5650 }
5651
5652 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5653 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5654 std::reverse(Input.begin(), Input.end());
5655
5656 size_t Index = 0;
5657 for (unsigned char Byte : Input) {
5658 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5659 Bytes[Offset.getQuantity() + Index] = Byte;
5660 ++Index;
5661 }
5662 }
5663
5664 size_t size() { return Bytes.size(); }
5665};
5666
5667/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5668/// target would represent the value at runtime.
5669class APValueToBufferConverter {
5670 EvalInfo &Info;
5671 BitCastBuffer Buffer;
5672 const CastExpr *BCE;
5673
5674 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5675 const CastExpr *BCE)
5676 : Info(Info),
5677 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5678 BCE(BCE) {}
5679
5680 bool visit(const APValue &Val, QualType Ty) {
5681 return visit(Val, Ty, CharUnits::fromQuantity(0));
5682 }
5683
5684 // Write out Val with type Ty into Buffer starting at Offset.
5685 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5686 assert((size_t)Offset.getQuantity() <= Buffer.size());
5687
5688 // As a special case, nullptr_t has an indeterminate value.
5689 if (Ty->isNullPtrType())
5690 return true;
5691
5692 // Dig through Src to find the byte at SrcOffset.
5693 switch (Val.getKind()) {
5694 case APValue::Indeterminate:
5695 case APValue::None:
5696 return true;
5697
5698 case APValue::Int:
5699 return visitInt(Val.getInt(), Ty, Offset);
5700 case APValue::Float:
5701 return visitFloat(Val.getFloat(), Ty, Offset);
5702 case APValue::Array:
5703 return visitArray(Val, Ty, Offset);
5704 case APValue::Struct:
5705 return visitRecord(Val, Ty, Offset);
5706
5707 case APValue::ComplexInt:
5708 case APValue::ComplexFloat:
5709 case APValue::Vector:
5710 case APValue::FixedPoint:
5711 // FIXME: We should support these.
5712
5713 case APValue::Union:
5714 case APValue::MemberPointer:
5715 case APValue::AddrLabelDiff: {
5716 Info.FFDiag(BCE->getBeginLoc(),
5717 diag::note_constexpr_bit_cast_unsupported_type)
5718 << Ty;
5719 return false;
5720 }
5721
5722 case APValue::LValue:
5723 llvm_unreachable("LValue subobject in bit_cast?");
5724 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005725 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005726 }
5727
5728 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5729 const RecordDecl *RD = Ty->getAsRecordDecl();
5730 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5731
5732 // Visit the base classes.
5733 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5734 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5735 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5736 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5737
5738 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5739 Layout.getBaseClassOffset(BaseDecl) + Offset))
5740 return false;
5741 }
5742 }
5743
5744 // Visit the fields.
5745 unsigned FieldIdx = 0;
5746 for (FieldDecl *FD : RD->fields()) {
5747 if (FD->isBitField()) {
5748 Info.FFDiag(BCE->getBeginLoc(),
5749 diag::note_constexpr_bit_cast_unsupported_bitfield);
5750 return false;
5751 }
5752
5753 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5754
5755 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5756 "only bit-fields can have sub-char alignment");
5757 CharUnits FieldOffset =
5758 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5759 QualType FieldTy = FD->getType();
5760 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5761 return false;
5762 ++FieldIdx;
5763 }
5764
5765 return true;
5766 }
5767
5768 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5769 const auto *CAT =
5770 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5771 if (!CAT)
5772 return false;
5773
5774 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5775 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5776 unsigned ArraySize = Val.getArraySize();
5777 // First, initialize the initialized elements.
5778 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5779 const APValue &SubObj = Val.getArrayInitializedElt(I);
5780 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5781 return false;
5782 }
5783
5784 // Next, initialize the rest of the array using the filler.
5785 if (Val.hasArrayFiller()) {
5786 const APValue &Filler = Val.getArrayFiller();
5787 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5788 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5789 return false;
5790 }
5791 }
5792
5793 return true;
5794 }
5795
5796 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5797 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5798 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5799 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5800 Buffer.writeObject(Offset, Bytes);
5801 return true;
5802 }
5803
5804 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5805 APSInt AsInt(Val.bitcastToAPInt());
5806 return visitInt(AsInt, Ty, Offset);
5807 }
5808
5809public:
5810 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5811 const CastExpr *BCE) {
5812 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5813 APValueToBufferConverter Converter(Info, DstSize, BCE);
5814 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5815 return None;
5816 return Converter.Buffer;
5817 }
5818};
5819
5820/// Write an BitCastBuffer into an APValue.
5821class BufferToAPValueConverter {
5822 EvalInfo &Info;
5823 const BitCastBuffer &Buffer;
5824 const CastExpr *BCE;
5825
5826 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5827 const CastExpr *BCE)
5828 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5829
5830 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5831 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5832 // Ideally this will be unreachable.
5833 llvm::NoneType unsupportedType(QualType Ty) {
5834 Info.FFDiag(BCE->getBeginLoc(),
5835 diag::note_constexpr_bit_cast_unsupported_type)
5836 << Ty;
5837 return None;
5838 }
5839
5840 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5841 const EnumType *EnumSugar = nullptr) {
5842 if (T->isNullPtrType()) {
5843 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5844 return APValue((Expr *)nullptr,
5845 /*Offset=*/CharUnits::fromQuantity(NullValue),
5846 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5847 }
5848
5849 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5850 SmallVector<uint8_t, 8> Bytes;
5851 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5852 // If this is std::byte or unsigned char, then its okay to store an
5853 // indeterminate value.
5854 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5855 bool IsUChar =
5856 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5857 T->isSpecificBuiltinType(BuiltinType::Char_U));
5858 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00005859 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005860 Info.FFDiag(BCE->getExprLoc(),
5861 diag::note_constexpr_bit_cast_indet_dest)
5862 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5863 return None;
5864 }
5865
5866 return APValue::IndeterminateValue();
5867 }
5868
5869 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5870 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5871
5872 if (T->isIntegralOrEnumerationType()) {
5873 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5874 return APValue(Val);
5875 }
5876
5877 if (T->isRealFloatingType()) {
5878 const llvm::fltSemantics &Semantics =
5879 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5880 return APValue(APFloat(Semantics, Val));
5881 }
5882
5883 return unsupportedType(QualType(T, 0));
5884 }
5885
5886 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5887 const RecordDecl *RD = RTy->getAsRecordDecl();
5888 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5889
5890 unsigned NumBases = 0;
5891 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5892 NumBases = CXXRD->getNumBases();
5893
5894 APValue ResultVal(APValue::UninitStruct(), NumBases,
5895 std::distance(RD->field_begin(), RD->field_end()));
5896
5897 // Visit the base classes.
5898 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5899 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5900 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5901 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5902 if (BaseDecl->isEmpty() ||
5903 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5904 continue;
5905
5906 Optional<APValue> SubObj = visitType(
5907 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5908 if (!SubObj)
5909 return None;
5910 ResultVal.getStructBase(I) = *SubObj;
5911 }
5912 }
5913
5914 // Visit the fields.
5915 unsigned FieldIdx = 0;
5916 for (FieldDecl *FD : RD->fields()) {
5917 // FIXME: We don't currently support bit-fields. A lot of the logic for
5918 // this is in CodeGen, so we need to factor it around.
5919 if (FD->isBitField()) {
5920 Info.FFDiag(BCE->getBeginLoc(),
5921 diag::note_constexpr_bit_cast_unsupported_bitfield);
5922 return None;
5923 }
5924
5925 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5926 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5927
5928 CharUnits FieldOffset =
5929 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5930 Offset;
5931 QualType FieldTy = FD->getType();
5932 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5933 if (!SubObj)
5934 return None;
5935 ResultVal.getStructField(FieldIdx) = *SubObj;
5936 ++FieldIdx;
5937 }
5938
5939 return ResultVal;
5940 }
5941
5942 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5943 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5944 assert(!RepresentationType.isNull() &&
5945 "enum forward decl should be caught by Sema");
5946 const BuiltinType *AsBuiltin =
5947 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5948 assert(AsBuiltin && "non-integral enum underlying type?");
5949 // Recurse into the underlying type. Treat std::byte transparently as
5950 // unsigned char.
5951 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5952 }
5953
5954 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5955 size_t Size = Ty->getSize().getLimitedValue();
5956 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5957
5958 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5959 for (size_t I = 0; I != Size; ++I) {
5960 Optional<APValue> ElementValue =
5961 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5962 if (!ElementValue)
5963 return None;
5964 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5965 }
5966
5967 return ArrayValue;
5968 }
5969
5970 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5971 return unsupportedType(QualType(Ty, 0));
5972 }
5973
5974 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5975 QualType Can = Ty.getCanonicalType();
5976
5977 switch (Can->getTypeClass()) {
5978#define TYPE(Class, Base) \
5979 case Type::Class: \
5980 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5981#define ABSTRACT_TYPE(Class, Base)
5982#define NON_CANONICAL_TYPE(Class, Base) \
5983 case Type::Class: \
5984 llvm_unreachable("non-canonical type should be impossible!");
5985#define DEPENDENT_TYPE(Class, Base) \
5986 case Type::Class: \
5987 llvm_unreachable( \
5988 "dependent types aren't supported in the constant evaluator!");
5989#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5990 case Type::Class: \
5991 llvm_unreachable("either dependent or not canonical!");
5992#include "clang/AST/TypeNodes.def"
5993 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005994 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005995 }
5996
5997public:
5998 // Pull out a full value of type DstType.
5999 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6000 const CastExpr *BCE) {
6001 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6002 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6003 }
6004};
6005
6006static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6007 QualType Ty, EvalInfo *Info,
6008 const ASTContext &Ctx,
6009 bool CheckingDest) {
6010 Ty = Ty.getCanonicalType();
6011
6012 auto diag = [&](int Reason) {
6013 if (Info)
6014 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6015 << CheckingDest << (Reason == 4) << Reason;
6016 return false;
6017 };
6018 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6019 if (Info)
6020 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6021 << NoteTy << Construct << Ty;
6022 return false;
6023 };
6024
6025 if (Ty->isUnionType())
6026 return diag(0);
6027 if (Ty->isPointerType())
6028 return diag(1);
6029 if (Ty->isMemberPointerType())
6030 return diag(2);
6031 if (Ty.isVolatileQualified())
6032 return diag(3);
6033
6034 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6035 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6036 for (CXXBaseSpecifier &BS : CXXRD->bases())
6037 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6038 CheckingDest))
6039 return note(1, BS.getType(), BS.getBeginLoc());
6040 }
6041 for (FieldDecl *FD : Record->fields()) {
6042 if (FD->getType()->isReferenceType())
6043 return diag(4);
6044 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6045 CheckingDest))
6046 return note(0, FD->getType(), FD->getBeginLoc());
6047 }
6048 }
6049
6050 if (Ty->isArrayType() &&
6051 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6052 Info, Ctx, CheckingDest))
6053 return false;
6054
6055 return true;
6056}
6057
6058static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6059 const ASTContext &Ctx,
6060 const CastExpr *BCE) {
6061 bool DestOK = checkBitCastConstexprEligibilityType(
6062 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6063 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6064 BCE->getBeginLoc(),
6065 BCE->getSubExpr()->getType(), Info, Ctx, false);
6066 return SourceOK;
6067}
6068
6069static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6070 APValue &SourceValue,
6071 const CastExpr *BCE) {
6072 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6073 "no host or target supports non 8-bit chars");
6074 assert(SourceValue.isLValue() &&
6075 "LValueToRValueBitcast requires an lvalue operand!");
6076
6077 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6078 return false;
6079
6080 LValue SourceLValue;
6081 APValue SourceRValue;
6082 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00006083 if (!handleLValueToRValueConversion(
6084 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6085 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006086 return false;
6087
6088 // Read out SourceValue into a char buffer.
6089 Optional<BitCastBuffer> Buffer =
6090 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6091 if (!Buffer)
6092 return false;
6093
6094 // Write out the buffer into a new APValue.
6095 Optional<APValue> MaybeDestValue =
6096 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6097 if (!MaybeDestValue)
6098 return false;
6099
6100 DestValue = std::move(*MaybeDestValue);
6101 return true;
6102}
6103
Aaron Ballman68af21c2014-01-03 19:26:43 +00006104template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00006105class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006106 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00006107private:
Richard Smith52a980a2015-08-28 02:43:42 +00006108 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006109 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006110 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006111 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006112 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006113 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006114 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006115
Richard Smith17100ba2012-02-16 02:46:34 +00006116 // Check whether a conditional operator with a non-constant condition is a
6117 // potential constant expression. If neither arm is a potential constant
6118 // expression, then the conditional operator is not either.
6119 template<typename ConditionalOperator>
6120 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00006121 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00006122
6123 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00006124 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00006125 {
Richard Smith17100ba2012-02-16 02:46:34 +00006126 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006127 StmtVisitorTy::Visit(E->getFalseExpr());
6128 if (Diag.empty())
6129 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00006130 }
Richard Smith17100ba2012-02-16 02:46:34 +00006131
George Burgess IV8c892b52016-05-25 22:31:54 +00006132 {
6133 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006134 Diag.clear();
6135 StmtVisitorTy::Visit(E->getTrueExpr());
6136 if (Diag.empty())
6137 return;
6138 }
6139
6140 Error(E, diag::note_constexpr_conditional_never_const);
6141 }
6142
6143
6144 template<typename ConditionalOperator>
6145 bool HandleConditionalOperator(const ConditionalOperator *E) {
6146 bool BoolResult;
6147 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00006148 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00006149 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00006150 return false;
6151 }
6152 if (Info.noteFailure()) {
6153 StmtVisitorTy::Visit(E->getTrueExpr());
6154 StmtVisitorTy::Visit(E->getFalseExpr());
6155 }
Richard Smith17100ba2012-02-16 02:46:34 +00006156 return false;
6157 }
6158
6159 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6160 return StmtVisitorTy::Visit(EvalExpr);
6161 }
6162
Peter Collingbournee9200682011-05-13 03:29:01 +00006163protected:
6164 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006165 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00006166 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6167
Richard Smith92b1ce02011-12-12 09:28:41 +00006168 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006169 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006170 }
6171
Aaron Ballman68af21c2014-01-03 19:26:43 +00006172 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006173
6174public:
6175 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6176
6177 EvalInfo &getEvalInfo() { return Info; }
6178
Richard Smithf57d8cb2011-12-09 22:58:01 +00006179 /// Report an evaluation error. This should only be called when an error is
6180 /// first discovered. When propagating an error, just return false.
6181 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006182 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006183 return false;
6184 }
6185 bool Error(const Expr *E) {
6186 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6187 }
6188
Aaron Ballman68af21c2014-01-03 19:26:43 +00006189 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00006190 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00006191 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006192 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006193 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006194 }
6195
Bill Wendling8003edc2018-11-09 00:41:36 +00006196 bool VisitConstantExpr(const ConstantExpr *E)
6197 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006198 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006199 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006200 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006201 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006202 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006203 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006204 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00006205 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006206 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006207 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006208 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00006209 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006210 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6211 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00006212 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006213 return StmtVisitorTy::Visit(E->getExpr());
6214 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006215 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006216 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00006217 // The initializer may not have been parsed yet, or might be erroneous.
6218 if (!E->getExpr())
6219 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00006220 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00006221 return StmtVisitorTy::Visit(E->getExpr());
6222 }
Eric Fiselier708afb52019-05-16 21:04:15 +00006223
Richard Smith457226e2019-09-23 03:48:44 +00006224 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6225 FullExpressionRAII Scope(Info);
6226 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6227 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006228
Aaron Ballman68af21c2014-01-03 19:26:43 +00006229 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006230 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6231 return static_cast<Derived*>(this)->VisitCastExpr(E);
6232 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006233 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00006234 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6235 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006236 return static_cast<Derived*>(this)->VisitCastExpr(E);
6237 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006238 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6239 return static_cast<Derived*>(this)->VisitCastExpr(E);
6240 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006241
Aaron Ballman68af21c2014-01-03 19:26:43 +00006242 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006243 switch (E->getOpcode()) {
6244 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006245 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006246
6247 case BO_Comma:
6248 VisitIgnoredValue(E->getLHS());
6249 return StmtVisitorTy::Visit(E->getRHS());
6250
6251 case BO_PtrMemD:
6252 case BO_PtrMemI: {
6253 LValue Obj;
6254 if (!HandleMemberPointerAccess(Info, E, Obj))
6255 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006256 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006257 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006258 return false;
6259 return DerivedSuccess(Result, E);
6260 }
6261 }
6262 }
6263
Aaron Ballman68af21c2014-01-03 19:26:43 +00006264 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006265 // Evaluate and cache the common expression. We treat it as a temporary,
6266 // even though it's not quite the same thing.
Richard Smith457226e2019-09-23 03:48:44 +00006267 LValue CommonLV;
6268 if (!Evaluate(Info.CurrentCall->createTemporary(
6269 E->getOpaqueValue(), getStorageType(Info.Ctx, E->getOpaqueValue()),
6270 false, CommonLV),
Richard Smith26d4cc12012-06-26 08:12:11 +00006271 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006272 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006273
Richard Smith17100ba2012-02-16 02:46:34 +00006274 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006275 }
6276
Aaron Ballman68af21c2014-01-03 19:26:43 +00006277 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006278 bool IsBcpCall = false;
6279 // If the condition (ignoring parens) is a __builtin_constant_p call,
6280 // the result is a constant expression if it can be folded without
6281 // side-effects. This is an important GNU extension. See GCC PR38377
6282 // for discussion.
6283 if (const CallExpr *CallCE =
6284 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006285 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006286 IsBcpCall = true;
6287
6288 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6289 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00006290 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6291 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00006292 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006293 return false;
6294
Richard Smith6d4c6582013-11-05 22:18:15 +00006295 FoldConstant Fold(Info, IsBcpCall);
6296 if (!HandleConditionalOperator(E)) {
6297 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006298 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006299 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006300
6301 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006302 }
6303
Aaron Ballman68af21c2014-01-03 19:26:43 +00006304 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006305 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006306 return DerivedSuccess(*Value, E);
6307
6308 const Expr *Source = E->getSourceExpr();
6309 if (!Source)
6310 return Error(E);
6311 if (Source == E) { // sanity checking.
6312 assert(0 && "OpaqueValueExpr recursively refers to itself");
6313 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006314 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006315 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006316 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006317
Aaron Ballman68af21c2014-01-03 19:26:43 +00006318 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006319 APValue Result;
6320 if (!handleCallExpr(E, Result, nullptr))
6321 return false;
6322 return DerivedSuccess(Result, E);
6323 }
6324
6325 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006326 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006327 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006328 QualType CalleeType = Callee->getType();
6329
Craig Topper36250ad2014-05-12 05:36:57 +00006330 const FunctionDecl *FD = nullptr;
6331 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006332 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006333 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006334
Richard Smithe97cbd72011-11-11 04:05:33 +00006335 // Extract function decl and 'this' pointer from the callee.
6336 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006337 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006338 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6339 // Explicit bound member calls, such as x.f() or p->g();
6340 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006341 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006342 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6343 if (!Member)
6344 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006345 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006346 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006347 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6348 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006349 Member = dyn_cast_or_null<CXXMethodDecl>(
6350 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6351 if (!Member)
6352 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006353 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00006354 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006355 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006356 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006357 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006358 LValue Call;
6359 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006360 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006361
Richard Smitha8105bc2012-01-06 16:39:00 +00006362 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006363 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006364 FD = dyn_cast_or_null<FunctionDecl>(
6365 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006366 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006367 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006368 // Don't call function pointers which have been cast to some other type.
6369 // Per DR (no number yet), the caller and callee can differ in noexcept.
6370 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6371 CalleeType->getPointeeType(), FD->getType())) {
6372 return Error(E);
6373 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006374
6375 // Overloaded operator calls to member functions are represented as normal
6376 // calls with '*this' as the first argument.
6377 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6378 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006379 // FIXME: When selecting an implicit conversion for an overloaded
6380 // operator delete, we sometimes try to evaluate calls to conversion
6381 // operators without a 'this' parameter!
6382 if (Args.empty())
6383 return Error(E);
6384
Nick Lewycky13073a62017-06-12 21:15:44 +00006385 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006386 return false;
6387 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006388 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006389 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006390 // Map the static invoker for the lambda back to the call operator.
6391 // Conveniently, we don't have to slice out the 'this' argument (as is
6392 // being done for the non-static case), since a static member function
6393 // doesn't have an implicit argument passed in.
6394 const CXXRecordDecl *ClosureClass = MD->getParent();
6395 assert(
6396 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6397 "Number of captures must be zero for conversion to function-ptr");
6398
6399 const CXXMethodDecl *LambdaCallOp =
6400 ClosureClass->getLambdaCallOperator();
6401
6402 // Set 'FD', the function that will be called below, to the call
6403 // operator. If the closure object represents a generic lambda, find
6404 // the corresponding specialization of the call operator.
6405
6406 if (ClosureClass->isGenericLambda()) {
6407 assert(MD->isFunctionTemplateSpecialization() &&
6408 "A generic lambda's static-invoker function must be a "
6409 "template specialization");
6410 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6411 FunctionTemplateDecl *CallOpTemplate =
6412 LambdaCallOp->getDescribedFunctionTemplate();
6413 void *InsertPos = nullptr;
6414 FunctionDecl *CorrespondingCallOpSpecialization =
6415 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6416 assert(CorrespondingCallOpSpecialization &&
6417 "We must always have a function call operator specialization "
6418 "that corresponds to our static invoker specialization");
6419 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6420 } else
6421 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00006422 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006423 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006424 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006425
Richard Smith921f1322019-05-13 23:35:21 +00006426 SmallVector<QualType, 4> CovariantAdjustmentPath;
6427 if (This) {
6428 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006429 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6430 // Perform virtual dispatch, if necessary.
6431 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6432 CovariantAdjustmentPath);
6433 if (!FD)
6434 return false;
6435 } else {
6436 // Check that the 'this' pointer points to an object of the right type.
6437 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6438 return false;
6439 }
Richard Smith921f1322019-05-13 23:35:21 +00006440 }
Richard Smith47b34932012-02-01 02:39:43 +00006441
Craig Topper36250ad2014-05-12 05:36:57 +00006442 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006443 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006444
Nick Lewycky13073a62017-06-12 21:15:44 +00006445 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6446 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006447 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006448 return false;
6449
Richard Smith921f1322019-05-13 23:35:21 +00006450 if (!CovariantAdjustmentPath.empty() &&
6451 !HandleCovariantReturnAdjustment(Info, E, Result,
6452 CovariantAdjustmentPath))
6453 return false;
6454
Richard Smith52a980a2015-08-28 02:43:42 +00006455 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006456 }
6457
Aaron Ballman68af21c2014-01-03 19:26:43 +00006458 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006459 return StmtVisitorTy::Visit(E->getInitializer());
6460 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006461 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006462 if (E->getNumInits() == 0)
6463 return DerivedZeroInitialization(E);
6464 if (E->getNumInits() == 1)
6465 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006466 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006467 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006468 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006469 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006470 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006471 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006472 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006473 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006474 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006475 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006476 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006477
Richard Smithd62306a2011-11-10 06:34:14 +00006478 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006479 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006480 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6481 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006482 assert(!E->isArrow() && "missing call to bound member function?");
6483
Richard Smith2e312c82012-03-03 22:46:17 +00006484 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006485 if (!Evaluate(Val, Info, E->getBase()))
6486 return false;
6487
6488 QualType BaseTy = E->getBase()->getType();
6489
6490 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00006491 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006492 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00006493 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00006494 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6495
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006496 // Note: there is no lvalue base here. But this case should only ever
6497 // happen in C or in C++98, where we cannot be evaluating a constexpr
6498 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00006499 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00006500 SubobjectDesignator Designator(BaseTy);
6501 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00006502
Richard Smith3229b742013-05-05 21:17:10 +00006503 APValue Result;
6504 return extractSubobject(Info, E, Obj, Designator, Result) &&
6505 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00006506 }
6507
Aaron Ballman68af21c2014-01-03 19:26:43 +00006508 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006509 switch (E->getCastKind()) {
6510 default:
6511 break;
6512
Richard Smitha23ab512013-05-23 00:30:41 +00006513 case CK_AtomicToNonAtomic: {
6514 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00006515 // This does not need to be done in place even for class/array types:
6516 // atomic-to-non-atomic conversion implies copying the object
6517 // representation.
6518 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00006519 return false;
6520 return DerivedSuccess(AtomicVal, E);
6521 }
6522
Richard Smith11562c52011-10-28 17:51:58 +00006523 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00006524 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00006525 return StmtVisitorTy::Visit(E->getSubExpr());
6526
6527 case CK_LValueToRValue: {
6528 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006529 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6530 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006531 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00006532 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00006533 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00006534 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006535 return false;
6536 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00006537 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006538 case CK_LValueToRValueBitCast: {
6539 APValue DestValue, SourceValue;
6540 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6541 return false;
6542 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6543 return false;
6544 return DerivedSuccess(DestValue, E);
6545 }
Richard Smith11562c52011-10-28 17:51:58 +00006546 }
6547
Richard Smithf57d8cb2011-12-09 22:58:01 +00006548 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006549 }
6550
Aaron Ballman68af21c2014-01-03 19:26:43 +00006551 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006552 return VisitUnaryPostIncDec(UO);
6553 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006554 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006555 return VisitUnaryPostIncDec(UO);
6556 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006557 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006558 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006559 return Error(UO);
6560
6561 LValue LVal;
6562 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6563 return false;
6564 APValue RVal;
6565 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6566 UO->isIncrementOp(), &RVal))
6567 return false;
6568 return DerivedSuccess(RVal, UO);
6569 }
6570
Aaron Ballman68af21c2014-01-03 19:26:43 +00006571 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00006572 // We will have checked the full-expressions inside the statement expression
6573 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00006574 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00006575 return Error(E);
6576
6577 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006578 if (CS->body_empty())
6579 return true;
6580
Richard Smith457226e2019-09-23 03:48:44 +00006581 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00006582 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6583 BE = CS->body_end();
6584 /**/; ++BI) {
6585 if (BI + 1 == BE) {
6586 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6587 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006588 Info.FFDiag((*BI)->getBeginLoc(),
6589 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006590 return false;
6591 }
Richard Smith457226e2019-09-23 03:48:44 +00006592 return this->Visit(FinalExpr) && Scope.destroy();
Richard Smith51f03172013-06-20 03:00:05 +00006593 }
6594
6595 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00006596 StmtResult Result = { ReturnValue, nullptr };
6597 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00006598 if (ESR != ESR_Succeeded) {
6599 // FIXME: If the statement-expression terminated due to 'return',
6600 // 'break', or 'continue', it would be nice to propagate that to
6601 // the outer statement evaluation rather than bailing out.
6602 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006603 Info.FFDiag((*BI)->getBeginLoc(),
6604 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006605 return false;
6606 }
6607 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006608
6609 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00006610 }
6611
Richard Smith4a678122011-10-24 18:44:57 +00006612 /// Visit a value which is evaluated, but whose value is ignored.
6613 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00006614 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00006615 }
David Majnemere9807b22016-02-26 04:23:19 +00006616
6617 /// Potentially visit a MemberExpr's base expression.
6618 void VisitIgnoredBaseExpression(const Expr *E) {
6619 // While MSVC doesn't evaluate the base expression, it does diagnose the
6620 // presence of side-effecting behavior.
6621 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6622 return;
6623 VisitIgnoredValue(E);
6624 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006625};
6626
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006627} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00006628
6629//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006630// Common base class for lvalue and temporary evaluation.
6631//===----------------------------------------------------------------------===//
6632namespace {
6633template<class Derived>
6634class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006635 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00006636protected:
6637 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006638 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00006639 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006640 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00006641
6642 bool Success(APValue::LValueBase B) {
6643 Result.set(B);
6644 return true;
6645 }
6646
George Burgess IVf9013bf2017-02-10 22:52:29 +00006647 bool evaluatePointer(const Expr *E, LValue &Result) {
6648 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6649 }
6650
Richard Smith027bf112011-11-17 22:56:20 +00006651public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006652 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6653 : ExprEvaluatorBaseTy(Info), Result(Result),
6654 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00006655
Richard Smith2e312c82012-03-03 22:46:17 +00006656 bool Success(const APValue &V, const Expr *E) {
6657 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00006658 return true;
6659 }
Richard Smith027bf112011-11-17 22:56:20 +00006660
Richard Smith027bf112011-11-17 22:56:20 +00006661 bool VisitMemberExpr(const MemberExpr *E) {
6662 // Handle non-static data members.
6663 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006664 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00006665 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006666 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00006667 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00006668 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006669 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00006670 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00006671 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00006672 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00006673 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00006674 BaseTy = E->getBase()->getType();
6675 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00006676 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006677 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006678 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006679 Result.setInvalid(E);
6680 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006681 }
Richard Smith027bf112011-11-17 22:56:20 +00006682
Richard Smith1b78b3d2012-01-25 22:15:11 +00006683 const ValueDecl *MD = E->getMemberDecl();
6684 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6685 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6686 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6687 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00006688 if (!HandleLValueMember(this->Info, E, Result, FD))
6689 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006690 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00006691 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6692 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006693 } else
6694 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006695
Richard Smith1b78b3d2012-01-25 22:15:11 +00006696 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00006697 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00006698 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00006699 RefValue))
6700 return false;
6701 return Success(RefValue, E);
6702 }
6703 return true;
6704 }
6705
6706 bool VisitBinaryOperator(const BinaryOperator *E) {
6707 switch (E->getOpcode()) {
6708 default:
6709 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6710
6711 case BO_PtrMemD:
6712 case BO_PtrMemI:
6713 return HandleMemberPointerAccess(this->Info, E, Result);
6714 }
6715 }
6716
6717 bool VisitCastExpr(const CastExpr *E) {
6718 switch (E->getCastKind()) {
6719 default:
6720 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6721
6722 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006723 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00006724 if (!this->Visit(E->getSubExpr()))
6725 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006726
6727 // Now figure out the necessary offset to add to the base LV to get from
6728 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006729 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6730 Result);
Richard Smith027bf112011-11-17 22:56:20 +00006731 }
6732 }
6733};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006734}
Richard Smith027bf112011-11-17 22:56:20 +00006735
6736//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00006737// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006738//
6739// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6740// function designators (in C), decl references to void objects (in C), and
6741// temporaries (if building with -Wno-address-of-temporary).
6742//
6743// LValue evaluation produces values comprising a base expression of one of the
6744// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006745// - Declarations
6746// * VarDecl
6747// * FunctionDecl
6748// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006749// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006750// * StringLiteral
6751// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006752// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006753// * ObjCEncodeExpr
6754// * AddrLabelExpr
6755// * BlockExpr
6756// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006757// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006758// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006759// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006760// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006761// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6762// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006763// * A MaterializeTemporaryExpr that has static storage duration, with no
6764// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006765// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006766//===----------------------------------------------------------------------===//
6767namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006768class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006769 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006770public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006771 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6772 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006773
Richard Smith11562c52011-10-28 17:51:58 +00006774 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006775 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006776
Peter Collingbournee9200682011-05-13 03:29:01 +00006777 bool VisitDeclRefExpr(const DeclRefExpr *E);
6778 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006779 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006780 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6781 bool VisitMemberExpr(const MemberExpr *E);
6782 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6783 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006784 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006785 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006786 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6787 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006788 bool VisitUnaryReal(const UnaryOperator *E);
6789 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006790 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6791 return VisitUnaryPreIncDec(UO);
6792 }
6793 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6794 return VisitUnaryPreIncDec(UO);
6795 }
Richard Smith3229b742013-05-05 21:17:10 +00006796 bool VisitBinAssign(const BinaryOperator *BO);
6797 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006798
Peter Collingbournee9200682011-05-13 03:29:01 +00006799 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006800 switch (E->getCastKind()) {
6801 default:
Richard Smith027bf112011-11-17 22:56:20 +00006802 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006803
Eli Friedmance3e02a2011-10-11 00:13:24 +00006804 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006805 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006806 if (!Visit(E->getSubExpr()))
6807 return false;
6808 Result.Designator.setInvalid();
6809 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006810
Richard Smith027bf112011-11-17 22:56:20 +00006811 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006812 if (!Visit(E->getSubExpr()))
6813 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006814 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006815
6816 case CK_Dynamic:
6817 if (!Visit(E->getSubExpr()))
6818 return false;
6819 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006820 }
6821 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006822};
6823} // end anonymous namespace
6824
Richard Smith11562c52011-10-28 17:51:58 +00006825/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006826/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006827/// * function designators in C, and
6828/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006829/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006830static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6831 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006832 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006833 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006834 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006835}
6836
Peter Collingbournee9200682011-05-13 03:29:01 +00006837bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006838 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006839 return Success(FD);
6840 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006841 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006842 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006843 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006844 return Error(E);
6845}
Richard Smith733237d2011-10-24 23:14:33 +00006846
Faisal Vali0528a312016-11-13 06:09:16 +00006847
Richard Smith11562c52011-10-28 17:51:58 +00006848bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006849
6850 // If we are within a lambda's call operator, check whether the 'VD' referred
6851 // to within 'E' actually represents a lambda-capture that maps to a
6852 // data-member/field within the closure object, and if so, evaluate to the
6853 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006854 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6855 isa<DeclRefExpr>(E) &&
6856 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6857 // We don't always have a complete capture-map when checking or inferring if
6858 // the function call operator meets the requirements of a constexpr function
6859 // - but we don't need to evaluate the captures to determine constexprness
6860 // (dcl.constexpr C++17).
6861 if (Info.checkingPotentialConstantExpression())
6862 return false;
6863
Faisal Vali051e3a22017-02-16 04:12:21 +00006864 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006865 // Start with 'Result' referring to the complete closure object...
6866 Result = *Info.CurrentCall->This;
6867 // ... then update it to refer to the field of the closure object
6868 // that represents the capture.
6869 if (!HandleLValueMember(Info, E, Result, FD))
6870 return false;
6871 // And if the field is of reference type, update 'Result' to refer to what
6872 // the field refers to.
6873 if (FD->getType()->isReferenceType()) {
6874 APValue RVal;
6875 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6876 RVal))
6877 return false;
6878 Result.setFrom(Info.Ctx, RVal);
6879 }
6880 return true;
6881 }
6882 }
Craig Topper36250ad2014-05-12 05:36:57 +00006883 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006884 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6885 // Only if a local variable was declared in the function currently being
6886 // evaluated, do we expect to be able to find its value in the current
6887 // frame. (Otherwise it was likely declared in an enclosing context and
6888 // could either have a valid evaluatable value (for e.g. a constexpr
6889 // variable) or be ill-formed (and trigger an appropriate evaluation
6890 // diagnostic)).
6891 if (Info.CurrentCall->Callee &&
6892 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6893 Frame = Info.CurrentCall;
6894 }
6895 }
Richard Smith3229b742013-05-05 21:17:10 +00006896
Richard Smithfec09922011-11-01 16:57:24 +00006897 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006898 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006899 Result.set({VD, Frame->Index,
6900 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006901 return true;
6902 }
Richard Smithce40ad62011-11-12 22:28:03 +00006903 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006904 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006905
Richard Smith3229b742013-05-05 21:17:10 +00006906 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006907 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006908 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006909 if (!V->hasValue()) {
6910 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6911 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006912 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006913 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006914 return false;
6915 }
Richard Smith3229b742013-05-05 21:17:10 +00006916 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006917}
6918
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006919bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6920 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006921 // Walk through the expression to find the materialized temporary itself.
6922 SmallVector<const Expr *, 2> CommaLHSs;
6923 SmallVector<SubobjectAdjustment, 2> Adjustments;
6924 const Expr *Inner = E->GetTemporaryExpr()->
6925 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006926
Richard Smith84401042013-06-03 05:03:02 +00006927 // If we passed any comma operators, evaluate their LHSs.
6928 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6929 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6930 return false;
6931
Richard Smithe6c01442013-06-05 00:46:14 +00006932 // A materialized temporary with static storage duration can appear within the
6933 // result of a constant expression evaluation, so we need to preserve its
6934 // value for use outside this evaluation.
6935 APValue *Value;
6936 if (E->getStorageDuration() == SD_Static) {
6937 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006938 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006939 Result.set(E);
6940 } else {
Richard Smith457226e2019-09-23 03:48:44 +00006941 Value = &Info.CurrentCall->createTemporary(
6942 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
Richard Smithe6c01442013-06-05 00:46:14 +00006943 }
6944
Richard Smithea4ad5d2013-06-06 08:19:16 +00006945 QualType Type = Inner->getType();
6946
Richard Smith84401042013-06-03 05:03:02 +00006947 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006948 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6949 (E->getStorageDuration() == SD_Static &&
6950 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6951 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006952 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006953 }
Richard Smith84401042013-06-03 05:03:02 +00006954
6955 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006956 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6957 --I;
6958 switch (Adjustments[I].Kind) {
6959 case SubobjectAdjustment::DerivedToBaseAdjustment:
6960 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6961 Type, Result))
6962 return false;
6963 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6964 break;
6965
6966 case SubobjectAdjustment::FieldAdjustment:
6967 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6968 return false;
6969 Type = Adjustments[I].Field->getType();
6970 break;
6971
6972 case SubobjectAdjustment::MemberPointerAdjustment:
6973 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6974 Adjustments[I].Ptr.RHS))
6975 return false;
6976 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6977 break;
6978 }
6979 }
6980
6981 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006982}
6983
Peter Collingbournee9200682011-05-13 03:29:01 +00006984bool
6985LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006986 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6987 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006988 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6989 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006990 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006991}
6992
Richard Smith6e525142011-12-27 12:18:28 +00006993bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006994 TypeInfoLValue TypeInfo;
6995
Richard Smithee0ce3022019-05-17 07:06:46 +00006996 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006997 if (E->isTypeOperand())
6998 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6999 else
7000 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00007001 } else {
7002 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7003 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7004 << E->getExprOperand()->getType()
7005 << E->getExprOperand()->getSourceRange();
7006 }
7007
7008 if (!Visit(E->getExprOperand()))
7009 return false;
7010
7011 Optional<DynamicType> DynType =
7012 ComputeDynamicType(Info, E, Result, AK_TypeId);
7013 if (!DynType)
7014 return false;
7015
7016 TypeInfo =
7017 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00007018 }
Richard Smith6f3d4352012-10-17 23:52:07 +00007019
Richard Smitha9330302019-05-17 19:19:28 +00007020 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00007021}
7022
Francois Pichet0066db92012-04-16 04:08:35 +00007023bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7024 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00007025}
Francois Pichet0066db92012-04-16 04:08:35 +00007026
Peter Collingbournee9200682011-05-13 03:29:01 +00007027bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007028 // Handle static data members.
7029 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007030 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00007031 return VisitVarDecl(E, VD);
7032 }
7033
Richard Smith254a73d2011-10-28 22:34:42 +00007034 // Handle static member functions.
7035 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7036 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00007037 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00007038 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00007039 }
7040 }
7041
Richard Smithd62306a2011-11-10 06:34:14 +00007042 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00007043 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007044}
7045
Peter Collingbournee9200682011-05-13 03:29:01 +00007046bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007047 // FIXME: Deal with vectors as array subscript bases.
7048 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007049 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007050
Nick Lewyckyad888682017-04-27 07:27:36 +00007051 bool Success = true;
7052 if (!evaluatePointer(E->getBase(), Result)) {
7053 if (!Info.noteFailure())
7054 return false;
7055 Success = false;
7056 }
Mike Stump11289f42009-09-09 15:08:12 +00007057
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007058 APSInt Index;
7059 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00007060 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007061
Nick Lewyckyad888682017-04-27 07:27:36 +00007062 return Success &&
7063 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007064}
Eli Friedman9a156e52008-11-12 09:44:48 +00007065
Peter Collingbournee9200682011-05-13 03:29:01 +00007066bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007067 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00007068}
7069
Richard Smith66c96992012-02-18 22:04:06 +00007070bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7071 if (!Visit(E->getSubExpr()))
7072 return false;
7073 // __real is a no-op on scalar lvalues.
7074 if (E->getSubExpr()->getType()->isAnyComplexType())
7075 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7076 return true;
7077}
7078
7079bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7080 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7081 "lvalue __imag__ on scalar?");
7082 if (!Visit(E->getSubExpr()))
7083 return false;
7084 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7085 return true;
7086}
7087
Richard Smith243ef902013-05-05 23:31:59 +00007088bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007089 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007090 return Error(UO);
7091
7092 if (!this->Visit(UO->getSubExpr()))
7093 return false;
7094
Richard Smith243ef902013-05-05 23:31:59 +00007095 return handleIncDec(
7096 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00007097 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00007098}
7099
7100bool LValueExprEvaluator::VisitCompoundAssignOperator(
7101 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007102 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007103 return Error(CAO);
7104
Richard Smith3229b742013-05-05 21:17:10 +00007105 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00007106
7107 // The overall lvalue result is the result of evaluating the LHS.
7108 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007109 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007110 Evaluate(RHS, this->Info, CAO->getRHS());
7111 return false;
7112 }
7113
Richard Smith3229b742013-05-05 21:17:10 +00007114 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7115 return false;
7116
Richard Smith43e77732013-05-07 04:50:00 +00007117 return handleCompoundAssignment(
7118 this->Info, CAO,
7119 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7120 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00007121}
7122
7123bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007124 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007125 return Error(E);
7126
Richard Smith3229b742013-05-05 21:17:10 +00007127 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00007128
7129 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007130 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007131 Evaluate(NewVal, this->Info, E->getRHS());
7132 return false;
7133 }
7134
Richard Smith3229b742013-05-05 21:17:10 +00007135 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7136 return false;
Richard Smith243ef902013-05-05 23:31:59 +00007137
Richard Smith31c69a32019-05-21 23:15:20 +00007138 if (Info.getLangOpts().CPlusPlus2a &&
7139 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7140 return false;
7141
Richard Smith243ef902013-05-05 23:31:59 +00007142 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00007143 NewVal);
7144}
7145
Eli Friedman9a156e52008-11-12 09:44:48 +00007146//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007147// Pointer Evaluation
7148//===----------------------------------------------------------------------===//
7149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007150/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00007151/// returned by a function with the alloc_size attribute. Returns true if we
7152/// were successful. Places an unsigned number into `Result`.
7153///
7154/// This expects the given CallExpr to be a call to a function with an
7155/// alloc_size attribute.
7156static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7157 const CallExpr *Call,
7158 llvm::APInt &Result) {
7159 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7160
Joel E. Denny81508102018-03-13 14:51:22 +00007161 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7162 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007163 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7164 if (Call->getNumArgs() <= SizeArgNo)
7165 return false;
7166
7167 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00007168 Expr::EvalResult ExprResult;
7169 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00007170 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007171 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00007172 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7173 return false;
7174 Into = Into.zextOrSelf(BitsInSizeT);
7175 return true;
7176 };
7177
7178 APSInt SizeOfElem;
7179 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7180 return false;
7181
Joel E. Denny81508102018-03-13 14:51:22 +00007182 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007183 Result = std::move(SizeOfElem);
7184 return true;
7185 }
7186
7187 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00007188 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007189 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7190 return false;
7191
7192 bool Overflow;
7193 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7194 if (Overflow)
7195 return false;
7196
7197 Result = std::move(BytesAvailable);
7198 return true;
7199}
7200
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007201/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00007202/// function.
7203static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7204 const LValue &LVal,
7205 llvm::APInt &Result) {
7206 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7207 "Can't get the size of a non alloc_size function");
7208 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7209 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7210 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7211}
7212
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007213/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00007214/// a function with the alloc_size attribute. If it was possible to do so, this
7215/// function will return true, make Result's Base point to said function call,
7216/// and mark Result's Base as invalid.
7217static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7218 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007219 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00007220 return false;
7221
7222 // Because we do no form of static analysis, we only support const variables.
7223 //
7224 // Additionally, we can't support parameters, nor can we support static
7225 // variables (in the latter case, use-before-assign isn't UB; in the former,
7226 // we have no clue what they'll be assigned to).
7227 const auto *VD =
7228 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7229 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7230 return false;
7231
7232 const Expr *Init = VD->getAnyInitializer();
7233 if (!Init)
7234 return false;
7235
7236 const Expr *E = Init->IgnoreParens();
7237 if (!tryUnwrapAllocSizeCall(E))
7238 return false;
7239
7240 // Store E instead of E unwrapped so that the type of the LValue's base is
7241 // what the user wanted.
7242 Result.setInvalid(E);
7243
7244 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007245 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007246 return true;
7247}
7248
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007249namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007250class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007251 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007252 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007253 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007254
Peter Collingbournee9200682011-05-13 03:29:01 +00007255 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007256 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007257 return true;
7258 }
George Burgess IVe3763372016-12-22 02:50:20 +00007259
George Burgess IVf9013bf2017-02-10 22:52:29 +00007260 bool evaluateLValue(const Expr *E, LValue &Result) {
7261 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7262 }
7263
7264 bool evaluatePointer(const Expr *E, LValue &Result) {
7265 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7266 }
7267
George Burgess IVe3763372016-12-22 02:50:20 +00007268 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007269public:
Mike Stump11289f42009-09-09 15:08:12 +00007270
George Burgess IVf9013bf2017-02-10 22:52:29 +00007271 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7272 : ExprEvaluatorBaseTy(info), Result(Result),
7273 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007274
Richard Smith2e312c82012-03-03 22:46:17 +00007275 bool Success(const APValue &V, const Expr *E) {
7276 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007277 return true;
7278 }
Richard Smithfddd3842011-12-30 21:15:51 +00007279 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00007280 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7281 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00007282 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007283 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007284
John McCall45d55e42010-05-07 21:00:08 +00007285 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007286 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007287 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007288 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007289 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007290 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007291 if (E->isExpressibleAsConstantInitializer())
7292 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007293 if (Info.noteFailure())
7294 EvaluateIgnoredValue(Info, E->getSubExpr());
7295 return Error(E);
7296 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007297 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007298 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007299 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007300 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007301 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007302 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007303 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007304 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007305 }
Richard Smithd62306a2011-11-10 06:34:14 +00007306 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007307 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007308 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007309 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007310 if (!Info.CurrentCall->This) {
7311 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007312 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007313 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007314 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007315 return false;
7316 }
Richard Smithd62306a2011-11-10 06:34:14 +00007317 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007318 // If we are inside a lambda's call operator, the 'this' expression refers
7319 // to the enclosing '*this' object (either by value or reference) which is
7320 // either copied into the closure object's field that represents the '*this'
7321 // or refers to '*this'.
7322 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7323 // Update 'Result' to refer to the data member/field of the closure object
7324 // that represents the '*this' capture.
7325 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007326 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007327 return false;
7328 // If we captured '*this' by reference, replace the field with its referent.
7329 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7330 ->isPointerType()) {
7331 APValue RVal;
7332 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7333 RVal))
7334 return false;
7335
7336 Result.setFrom(Info.Ctx, RVal);
7337 }
7338 }
Richard Smithd62306a2011-11-10 06:34:14 +00007339 return true;
7340 }
John McCallc07a0c72011-02-17 10:25:35 +00007341
Eric Fiselier708afb52019-05-16 21:04:15 +00007342 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7343 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7344 APValue LValResult = E->EvaluateInContext(
7345 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7346 Result.setFrom(Info.Ctx, LValResult);
7347 return true;
7348 }
7349
Eli Friedman449fe542009-03-23 04:56:01 +00007350 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007351};
Chris Lattner05706e882008-07-11 18:11:29 +00007352} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007353
George Burgess IVf9013bf2017-02-10 22:52:29 +00007354static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7355 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007356 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007357 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007358}
7359
John McCall45d55e42010-05-07 21:00:08 +00007360bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007361 if (E->getOpcode() != BO_Add &&
7362 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007363 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007364
Chris Lattner05706e882008-07-11 18:11:29 +00007365 const Expr *PExp = E->getLHS();
7366 const Expr *IExp = E->getRHS();
7367 if (IExp->getType()->isPointerType())
7368 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007369
George Burgess IVf9013bf2017-02-10 22:52:29 +00007370 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007371 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007372 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007373
John McCall45d55e42010-05-07 21:00:08 +00007374 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007375 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007376 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007377
Richard Smith96e0c102011-11-04 02:25:55 +00007378 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007379 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007380
Ted Kremenek28831752012-08-23 20:46:57 +00007381 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007382 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007383}
Eli Friedman9a156e52008-11-12 09:44:48 +00007384
John McCall45d55e42010-05-07 21:00:08 +00007385bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007386 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007387}
Mike Stump11289f42009-09-09 15:08:12 +00007388
Richard Smith81dfef92018-07-11 00:29:05 +00007389bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7390 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007391
Eli Friedman847a2bc2009-12-27 05:43:15 +00007392 switch (E->getCastKind()) {
7393 default:
7394 break;
John McCalle3027922010-08-25 11:45:40 +00007395 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007396 case CK_CPointerToObjCPointerCast:
7397 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007398 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007399 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007400 if (!Visit(SubExpr))
7401 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007402 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7403 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7404 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007405 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00007406 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00007407 if (SubExpr->getType()->isVoidPointerType())
7408 CCEDiag(E, diag::note_constexpr_invalid_cast)
7409 << 3 << SubExpr->getType();
7410 else
7411 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7412 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007413 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7414 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007415 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007416
Anders Carlsson18275092010-10-31 20:41:46 +00007417 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007418 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007419 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007420 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007421 if (!Result.Base && Result.Offset.isZero())
7422 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007423
Richard Smithd62306a2011-11-10 06:34:14 +00007424 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007425 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007426 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7427 castAs<PointerType>()->getPointeeType(),
7428 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007429
Richard Smith027bf112011-11-17 22:56:20 +00007430 case CK_BaseToDerived:
7431 if (!Visit(E->getSubExpr()))
7432 return false;
7433 if (!Result.Base && Result.Offset.isZero())
7434 return true;
7435 return HandleBaseToDerivedCast(Info, E, Result);
7436
Richard Smith7bd54ab2019-05-15 20:22:21 +00007437 case CK_Dynamic:
7438 if (!Visit(E->getSubExpr()))
7439 return false;
7440 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7441
Richard Smith0b0a0b62011-10-29 20:57:55 +00007442 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007443 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007444 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007445
John McCalle3027922010-08-25 11:45:40 +00007446 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007447 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7448
Richard Smith2e312c82012-03-03 22:46:17 +00007449 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007450 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007451 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007452
John McCall45d55e42010-05-07 21:00:08 +00007453 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007454 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7455 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007456 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007457 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007458 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007459 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007460 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007461 return true;
7462 } else {
7463 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007464 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007465 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007466 }
7467 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007468
7469 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007470 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007471 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007472 return false;
7473 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007474 APValue &Value = Info.CurrentCall->createTemporary(
7475 SubExpr, SubExpr->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007476 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007477 return false;
7478 }
Richard Smith96e0c102011-11-04 02:25:55 +00007479 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00007480 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7481 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00007482 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00007483 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00007484 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00007485 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00007486 }
Richard Smithdd785442011-10-31 20:57:44 +00007487
John McCalle3027922010-08-25 11:45:40 +00007488 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007489 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007490
7491 case CK_LValueToRValue: {
7492 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007493 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00007494 return false;
7495
7496 APValue RVal;
7497 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7498 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7499 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00007500 return InvalidBaseOK &&
7501 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007502 return Success(RVal, E);
7503 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007504 }
7505
Richard Smith11562c52011-10-28 17:51:58 +00007506 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00007507}
Chris Lattner05706e882008-07-11 18:11:29 +00007508
Richard Smith6822bd72018-10-26 19:26:45 +00007509static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7510 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007511 // C++ [expr.alignof]p3:
7512 // When alignof is applied to a reference type, the result is the
7513 // alignment of the referenced type.
7514 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7515 T = Ref->getPointeeType();
7516
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00007517 if (T.getQualifiers().hasUnaligned())
7518 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00007519
7520 const bool AlignOfReturnsPreferred =
7521 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7522
7523 // __alignof is defined to return the preferred alignment.
7524 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7525 // as well.
7526 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7527 return Info.Ctx.toCharUnitsFromBits(
7528 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7529 // alignof and _Alignof are defined to return the ABI alignment.
7530 else if (ExprKind == UETT_AlignOf)
7531 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7532 else
7533 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00007534}
7535
Richard Smith6822bd72018-10-26 19:26:45 +00007536static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7537 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007538 E = E->IgnoreParens();
7539
7540 // The kinds of expressions that we have special-case logic here for
7541 // should be kept up to date with the special checks for those
7542 // expressions in Sema.
7543
7544 // alignof decl is always accepted, even if it doesn't make sense: we default
7545 // to 1 in those cases.
7546 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7547 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7548 /*RefAsPointee*/true);
7549
7550 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7551 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7552 /*RefAsPointee*/true);
7553
Richard Smith6822bd72018-10-26 19:26:45 +00007554 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007555}
7556
George Burgess IVe3763372016-12-22 02:50:20 +00007557// To be clear: this happily visits unsupported builtins. Better name welcomed.
7558bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7559 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7560 return true;
7561
George Burgess IVf9013bf2017-02-10 22:52:29 +00007562 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00007563 return false;
7564
7565 Result.setInvalid(E);
7566 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007567 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00007568 return true;
7569}
7570
Peter Collingbournee9200682011-05-13 03:29:01 +00007571bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007572 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00007573 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00007574
Richard Smith6328cbd2016-11-16 00:57:23 +00007575 if (unsigned BuiltinOp = E->getBuiltinCallee())
7576 return VisitBuiltinCallExpr(E, BuiltinOp);
7577
George Burgess IVe3763372016-12-22 02:50:20 +00007578 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007579}
7580
7581bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7582 unsigned BuiltinOp) {
7583 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00007584 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007585 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007586 case Builtin::BI__builtin_assume_aligned: {
7587 // We need to be very careful here because: if the pointer does not have the
7588 // asserted alignment, then the behavior is undefined, and undefined
7589 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00007590 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00007591 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00007592
Hal Finkel0dd05d42014-10-03 17:18:37 +00007593 LValue OffsetResult(Result);
7594 APSInt Alignment;
7595 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7596 return false;
Richard Smith642a2362017-01-30 23:30:26 +00007597 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00007598
7599 if (E->getNumArgs() > 2) {
7600 APSInt Offset;
7601 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7602 return false;
7603
Richard Smith642a2362017-01-30 23:30:26 +00007604 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007605 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7606 }
7607
7608 // If there is a base object, then it must have the correct alignment.
7609 if (OffsetResult.Base) {
7610 CharUnits BaseAlignment;
7611 if (const ValueDecl *VD =
7612 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7613 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00007614 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7615 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007616 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00007617 BaseAlignment = GetAlignOfType(
7618 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007619 }
7620
7621 if (BaseAlignment < Align) {
7622 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00007623 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00007624 CCEDiag(E->getArg(0),
7625 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00007626 << (unsigned)BaseAlignment.getQuantity()
7627 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007628 return false;
7629 }
7630 }
7631
7632 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007633 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007634 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007635
Richard Smith642a2362017-01-30 23:30:26 +00007636 (OffsetResult.Base
7637 ? CCEDiag(E->getArg(0),
7638 diag::note_constexpr_baa_insufficient_alignment) << 1
7639 : CCEDiag(E->getArg(0),
7640 diag::note_constexpr_baa_value_insufficient_alignment))
7641 << (int)OffsetResult.Offset.getQuantity()
7642 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007643 return false;
7644 }
7645
7646 return true;
7647 }
Eric Fiselier26187502018-12-14 21:11:28 +00007648 case Builtin::BI__builtin_launder:
7649 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00007650 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007651 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00007652 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007653 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00007654 if (Info.getLangOpts().CPlusPlus11)
7655 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7656 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007657 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00007658 else
7659 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007660 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00007661 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007662 case Builtin::BI__builtin_wcschr:
7663 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007664 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007665 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00007666 if (!Visit(E->getArg(0)))
7667 return false;
7668 APSInt Desired;
7669 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7670 return false;
7671 uint64_t MaxLength = uint64_t(-1);
7672 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007673 BuiltinOp != Builtin::BIwcschr &&
7674 BuiltinOp != Builtin::BI__builtin_strchr &&
7675 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00007676 APSInt N;
7677 if (!EvaluateInteger(E->getArg(2), N, Info))
7678 return false;
7679 MaxLength = N.getExtValue();
7680 }
Hubert Tong147b7432018-12-12 16:53:43 +00007681 // We cannot find the value if there are no candidates to match against.
7682 if (MaxLength == 0u)
7683 return ZeroInitialization(E);
7684 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7685 Result.Designator.Invalid)
7686 return false;
7687 QualType CharTy = Result.Designator.getType(Info.Ctx);
7688 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7689 BuiltinOp == Builtin::BI__builtin_memchr;
7690 assert(IsRawByte ||
7691 Info.Ctx.hasSameUnqualifiedType(
7692 CharTy, E->getArg(0)->getType()->getPointeeType()));
7693 // Pointers to const void may point to objects of incomplete type.
7694 if (IsRawByte && CharTy->isIncompleteType()) {
7695 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7696 return false;
7697 }
7698 // Give up on byte-oriented matching against multibyte elements.
7699 // FIXME: We can compare the bytes in the correct order.
7700 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7701 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007702 // Figure out what value we're actually looking for (after converting to
7703 // the corresponding unsigned type if necessary).
7704 uint64_t DesiredVal;
7705 bool StopAtNull = false;
7706 switch (BuiltinOp) {
7707 case Builtin::BIstrchr:
7708 case Builtin::BI__builtin_strchr:
7709 // strchr compares directly to the passed integer, and therefore
7710 // always fails if given an int that is not a char.
7711 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7712 E->getArg(1)->getType(),
7713 Desired),
7714 Desired))
7715 return ZeroInitialization(E);
7716 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007717 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007718 case Builtin::BImemchr:
7719 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007720 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007721 // memchr compares by converting both sides to unsigned char. That's also
7722 // correct for strchr if we get this far (to cope with plain char being
7723 // unsigned in the strchr case).
7724 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7725 break;
Richard Smithe9507952016-11-12 01:39:56 +00007726
Richard Smith8110c9d2016-11-29 19:45:17 +00007727 case Builtin::BIwcschr:
7728 case Builtin::BI__builtin_wcschr:
7729 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007730 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007731 case Builtin::BIwmemchr:
7732 case Builtin::BI__builtin_wmemchr:
7733 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7734 DesiredVal = Desired.getZExtValue();
7735 break;
7736 }
Richard Smithe9507952016-11-12 01:39:56 +00007737
7738 for (; MaxLength; --MaxLength) {
7739 APValue Char;
7740 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7741 !Char.isInt())
7742 return false;
7743 if (Char.getInt().getZExtValue() == DesiredVal)
7744 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007745 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007746 break;
7747 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7748 return false;
7749 }
7750 // Not found: return nullptr.
7751 return ZeroInitialization(E);
7752 }
7753
Richard Smith06f71b52018-08-04 00:57:17 +00007754 case Builtin::BImemcpy:
7755 case Builtin::BImemmove:
7756 case Builtin::BIwmemcpy:
7757 case Builtin::BIwmemmove:
7758 if (Info.getLangOpts().CPlusPlus11)
7759 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7760 << /*isConstexpr*/0 << /*isConstructor*/0
7761 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7762 else
7763 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7764 LLVM_FALLTHROUGH;
7765 case Builtin::BI__builtin_memcpy:
7766 case Builtin::BI__builtin_memmove:
7767 case Builtin::BI__builtin_wmemcpy:
7768 case Builtin::BI__builtin_wmemmove: {
7769 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7770 BuiltinOp == Builtin::BIwmemmove ||
7771 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7772 BuiltinOp == Builtin::BI__builtin_wmemmove;
7773 bool Move = BuiltinOp == Builtin::BImemmove ||
7774 BuiltinOp == Builtin::BIwmemmove ||
7775 BuiltinOp == Builtin::BI__builtin_memmove ||
7776 BuiltinOp == Builtin::BI__builtin_wmemmove;
7777
7778 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007779 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007780 return false;
7781 LValue Dest = Result;
7782
7783 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007784 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007785 return false;
7786
7787 APSInt N;
7788 if (!EvaluateInteger(E->getArg(2), N, Info))
7789 return false;
7790 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7791
7792 // If the size is zero, we treat this as always being a valid no-op.
7793 // (Even if one of the src and dest pointers is null.)
7794 if (!N)
7795 return true;
7796
Richard Smith128719c2018-09-13 22:47:33 +00007797 // Otherwise, if either of the operands is null, we can't proceed. Don't
7798 // try to determine the type of the copied objects, because there aren't
7799 // any.
7800 if (!Src.Base || !Dest.Base) {
7801 APValue Val;
7802 (!Src.Base ? Src : Dest).moveInto(Val);
7803 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7804 << Move << WChar << !!Src.Base
7805 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7806 return false;
7807 }
7808 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7809 return false;
7810
Richard Smith06f71b52018-08-04 00:57:17 +00007811 // We require that Src and Dest are both pointers to arrays of
7812 // trivially-copyable type. (For the wide version, the designator will be
7813 // invalid if the designated object is not a wchar_t.)
7814 QualType T = Dest.Designator.getType(Info.Ctx);
7815 QualType SrcT = Src.Designator.getType(Info.Ctx);
7816 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7817 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7818 return false;
7819 }
Petr Pavlued083f22018-10-04 09:25:44 +00007820 if (T->isIncompleteType()) {
7821 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7822 return false;
7823 }
Richard Smith06f71b52018-08-04 00:57:17 +00007824 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7825 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7826 return false;
7827 }
7828
7829 // Figure out how many T's we're copying.
7830 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7831 if (!WChar) {
7832 uint64_t Remainder;
7833 llvm::APInt OrigN = N;
7834 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7835 if (Remainder) {
7836 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7837 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7838 << (unsigned)TSize;
7839 return false;
7840 }
7841 }
7842
7843 // Check that the copying will remain within the arrays, just so that we
7844 // can give a more meaningful diagnostic. This implicitly also checks that
7845 // N fits into 64 bits.
7846 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7847 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7848 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7849 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7850 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7851 << N.toString(10, /*Signed*/false);
7852 return false;
7853 }
7854 uint64_t NElems = N.getZExtValue();
7855 uint64_t NBytes = NElems * TSize;
7856
7857 // Check for overlap.
7858 int Direction = 1;
7859 if (HasSameBase(Src, Dest)) {
7860 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7861 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7862 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7863 // Dest is inside the source region.
7864 if (!Move) {
7865 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7866 return false;
7867 }
7868 // For memmove and friends, copy backwards.
7869 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7870 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7871 return false;
7872 Direction = -1;
7873 } else if (!Move && SrcOffset >= DestOffset &&
7874 SrcOffset - DestOffset < NBytes) {
7875 // Src is inside the destination region for memcpy: invalid.
7876 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7877 return false;
7878 }
7879 }
7880
7881 while (true) {
7882 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00007883 // FIXME: Set WantObjectRepresentation to true if we're copying a
7884 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00007885 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7886 !handleAssignment(Info, E, Dest, T, Val))
7887 return false;
7888 // Do not iterate past the last element; if we're copying backwards, that
7889 // might take us off the start of the array.
7890 if (--NElems == 0)
7891 return true;
7892 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7893 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7894 return false;
7895 }
7896 }
7897
Richard Smith6cbd65d2013-07-11 02:27:57 +00007898 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007899 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007900 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007901}
Chris Lattner05706e882008-07-11 18:11:29 +00007902
7903//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007904// Member Pointer Evaluation
7905//===----------------------------------------------------------------------===//
7906
7907namespace {
7908class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007909 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007910 MemberPtr &Result;
7911
7912 bool Success(const ValueDecl *D) {
7913 Result = MemberPtr(D);
7914 return true;
7915 }
7916public:
7917
7918 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7919 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7920
Richard Smith2e312c82012-03-03 22:46:17 +00007921 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007922 Result.setFrom(V);
7923 return true;
7924 }
Richard Smithfddd3842011-12-30 21:15:51 +00007925 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007926 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007927 }
7928
7929 bool VisitCastExpr(const CastExpr *E);
7930 bool VisitUnaryAddrOf(const UnaryOperator *E);
7931};
7932} // end anonymous namespace
7933
7934static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7935 EvalInfo &Info) {
7936 assert(E->isRValue() && E->getType()->isMemberPointerType());
7937 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7938}
7939
7940bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7941 switch (E->getCastKind()) {
7942 default:
7943 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7944
7945 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007946 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007947 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007948
7949 case CK_BaseToDerivedMemberPointer: {
7950 if (!Visit(E->getSubExpr()))
7951 return false;
7952 if (E->path_empty())
7953 return true;
7954 // Base-to-derived member pointer casts store the path in derived-to-base
7955 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7956 // the wrong end of the derived->base arc, so stagger the path by one class.
7957 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7958 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7959 PathI != PathE; ++PathI) {
7960 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7961 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7962 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007963 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007964 }
7965 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7966 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007967 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007968 return true;
7969 }
7970
7971 case CK_DerivedToBaseMemberPointer:
7972 if (!Visit(E->getSubExpr()))
7973 return false;
7974 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7975 PathE = E->path_end(); PathI != PathE; ++PathI) {
7976 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7977 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7978 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007979 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007980 }
7981 return true;
7982 }
7983}
7984
7985bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7986 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7987 // member can be formed.
7988 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7989}
7990
7991//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007992// Record Evaluation
7993//===----------------------------------------------------------------------===//
7994
7995namespace {
7996 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007997 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007998 const LValue &This;
7999 APValue &Result;
8000 public:
8001
8002 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8003 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8004
Richard Smith2e312c82012-03-03 22:46:17 +00008005 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00008006 Result = V;
8007 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00008008 }
Richard Smithb8348f52016-05-12 22:16:28 +00008009 bool ZeroInitialization(const Expr *E) {
8010 return ZeroInitialization(E, E->getType());
8011 }
8012 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00008013
Richard Smith52a980a2015-08-28 02:43:42 +00008014 bool VisitCallExpr(const CallExpr *E) {
8015 return handleCallExpr(E, Result, &This);
8016 }
Richard Smithe97cbd72011-11-11 04:05:33 +00008017 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008018 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008019 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8020 return VisitCXXConstructExpr(E, E->getType());
8021 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008022 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00008023 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008024 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00008025 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008026
Richard Smith457226e2019-09-23 03:48:44 +00008027 // Temporaries are registered when created, so we don't care about
8028 // CXXBindTemporaryExpr.
8029 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8030 return Visit(E->getSubExpr());
8031 }
8032
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008033 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008034 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008035}
Richard Smithd62306a2011-11-10 06:34:14 +00008036
Richard Smithfddd3842011-12-30 21:15:51 +00008037/// Perform zero-initialization on an object of non-union class type.
8038/// C++11 [dcl.init]p5:
8039/// To zero-initialize an object or reference of type T means:
8040/// [...]
8041/// -- if T is a (possibly cv-qualified) non-union class type,
8042/// each non-static data member and each base-class subobject is
8043/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00008044static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8045 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00008046 const LValue &This, APValue &Result) {
8047 assert(!RD->isUnion() && "Expected non-union class type");
8048 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8049 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00008050 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00008051
John McCalld7bca762012-05-01 00:38:49 +00008052 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008053 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8054
8055 if (CD) {
8056 unsigned Index = 0;
8057 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00008058 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00008059 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8060 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008061 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8062 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00008063 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00008064 Result.getStructBase(Index)))
8065 return false;
8066 }
8067 }
8068
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008069 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00008070 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00008071 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00008072 continue;
8073
8074 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008075 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008076 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008077
David Blaikie2d7c57e2012-04-30 02:36:29 +00008078 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008079 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00008080 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00008081 return false;
8082 }
8083
8084 return true;
8085}
8086
Richard Smithb8348f52016-05-12 22:16:28 +00008087bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8088 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008089 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008090 if (RD->isUnion()) {
8091 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8092 // object's first non-static named data member is zero-initialized
8093 RecordDecl::field_iterator I = RD->field_begin();
8094 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00008095 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00008096 return true;
8097 }
8098
8099 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00008100 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00008101 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00008102 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00008103 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008104 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00008105 }
8106
Richard Smith5d108602012-02-17 00:44:16 +00008107 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008108 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00008109 return false;
8110 }
8111
Richard Smitha8105bc2012-01-06 16:39:00 +00008112 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00008113}
8114
Richard Smithe97cbd72011-11-11 04:05:33 +00008115bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8116 switch (E->getCastKind()) {
8117 default:
8118 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8119
8120 case CK_ConstructorConversion:
8121 return Visit(E->getSubExpr());
8122
8123 case CK_DerivedToBase:
8124 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00008125 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008126 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00008127 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008128 if (!DerivedObject.isStruct())
8129 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00008130
8131 // Derived-to-base rvalue conversion: just slice off the derived part.
8132 APValue *Value = &DerivedObject;
8133 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8134 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8135 PathE = E->path_end(); PathI != PathE; ++PathI) {
8136 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
8137 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8138 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8139 RD = Base;
8140 }
8141 Result = *Value;
8142 return true;
8143 }
8144 }
8145}
8146
Richard Smithd62306a2011-11-10 06:34:14 +00008147bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00008148 if (E->isTransparent())
8149 return Visit(E->getInit(0));
8150
Richard Smithd62306a2011-11-10 06:34:14 +00008151 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008152 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008153 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008154 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8155
8156 EvalInfo::EvaluatingConstructorRAII EvalObj(
8157 Info,
8158 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8159 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00008160
8161 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00008162 const FieldDecl *Field = E->getInitializedFieldInUnion();
8163 Result = APValue(Field);
8164 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00008165 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00008166
8167 // If the initializer list for a union does not contain any elements, the
8168 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00008169 // FIXME: The element should be initialized from an initializer list.
8170 // Is this difference ever observable for initializer lists which
8171 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00008172 ImplicitValueInitExpr VIE(Field->getType());
8173 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8174
Richard Smithd62306a2011-11-10 06:34:14 +00008175 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008176 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8177 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00008178
8179 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8180 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8181 isa<CXXDefaultInitExpr>(InitExpr));
8182
Richard Smithb228a862012-02-15 02:18:13 +00008183 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00008184 }
8185
Richard Smithe637cbe2019-05-21 23:15:18 +00008186 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00008187 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8188 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00008189 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00008190 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00008191
8192 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008193 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00008194 for (const auto &Base : CXXRD->bases()) {
8195 assert(ElementNo < E->getNumInits() && "missing init for base class");
8196 const Expr *Init = E->getInit(ElementNo);
8197
8198 LValue Subobject = This;
8199 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8200 return false;
8201
8202 APValue &FieldVal = Result.getStructBase(ElementNo);
8203 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008204 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00008205 return false;
8206 Success = false;
8207 }
8208 ++ElementNo;
8209 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008210
8211 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00008212 }
8213
8214 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008215 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008216 // Anonymous bit-fields are not considered members of the class for
8217 // purposes of aggregate initialization.
8218 if (Field->isUnnamedBitfield())
8219 continue;
8220
8221 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00008222
Richard Smith253c2a32012-01-27 01:14:48 +00008223 bool HaveInit = ElementNo < E->getNumInits();
8224
8225 // FIXME: Diagnostics here should point to the end of the initializer
8226 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00008227 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008228 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008229 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008230
8231 // Perform an implicit value-initialization for members beyond the end of
8232 // the initializer list.
8233 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00008234 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00008235
Richard Smith852c9db2013-04-20 22:23:05 +00008236 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8237 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8238 isa<CXXDefaultInitExpr>(Init));
8239
Richard Smith49ca8aa2013-08-06 07:09:20 +00008240 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8241 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8242 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008243 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00008244 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00008245 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008246 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00008247 }
8248 }
8249
Richard Smith253c2a32012-01-27 01:14:48 +00008250 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00008251}
8252
Richard Smithb8348f52016-05-12 22:16:28 +00008253bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8254 QualType T) {
8255 // Note that E's type is not necessarily the type of our class here; we might
8256 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00008257 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00008258 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8259
Richard Smithfddd3842011-12-30 21:15:51 +00008260 bool ZeroInit = E->requiresZeroInitialization();
8261 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00008262 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00008263 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00008264 return true;
8265
Richard Smithc667cdc2019-09-18 17:37:44 +00008266 if (ZeroInit)
8267 return ZeroInitialization(E, T);
8268
8269 Result = getDefaultInitValue(T);
8270 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00008271 }
8272
Craig Topper36250ad2014-05-12 05:36:57 +00008273 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008274 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00008275
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008276 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00008277 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008278
Richard Smith1bc5c2c2012-01-10 04:32:03 +00008279 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00008280 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00008281 if (const MaterializeTemporaryExpr *ME
8282 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8283 return Visit(ME->GetTemporaryExpr());
8284
Richard Smithb8348f52016-05-12 22:16:28 +00008285 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00008286 return false;
8287
Craig Topper5fc8fc22014-08-27 06:28:36 +00008288 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00008289 return HandleConstructorCall(E, This, Args,
8290 cast<CXXConstructorDecl>(Definition), Info,
8291 Result);
8292}
8293
8294bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8295 const CXXInheritedCtorInitExpr *E) {
8296 if (!Info.CurrentCall) {
8297 assert(Info.checkingPotentialConstantExpression());
8298 return false;
8299 }
8300
8301 const CXXConstructorDecl *FD = E->getConstructor();
8302 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8303 return false;
8304
8305 const FunctionDecl *Definition = nullptr;
8306 auto Body = FD->getBody(Definition);
8307
8308 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8309 return false;
8310
8311 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008312 cast<CXXConstructorDecl>(Definition), Info,
8313 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00008314}
8315
Richard Smithcc1b96d2013-06-12 22:31:48 +00008316bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8317 const CXXStdInitializerListExpr *E) {
8318 const ConstantArrayType *ArrayType =
8319 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8320
8321 LValue Array;
8322 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8323 return false;
8324
8325 // Get a pointer to the first element of the array.
8326 Array.addArray(Info, E, ArrayType);
8327
8328 // FIXME: Perform the checks on the field types in SemaInit.
8329 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8330 RecordDecl::field_iterator Field = Record->field_begin();
8331 if (Field == Record->field_end())
8332 return Error(E);
8333
8334 // Start pointer.
8335 if (!Field->getType()->isPointerType() ||
8336 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8337 ArrayType->getElementType()))
8338 return Error(E);
8339
8340 // FIXME: What if the initializer_list type has base classes, etc?
8341 Result = APValue(APValue::UninitStruct(), 0, 2);
8342 Array.moveInto(Result.getStructField(0));
8343
8344 if (++Field == Record->field_end())
8345 return Error(E);
8346
8347 if (Field->getType()->isPointerType() &&
8348 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8349 ArrayType->getElementType())) {
8350 // End pointer.
8351 if (!HandleLValueArrayAdjustment(Info, E, Array,
8352 ArrayType->getElementType(),
8353 ArrayType->getSize().getZExtValue()))
8354 return false;
8355 Array.moveInto(Result.getStructField(1));
8356 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8357 // Length.
8358 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8359 else
8360 return Error(E);
8361
8362 if (++Field != Record->field_end())
8363 return Error(E);
8364
8365 return true;
8366}
8367
Faisal Valic72a08c2017-01-09 03:02:53 +00008368bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8369 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8370 if (ClosureClass->isInvalidDecl()) return false;
8371
8372 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008373
Faisal Vali051e3a22017-02-16 04:12:21 +00008374 const size_t NumFields =
8375 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00008376
8377 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8378 E->capture_init_end()) &&
8379 "The number of lambda capture initializers should equal the number of "
8380 "fields within the closure type");
8381
Faisal Vali051e3a22017-02-16 04:12:21 +00008382 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8383 // Iterate through all the lambda's closure object's fields and initialize
8384 // them.
8385 auto *CaptureInitIt = E->capture_init_begin();
8386 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8387 bool Success = true;
8388 for (const auto *Field : ClosureClass->fields()) {
8389 assert(CaptureInitIt != E->capture_init_end());
8390 // Get the initializer for this field
8391 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00008392
Faisal Vali051e3a22017-02-16 04:12:21 +00008393 // If there is no initializer, either this is a VLA or an error has
8394 // occurred.
8395 if (!CurFieldInit)
8396 return Error(E);
8397
8398 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8399 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8400 if (!Info.keepEvaluatingAfterFailure())
8401 return false;
8402 Success = false;
8403 }
8404 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00008405 }
Faisal Vali051e3a22017-02-16 04:12:21 +00008406 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00008407}
8408
Richard Smithd62306a2011-11-10 06:34:14 +00008409static bool EvaluateRecord(const Expr *E, const LValue &This,
8410 APValue &Result, EvalInfo &Info) {
8411 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00008412 "can't evaluate expression as a record rvalue");
8413 return RecordExprEvaluator(Info, This, Result).Visit(E);
8414}
8415
8416//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008417// Temporary Evaluation
8418//
8419// Temporaries are represented in the AST as rvalues, but generally behave like
8420// lvalues. The full-object of which the temporary is a subobject is implicitly
8421// materialized so that a reference can bind to it.
8422//===----------------------------------------------------------------------===//
8423namespace {
8424class TemporaryExprEvaluator
8425 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8426public:
8427 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00008428 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00008429
8430 /// Visit an expression which constructs the value of this temporary.
8431 bool VisitConstructExpr(const Expr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00008432 APValue &Value =
8433 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008434 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00008435 }
8436
8437 bool VisitCastExpr(const CastExpr *E) {
8438 switch (E->getCastKind()) {
8439 default:
8440 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8441
8442 case CK_ConstructorConversion:
8443 return VisitConstructExpr(E->getSubExpr());
8444 }
8445 }
8446 bool VisitInitListExpr(const InitListExpr *E) {
8447 return VisitConstructExpr(E);
8448 }
8449 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8450 return VisitConstructExpr(E);
8451 }
8452 bool VisitCallExpr(const CallExpr *E) {
8453 return VisitConstructExpr(E);
8454 }
Richard Smith513955c2014-12-17 19:24:30 +00008455 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8456 return VisitConstructExpr(E);
8457 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008458 bool VisitLambdaExpr(const LambdaExpr *E) {
8459 return VisitConstructExpr(E);
8460 }
Richard Smith027bf112011-11-17 22:56:20 +00008461};
8462} // end anonymous namespace
8463
8464/// Evaluate an expression of record type as a temporary.
8465static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00008466 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00008467 return TemporaryExprEvaluator(Info, Result).Visit(E);
8468}
8469
8470//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008471// Vector Evaluation
8472//===----------------------------------------------------------------------===//
8473
8474namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008475 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008476 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00008477 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008478 public:
Mike Stump11289f42009-09-09 15:08:12 +00008479
Richard Smith2d406342011-10-22 21:10:00 +00008480 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8481 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00008482
Craig Topper9798b932015-09-29 04:30:05 +00008483 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008484 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8485 // FIXME: remove this APValue copy.
8486 Result = APValue(V.data(), V.size());
8487 return true;
8488 }
Richard Smith2e312c82012-03-03 22:46:17 +00008489 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00008490 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00008491 Result = V;
8492 return true;
8493 }
Richard Smithfddd3842011-12-30 21:15:51 +00008494 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00008495
Richard Smith2d406342011-10-22 21:10:00 +00008496 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00008497 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00008498 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00008499 bool VisitInitListExpr(const InitListExpr *E);
8500 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008501 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00008502 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00008503 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008504 };
8505} // end anonymous namespace
8506
8507static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008508 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00008509 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008510}
8511
George Burgess IV533ff002015-12-11 00:23:35 +00008512bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008513 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008514 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008515
Richard Smith161f09a2011-12-06 22:44:34 +00008516 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00008517 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008518
Eli Friedmanc757de22011-03-25 00:43:55 +00008519 switch (E->getCastKind()) {
8520 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00008521 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00008522 if (SETy->isIntegerType()) {
8523 APSInt IntResult;
8524 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00008525 return false;
8526 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008527 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00008528 APFloat FloatResult(0.0);
8529 if (!EvaluateFloat(SE, FloatResult, Info))
8530 return false;
8531 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008532 } else {
Richard Smith2d406342011-10-22 21:10:00 +00008533 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008534 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008535
8536 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00008537 SmallVector<APValue, 4> Elts(NElts, Val);
8538 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00008539 }
Eli Friedman803acb32011-12-22 03:51:45 +00008540 case CK_BitCast: {
8541 // Evaluate the operand into an APInt we can extract from.
8542 llvm::APInt SValInt;
8543 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8544 return false;
8545 // Extract the elements
8546 QualType EltTy = VTy->getElementType();
8547 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8548 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8549 SmallVector<APValue, 4> Elts;
8550 if (EltTy->isRealFloatingType()) {
8551 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00008552 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00008553 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00008554 FloatEltSize = 80;
8555 for (unsigned i = 0; i < NElts; i++) {
8556 llvm::APInt Elt;
8557 if (BigEndian)
8558 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8559 else
8560 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00008561 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00008562 }
8563 } else if (EltTy->isIntegerType()) {
8564 for (unsigned i = 0; i < NElts; i++) {
8565 llvm::APInt Elt;
8566 if (BigEndian)
8567 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8568 else
8569 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8570 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8571 }
8572 } else {
8573 return Error(E);
8574 }
8575 return Success(Elts, E);
8576 }
Eli Friedmanc757de22011-03-25 00:43:55 +00008577 default:
Richard Smith11562c52011-10-28 17:51:58 +00008578 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008579 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008580}
8581
Richard Smith2d406342011-10-22 21:10:00 +00008582bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008583VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008584 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008585 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00008586 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008587
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008588 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008589 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008590
Eli Friedmanb9c71292012-01-03 23:24:20 +00008591 // The number of initializers can be less than the number of
8592 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00008593 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00008594 // should be initialized with zeroes.
8595 unsigned CountInits = 0, CountElts = 0;
8596 while (CountElts < NumElements) {
8597 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00008598 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00008599 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00008600 APValue v;
8601 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8602 return Error(E);
8603 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00008604 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00008605 Elements.push_back(v.getVectorElt(j));
8606 CountElts += vlen;
8607 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008608 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008609 if (CountInits < NumInits) {
8610 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008611 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008612 } else // trailing integer zero.
8613 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8614 Elements.push_back(APValue(sInt));
8615 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008616 } else {
8617 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008618 if (CountInits < NumInits) {
8619 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008620 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008621 } else // trailing float zero.
8622 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8623 Elements.push_back(APValue(f));
8624 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00008625 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00008626 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008627 }
Richard Smith2d406342011-10-22 21:10:00 +00008628 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008629}
8630
Richard Smith2d406342011-10-22 21:10:00 +00008631bool
Richard Smithfddd3842011-12-30 21:15:51 +00008632VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008633 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00008634 QualType EltTy = VT->getElementType();
8635 APValue ZeroElement;
8636 if (EltTy->isIntegerType())
8637 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8638 else
8639 ZeroElement =
8640 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8641
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008642 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00008643 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008644}
8645
Richard Smith2d406342011-10-22 21:10:00 +00008646bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00008647 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008648 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008649}
8650
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008651//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00008652// Array Evaluation
8653//===----------------------------------------------------------------------===//
8654
8655namespace {
8656 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008657 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008658 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00008659 APValue &Result;
8660 public:
8661
Richard Smithd62306a2011-11-10 06:34:14 +00008662 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8663 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00008664
8665 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00008666 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00008667 Result = V;
8668 return true;
8669 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008670
Richard Smithfddd3842011-12-30 21:15:51 +00008671 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008672 const ConstantArrayType *CAT =
8673 Info.Ctx.getAsConstantArrayType(E->getType());
8674 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008675 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008676
8677 Result = APValue(APValue::UninitArray(), 0,
8678 CAT->getSize().getZExtValue());
8679 if (!Result.hasArrayFiller()) return true;
8680
Richard Smithfddd3842011-12-30 21:15:51 +00008681 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00008682 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008683 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00008684 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00008685 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00008686 }
8687
Richard Smith52a980a2015-08-28 02:43:42 +00008688 bool VisitCallExpr(const CallExpr *E) {
8689 return handleCallExpr(E, Result, &This);
8690 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008691 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00008692 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00008693 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00008694 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8695 const LValue &Subobject,
8696 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00008697 bool VisitStringLiteral(const StringLiteral *E) {
8698 expandStringLiteral(Info, E, Result);
8699 return true;
8700 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008701 };
8702} // end anonymous namespace
8703
Richard Smithd62306a2011-11-10 06:34:14 +00008704static bool EvaluateArray(const Expr *E, const LValue &This,
8705 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00008706 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00008707 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008708}
8709
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008710// Return true iff the given array filler may depend on the element index.
8711static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8712 // For now, just whitelist non-class value-initialization and initialization
8713 // lists comprised of them.
8714 if (isa<ImplicitValueInitExpr>(FillerExpr))
8715 return false;
8716 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8717 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8718 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8719 return true;
8720 }
8721 return false;
8722 }
8723 return true;
8724}
8725
Richard Smithf3e9e432011-11-07 09:22:26 +00008726bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8727 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8728 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008729 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008730
Richard Smithca2cfbf2011-12-22 01:07:19 +00008731 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8732 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00008733 if (E->isStringLiteralInit())
8734 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00008735
Richard Smith253c2a32012-01-27 01:14:48 +00008736 bool Success = true;
8737
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008738 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8739 "zero-initialized array shouldn't have any initialized elts");
8740 APValue Filler;
8741 if (Result.isArray() && Result.hasArrayFiller())
8742 Filler = Result.getArrayFiller();
8743
Richard Smith9543c5e2013-04-22 14:44:29 +00008744 unsigned NumEltsToInit = E->getNumInits();
8745 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00008746 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008747
8748 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008749 // array element.
8750 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008751 NumEltsToInit = NumElts;
8752
Nicola Zaghen3538b392018-05-15 13:30:56 +00008753 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8754 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008755
Richard Smith9543c5e2013-04-22 14:44:29 +00008756 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008757
8758 // If the array was previously zero-initialized, preserve the
8759 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008760 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008761 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8762 Result.getArrayInitializedElt(I) = Filler;
8763 if (Result.hasArrayFiller())
8764 Result.getArrayFiller() = Filler;
8765 }
8766
Richard Smithd62306a2011-11-10 06:34:14 +00008767 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008768 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008769 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8770 const Expr *Init =
8771 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008772 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008773 Info, Subobject, Init) ||
8774 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008775 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008776 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008777 return false;
8778 Success = false;
8779 }
Richard Smithd62306a2011-11-10 06:34:14 +00008780 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008781
Richard Smith9543c5e2013-04-22 14:44:29 +00008782 if (!Result.hasArrayFiller())
8783 return Success;
8784
8785 // If we get here, we have a trivial filler, which we can just evaluate
8786 // once and splat over the rest of the array elements.
8787 assert(FillerExpr && "no array filler for incomplete init list");
8788 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8789 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008790}
8791
Richard Smith410306b2016-12-12 02:53:20 +00008792bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00008793 LValue CommonLV;
Richard Smith410306b2016-12-12 02:53:20 +00008794 if (E->getCommonExpr() &&
Richard Smith457226e2019-09-23 03:48:44 +00008795 !Evaluate(Info.CurrentCall->createTemporary(
8796 E->getCommonExpr(),
8797 getStorageType(Info.Ctx, E->getCommonExpr()), false,
8798 CommonLV),
Richard Smith410306b2016-12-12 02:53:20 +00008799 Info, E->getCommonExpr()->getSourceExpr()))
8800 return false;
8801
8802 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8803
8804 uint64_t Elements = CAT->getSize().getZExtValue();
8805 Result = APValue(APValue::UninitArray(), Elements, Elements);
8806
8807 LValue Subobject = This;
8808 Subobject.addArray(Info, E, CAT);
8809
8810 bool Success = true;
8811 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8812 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8813 Info, Subobject, E->getSubExpr()) ||
8814 !HandleLValueArrayAdjustment(Info, E, Subobject,
8815 CAT->getElementType(), 1)) {
8816 if (!Info.noteFailure())
8817 return false;
8818 Success = false;
8819 }
8820 }
8821
8822 return Success;
8823}
8824
Richard Smith027bf112011-11-17 22:56:20 +00008825bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008826 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8827}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008828
Richard Smith9543c5e2013-04-22 14:44:29 +00008829bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8830 const LValue &Subobject,
8831 APValue *Value,
8832 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008833 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008834
8835 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8836 unsigned N = CAT->getSize().getZExtValue();
8837
8838 // Preserve the array filler if we had prior zero-initialization.
8839 APValue Filler =
8840 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8841 : APValue();
8842
8843 *Value = APValue(APValue::UninitArray(), N, N);
8844
8845 if (HadZeroInit)
8846 for (unsigned I = 0; I != N; ++I)
8847 Value->getArrayInitializedElt(I) = Filler;
8848
8849 // Initialize the elements.
8850 LValue ArrayElt = Subobject;
8851 ArrayElt.addArray(Info, E, CAT);
8852 for (unsigned I = 0; I != N; ++I)
8853 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8854 CAT->getElementType()) ||
8855 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8856 CAT->getElementType(), 1))
8857 return false;
8858
8859 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008860 }
Richard Smith027bf112011-11-17 22:56:20 +00008861
Richard Smith9543c5e2013-04-22 14:44:29 +00008862 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008863 return Error(E);
8864
Richard Smithb8348f52016-05-12 22:16:28 +00008865 return RecordExprEvaluator(Info, Subobject, *Value)
8866 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008867}
8868
Richard Smithf3e9e432011-11-07 09:22:26 +00008869//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008870// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008871//
8872// As a GNU extension, we support casting pointers to sufficiently-wide integer
8873// types and back in constant folding. Integer values are thus represented
8874// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008875//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008876
8877namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008878class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008879 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008880 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008881public:
Richard Smith2e312c82012-03-03 22:46:17 +00008882 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008883 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008884
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008885 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008886 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008887 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008888 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008889 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008890 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008891 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008892 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008893 return true;
8894 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008895 bool Success(const llvm::APSInt &SI, const Expr *E) {
8896 return Success(SI, E, Result);
8897 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008898
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008899 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008900 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008901 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008902 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008903 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008904 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008905 Result.getInt().setIsUnsigned(
8906 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008907 return true;
8908 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008909 bool Success(const llvm::APInt &I, const Expr *E) {
8910 return Success(I, E, Result);
8911 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008912
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008913 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008914 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008915 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008916 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008917 return true;
8918 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008919 bool Success(uint64_t Value, const Expr *E) {
8920 return Success(Value, E, Result);
8921 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008922
Ken Dyckdbc01912011-03-11 02:13:43 +00008923 bool Success(CharUnits Size, const Expr *E) {
8924 return Success(Size.getQuantity(), E);
8925 }
8926
Richard Smith2e312c82012-03-03 22:46:17 +00008927 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00008928 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008929 Result = V;
8930 return true;
8931 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008932 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008933 }
Mike Stump11289f42009-09-09 15:08:12 +00008934
Richard Smithfddd3842011-12-30 21:15:51 +00008935 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008936
Peter Collingbournee9200682011-05-13 03:29:01 +00008937 //===--------------------------------------------------------------------===//
8938 // Visitor Methods
8939 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008940
Fangrui Song407659a2018-11-30 23:41:18 +00008941 bool VisitConstantExpr(const ConstantExpr *E);
8942
Chris Lattner7174bf32008-07-12 00:38:25 +00008943 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008944 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008945 }
8946 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008947 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008948 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008949
8950 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8951 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008952 if (CheckReferencedDecl(E, E->getDecl()))
8953 return true;
8954
8955 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008956 }
8957 bool VisitMemberExpr(const MemberExpr *E) {
8958 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008959 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008960 return true;
8961 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008962
8963 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008964 }
8965
Peter Collingbournee9200682011-05-13 03:29:01 +00008966 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008967 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008968 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008969 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008970 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008971
Peter Collingbournee9200682011-05-13 03:29:01 +00008972 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008973 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008974
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008975 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008976 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008977 }
Mike Stump11289f42009-09-09 15:08:12 +00008978
Ted Kremeneke65b0862012-03-06 20:05:56 +00008979 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8980 return Success(E->getValue(), E);
8981 }
Richard Smith410306b2016-12-12 02:53:20 +00008982
8983 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8984 if (Info.ArrayInitIndex == uint64_t(-1)) {
8985 // We were asked to evaluate this subexpression independent of the
8986 // enclosing ArrayInitLoopExpr. We can't do that.
8987 Info.FFDiag(E);
8988 return false;
8989 }
8990 return Success(Info.ArrayInitIndex, E);
8991 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008992
Richard Smith4ce706a2011-10-11 21:43:33 +00008993 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008994 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008995 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008996 }
8997
Douglas Gregor29c42f22012-02-24 07:38:34 +00008998 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8999 return Success(E->getValue(), E);
9000 }
9001
John Wiegley6242b6a2011-04-28 00:16:57 +00009002 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9003 return Success(E->getValue(), E);
9004 }
9005
John Wiegleyf9f65842011-04-25 06:54:41 +00009006 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9007 return Success(E->getValue(), E);
9008 }
9009
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009010 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009011 bool VisitUnaryImag(const UnaryOperator *E);
9012
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009013 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009014 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00009015 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009016 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00009017};
Leonard Chandb01c3a2018-06-20 17:19:40 +00009018
9019class FixedPointExprEvaluator
9020 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9021 APValue &Result;
9022
9023 public:
9024 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9025 : ExprEvaluatorBaseTy(info), Result(result) {}
9026
Leonard Chandb01c3a2018-06-20 17:19:40 +00009027 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009028 return Success(
9029 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009030 }
9031
Leonard Chandb01c3a2018-06-20 17:19:40 +00009032 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009033 return Success(
9034 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009035 }
9036
9037 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009038 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009039 }
9040
Leonard Chand3f3e162019-01-18 21:04:25 +00009041 bool Success(const APFixedPoint &V, const Expr *E) {
9042 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9043 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9044 "Invalid evaluation result.");
9045 Result = APValue(V);
9046 return true;
9047 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00009048
9049 //===--------------------------------------------------------------------===//
9050 // Visitor Methods
9051 //===--------------------------------------------------------------------===//
9052
9053 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9054 return Success(E->getValue(), E);
9055 }
9056
Leonard Chand3f3e162019-01-18 21:04:25 +00009057 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009058 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00009059 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009060};
Chris Lattner05706e882008-07-11 18:11:29 +00009061} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009062
Richard Smith11562c52011-10-28 17:51:58 +00009063/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9064/// produce either the integer value or a pointer.
9065///
9066/// GCC has a heinous extension which folds casts between pointer types and
9067/// pointer-sized integral types. We support this by allowing the evaluation of
9068/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9069/// Some simple arithmetic on such values is supported (they are treated much
9070/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00009071static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00009072 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009073 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009074 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00009075}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009076
Richard Smithf57d8cb2011-12-09 22:58:01 +00009077static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00009078 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009079 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00009080 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009081 if (!Val.isInt()) {
9082 // FIXME: It would be better to produce the diagnostic for casting
9083 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00009084 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009085 return false;
9086 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009087 Result = Val.getInt();
9088 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009089}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009090
Eric Fiselier708afb52019-05-16 21:04:15 +00009091bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9092 APValue Evaluated = E->EvaluateInContext(
9093 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9094 return Success(Evaluated, E);
9095}
9096
Leonard Chand3f3e162019-01-18 21:04:25 +00009097static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9098 EvalInfo &Info) {
9099 if (E->getType()->isFixedPointType()) {
9100 APValue Val;
9101 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9102 return false;
9103 if (!Val.isFixedPoint())
9104 return false;
9105
9106 Result = Val.getFixedPoint();
9107 return true;
9108 }
9109 return false;
9110}
9111
9112static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9113 EvalInfo &Info) {
9114 if (E->getType()->isIntegerType()) {
9115 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9116 APSInt Val;
9117 if (!EvaluateInteger(E, Val, Info))
9118 return false;
9119 Result = APFixedPoint(Val, FXSema);
9120 return true;
9121 } else if (E->getType()->isFixedPointType()) {
9122 return EvaluateFixedPoint(E, Result, Info);
9123 }
9124 return false;
9125}
9126
Richard Smithf57d8cb2011-12-09 22:58:01 +00009127/// Check whether the given declaration can be directly converted to an integral
9128/// rvalue. If not, no diagnostic is produced; there are other things we can
9129/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009130bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00009131 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009132 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009133 // Check for signedness/width mismatches between E type and ECD value.
9134 bool SameSign = (ECD->getInitVal().isSigned()
9135 == E->getType()->isSignedIntegerOrEnumerationType());
9136 bool SameWidth = (ECD->getInitVal().getBitWidth()
9137 == Info.Ctx.getIntWidth(E->getType()));
9138 if (SameSign && SameWidth)
9139 return Success(ECD->getInitVal(), E);
9140 else {
9141 // Get rid of mismatch (otherwise Success assertions will fail)
9142 // by computing a new value matching the type of E.
9143 llvm::APSInt Val = ECD->getInitVal();
9144 if (!SameSign)
9145 Val.setIsSigned(!ECD->getInitVal().isSigned());
9146 if (!SameWidth)
9147 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9148 return Success(Val, E);
9149 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009150 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009151 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00009152}
9153
Richard Smith08b682b2018-05-23 21:18:00 +00009154/// Values returned by __builtin_classify_type, chosen to match the values
9155/// produced by GCC's builtin.
9156enum class GCCTypeClass {
9157 None = -1,
9158 Void = 0,
9159 Integer = 1,
9160 // GCC reserves 2 for character types, but instead classifies them as
9161 // integers.
9162 Enum = 3,
9163 Bool = 4,
9164 Pointer = 5,
9165 // GCC reserves 6 for references, but appears to never use it (because
9166 // expressions never have reference type, presumably).
9167 PointerToDataMember = 7,
9168 RealFloat = 8,
9169 Complex = 9,
9170 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9171 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9172 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9173 // uses 12 for that purpose, same as for a class or struct. Maybe it
9174 // internally implements a pointer to member as a struct? Who knows.
9175 PointerToMemberFunction = 12, // Not a bug, see above.
9176 ClassOrStruct = 12,
9177 Union = 13,
9178 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9179 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9180 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9181 // literals.
9182};
9183
Chris Lattner86ee2862008-10-06 06:40:35 +00009184/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9185/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00009186static GCCTypeClass
9187EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9188 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00009189
Richard Smith08b682b2018-05-23 21:18:00 +00009190 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009191 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9192
9193 switch (CanTy->getTypeClass()) {
9194#define TYPE(ID, BASE)
9195#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9196#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9197#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
9198#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00009199 case Type::Auto:
9200 case Type::DeducedTemplateSpecialization:
9201 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009202
9203 case Type::Builtin:
9204 switch (BT->getKind()) {
9205#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00009206#define SIGNED_TYPE(ID, SINGLETON_ID) \
9207 case BuiltinType::ID: return GCCTypeClass::Integer;
9208#define FLOATING_TYPE(ID, SINGLETON_ID) \
9209 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9210#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9211 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009212#include "clang/AST/BuiltinTypes.def"
9213 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00009214 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009215
9216 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00009217 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009218
Richard Smith08b682b2018-05-23 21:18:00 +00009219 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009220 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00009221 case BuiltinType::WChar_U:
9222 case BuiltinType::Char8:
9223 case BuiltinType::Char16:
9224 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009225 case BuiltinType::UShort:
9226 case BuiltinType::UInt:
9227 case BuiltinType::ULong:
9228 case BuiltinType::ULongLong:
9229 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00009230 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009231
Leonard Chanf921d852018-06-04 16:07:52 +00009232 case BuiltinType::UShortAccum:
9233 case BuiltinType::UAccum:
9234 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009235 case BuiltinType::UShortFract:
9236 case BuiltinType::UFract:
9237 case BuiltinType::ULongFract:
9238 case BuiltinType::SatUShortAccum:
9239 case BuiltinType::SatUAccum:
9240 case BuiltinType::SatULongAccum:
9241 case BuiltinType::SatUShortFract:
9242 case BuiltinType::SatUFract:
9243 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00009244 return GCCTypeClass::None;
9245
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009246 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009247
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009248 case BuiltinType::ObjCId:
9249 case BuiltinType::ObjCClass:
9250 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00009251#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9252 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00009253#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00009254#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9255 case BuiltinType::Id:
9256#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009257 case BuiltinType::OCLSampler:
9258 case BuiltinType::OCLEvent:
9259 case BuiltinType::OCLClkEvent:
9260 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009261 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00009262#define SVE_TYPE(Name, Id, SingletonId) \
9263 case BuiltinType::Id:
9264#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00009265 return GCCTypeClass::None;
9266
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009267 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00009268 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009269 };
Richard Smith08b682b2018-05-23 21:18:00 +00009270 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009271
9272 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00009273 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009274
9275 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009276 case Type::ConstantArray:
9277 case Type::VariableArray:
9278 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00009279 case Type::FunctionNoProto:
9280 case Type::FunctionProto:
9281 return GCCTypeClass::Pointer;
9282
9283 case Type::MemberPointer:
9284 return CanTy->isMemberDataPointerType()
9285 ? GCCTypeClass::PointerToDataMember
9286 : GCCTypeClass::PointerToMemberFunction;
9287
9288 case Type::Complex:
9289 return GCCTypeClass::Complex;
9290
9291 case Type::Record:
9292 return CanTy->isUnionType() ? GCCTypeClass::Union
9293 : GCCTypeClass::ClassOrStruct;
9294
9295 case Type::Atomic:
9296 // GCC classifies _Atomic T the same as T.
9297 return EvaluateBuiltinClassifyType(
9298 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009299
9300 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009301 case Type::Vector:
9302 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009303 case Type::ObjCObject:
9304 case Type::ObjCInterface:
9305 case Type::ObjCObjectPointer:
9306 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00009307 // GCC classifies vectors as None. We follow its lead and classify all
9308 // other types that don't fit into the regular classification the same way.
9309 return GCCTypeClass::None;
9310
9311 case Type::LValueReference:
9312 case Type::RValueReference:
9313 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009314 }
9315
Richard Smith08b682b2018-05-23 21:18:00 +00009316 llvm_unreachable("unexpected type class");
9317}
9318
9319/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9320/// as GCC.
9321static GCCTypeClass
9322EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9323 // If no argument was supplied, default to None. This isn't
9324 // ideal, however it is what gcc does.
9325 if (E->getNumArgs() == 0)
9326 return GCCTypeClass::None;
9327
9328 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9329 // being an ICE, but still folds it to a constant using the type of the first
9330 // argument.
9331 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00009332}
9333
Richard Smith5fab0c92011-12-28 19:48:30 +00009334/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00009335/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00009336///
Richard Smith31cfb312019-04-27 02:58:17 +00009337/// A pointer is only "constant" if it is null (or a pointer cast to integer)
9338/// or it points to the first character of a string literal.
9339static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9340 APValue::LValueBase Base = LV.getLValueBase();
9341 if (Base.isNull()) {
9342 // A null base is acceptable.
9343 return true;
9344 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9345 if (!isa<StringLiteral>(E))
9346 return false;
9347 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00009348 } else if (Base.is<TypeInfoLValue>()) {
9349 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9350 // evaluate to true.
9351 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00009352 } else {
9353 // Any other base is not constant enough for GCC.
9354 return false;
9355 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009356}
9357
9358/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9359/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00009360static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00009361 // This evaluation is not permitted to have side-effects, so evaluate it in
9362 // a speculative evaluation context.
9363 SpeculativeEvaluationRAII SpeculativeEval(Info);
9364
Richard Smith31cfb312019-04-27 02:58:17 +00009365 // Constant-folding is always enabled for the operand of __builtin_constant_p
9366 // (even when the enclosing evaluation context otherwise requires a strict
9367 // language-specific constant expression).
9368 FoldConstant Fold(Info, true);
9369
Richard Smith5fab0c92011-12-28 19:48:30 +00009370 QualType ArgType = Arg->getType();
9371
9372 // __builtin_constant_p always has one operand. The rules which gcc follows
9373 // are not precisely documented, but are as follows:
9374 //
9375 // - If the operand is of integral, floating, complex or enumeration type,
9376 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00009377 // - If the operand can be folded to a pointer to the first character
9378 // of a string literal (or such a pointer cast to an integral type)
9379 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00009380 //
9381 // Otherwise, it returns 0.
9382 //
9383 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00009384 // its support for this did not work prior to GCC 9 and is not yet well
9385 // understood.
9386 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9387 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9388 ArgType->isNullPtrType()) {
9389 APValue V;
9390 if (!::EvaluateAsRValue(Info, Arg, V)) {
9391 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00009392 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00009393 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009394
Richard Smith31cfb312019-04-27 02:58:17 +00009395 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00009396 if (V.getKind() == APValue::LValue)
9397 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00009398
9399 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00009400 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00009401 }
9402
9403 // Anything else isn't considered to be sufficiently constant.
9404 return false;
9405}
9406
John McCall95007602010-05-10 23:27:23 +00009407/// Retrieves the "underlying object type" of the given expression,
9408/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00009409static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00009410 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9411 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00009412 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00009413 } else if (const Expr *E = B.get<const Expr*>()) {
9414 if (isa<CompoundLiteralExpr>(E))
9415 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00009416 } else if (B.is<TypeInfoLValue>()) {
9417 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00009418 }
9419
9420 return QualType();
9421}
9422
George Burgess IV3a03fab2015-09-04 21:28:13 +00009423/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00009424/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00009425/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00009426/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9427///
9428/// Always returns an RValue with a pointer representation.
9429static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9430 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9431
9432 auto *NoParens = E->IgnoreParens();
9433 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00009434 if (Cast == nullptr)
9435 return NoParens;
9436
9437 // We only conservatively allow a few kinds of casts, because this code is
9438 // inherently a simple solution that seeks to support the common case.
9439 auto CastKind = Cast->getCastKind();
9440 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9441 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00009442 return NoParens;
9443
9444 auto *SubExpr = Cast->getSubExpr();
9445 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9446 return NoParens;
9447 return ignorePointerCastsAndParens(SubExpr);
9448}
9449
George Burgess IVa51c4072015-10-16 01:49:01 +00009450/// Checks to see if the given LValue's Designator is at the end of the LValue's
9451/// record layout. e.g.
9452/// struct { struct { int a, b; } fst, snd; } obj;
9453/// obj.fst // no
9454/// obj.snd // yes
9455/// obj.fst.a // no
9456/// obj.fst.b // no
9457/// obj.snd.a // no
9458/// obj.snd.b // yes
9459///
9460/// Please note: this function is specialized for how __builtin_object_size
9461/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00009462///
Richard Smith6f4f0f12017-10-20 22:56:25 +00009463/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9464/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00009465static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9466 assert(!LVal.Designator.Invalid);
9467
George Burgess IV4168d752016-06-27 19:40:41 +00009468 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9469 const RecordDecl *Parent = FD->getParent();
9470 Invalid = Parent->isInvalidDecl();
9471 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00009472 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00009473 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00009474 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9475 };
9476
9477 auto &Base = LVal.getLValueBase();
9478 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9479 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009480 bool Invalid;
9481 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9482 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009483 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009484 for (auto *FD : IFD->chain()) {
9485 bool Invalid;
9486 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9487 return Invalid;
9488 }
George Burgess IVa51c4072015-10-16 01:49:01 +00009489 }
9490 }
9491
George Burgess IVe3763372016-12-22 02:50:20 +00009492 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00009493 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00009494 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00009495 // If we don't know the array bound, conservatively assume we're looking at
9496 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00009497 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00009498 if (BaseType->isIncompleteArrayType())
9499 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9500 else
9501 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00009502 }
9503
9504 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9505 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00009506 if (BaseType->isArrayType()) {
9507 // Because __builtin_object_size treats arrays as objects, we can ignore
9508 // the index iff this is the last array in the Designator.
9509 if (I + 1 == E)
9510 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00009511 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00009512 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009513 if (Index + 1 != CAT->getSize())
9514 return false;
9515 BaseType = CAT->getElementType();
9516 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00009517 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009518 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009519 if (Index != 1)
9520 return false;
9521 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00009522 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00009523 bool Invalid;
9524 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9525 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009526 BaseType = FD->getType();
9527 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00009528 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00009529 return false;
9530 }
9531 }
9532 return true;
9533}
9534
George Burgess IVe3763372016-12-22 02:50:20 +00009535/// Tests to see if the LValue has a user-specified designator (that isn't
9536/// necessarily valid). Note that this always returns 'true' if the LValue has
9537/// an unsized array as its first designator entry, because there's currently no
9538/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00009539static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00009540 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00009541 return false;
9542
George Burgess IVe3763372016-12-22 02:50:20 +00009543 if (!LVal.Designator.Entries.empty())
9544 return LVal.Designator.isMostDerivedAnUnsizedArray();
9545
George Burgess IVa51c4072015-10-16 01:49:01 +00009546 if (!LVal.InvalidBase)
9547 return true;
9548
George Burgess IVe3763372016-12-22 02:50:20 +00009549 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9550 // the LValueBase.
9551 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9552 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00009553}
9554
George Burgess IVe3763372016-12-22 02:50:20 +00009555/// Attempts to detect a user writing into a piece of memory that's impossible
9556/// to figure out the size of by just using types.
9557static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9558 const SubobjectDesignator &Designator = LVal.Designator;
9559 // Notes:
9560 // - Users can only write off of the end when we have an invalid base. Invalid
9561 // bases imply we don't know where the memory came from.
9562 // - We used to be a bit more aggressive here; we'd only be conservative if
9563 // the array at the end was flexible, or if it had 0 or 1 elements. This
9564 // broke some common standard library extensions (PR30346), but was
9565 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9566 // with some sort of whitelist. OTOH, it seems that GCC is always
9567 // conservative with the last element in structs (if it's an array), so our
9568 // current behavior is more compatible than a whitelisting approach would
9569 // be.
9570 return LVal.InvalidBase &&
9571 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9572 Designator.MostDerivedIsArrayElement &&
9573 isDesignatorAtObjectEnd(Ctx, LVal);
9574}
9575
9576/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9577/// Fails if the conversion would cause loss of precision.
9578static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9579 CharUnits &Result) {
9580 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9581 if (Int.ugt(CharUnitsMax))
9582 return false;
9583 Result = CharUnits::fromQuantity(Int.getZExtValue());
9584 return true;
9585}
9586
9587/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9588/// determine how many bytes exist from the beginning of the object to either
9589/// the end of the current subobject, or the end of the object itself, depending
9590/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00009591///
George Burgess IVe3763372016-12-22 02:50:20 +00009592/// If this returns false, the value of Result is undefined.
9593static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9594 unsigned Type, const LValue &LVal,
9595 CharUnits &EndOffset) {
9596 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009597
George Burgess IV7fb7e362017-01-03 23:35:19 +00009598 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9599 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9600 return false;
9601 return HandleSizeof(Info, ExprLoc, Ty, Result);
9602 };
9603
George Burgess IVe3763372016-12-22 02:50:20 +00009604 // We want to evaluate the size of the entire object. This is a valid fallback
9605 // for when Type=1 and the designator is invalid, because we're asked for an
9606 // upper-bound.
9607 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9608 // Type=3 wants a lower bound, so we can't fall back to this.
9609 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00009610 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00009611
9612 llvm::APInt APEndOffset;
9613 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9614 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9615 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9616
9617 if (LVal.InvalidBase)
9618 return false;
9619
9620 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00009621 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00009622 }
9623
George Burgess IVe3763372016-12-22 02:50:20 +00009624 // We want to evaluate the size of a subobject.
9625 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009626
9627 // The following is a moderately common idiom in C:
9628 //
9629 // struct Foo { int a; char c[1]; };
9630 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9631 // strcpy(&F->c[0], Bar);
9632 //
George Burgess IVe3763372016-12-22 02:50:20 +00009633 // In order to not break too much legacy code, we need to support it.
9634 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9635 // If we can resolve this to an alloc_size call, we can hand that back,
9636 // because we know for certain how many bytes there are to write to.
9637 llvm::APInt APEndOffset;
9638 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9639 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9640 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9641
9642 // If we cannot determine the size of the initial allocation, then we can't
9643 // given an accurate upper-bound. However, we are still able to give
9644 // conservative lower-bounds for Type=3.
9645 if (Type == 1)
9646 return false;
9647 }
9648
9649 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00009650 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009651 return false;
9652
George Burgess IVe3763372016-12-22 02:50:20 +00009653 // According to the GCC documentation, we want the size of the subobject
9654 // denoted by the pointer. But that's not quite right -- what we actually
9655 // want is the size of the immediately-enclosing array, if there is one.
9656 int64_t ElemsRemaining;
9657 if (Designator.MostDerivedIsArrayElement &&
9658 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9659 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009660 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00009661 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9662 } else {
9663 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9664 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009665
George Burgess IVe3763372016-12-22 02:50:20 +00009666 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9667 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009668}
9669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009670/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00009671/// returns true and stores the result in @p Size.
9672///
9673/// If @p WasError is non-null, this will report whether the failure to evaluate
9674/// is to be treated as an Error in IntExprEvaluator.
9675static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9676 EvalInfo &Info, uint64_t &Size) {
9677 // Determine the denoted object.
9678 LValue LVal;
9679 {
9680 // The operand of __builtin_object_size is never evaluated for side-effects.
9681 // If there are any, but we can determine the pointed-to object anyway, then
9682 // ignore the side-effects.
9683 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00009684 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00009685
9686 if (E->isGLValue()) {
9687 // It's possible for us to be given GLValues if we're called via
9688 // Expr::tryEvaluateObjectSize.
9689 APValue RVal;
9690 if (!EvaluateAsRValue(Info, E, RVal))
9691 return false;
9692 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00009693 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9694 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00009695 return false;
9696 }
9697
9698 // If we point to before the start of the object, there are no accessible
9699 // bytes.
9700 if (LVal.getLValueOffset().isNegative()) {
9701 Size = 0;
9702 return true;
9703 }
9704
9705 CharUnits EndOffset;
9706 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9707 return false;
9708
9709 // If we've fallen outside of the end offset, just pretend there's nothing to
9710 // write to/read from.
9711 if (EndOffset <= LVal.getLValueOffset())
9712 Size = 0;
9713 else
9714 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9715 return true;
John McCall95007602010-05-10 23:27:23 +00009716}
9717
Fangrui Song407659a2018-11-30 23:41:18 +00009718bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9719 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +00009720 if (E->getResultAPValueKind() != APValue::None)
9721 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +00009722 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9723}
9724
Peter Collingbournee9200682011-05-13 03:29:01 +00009725bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00009726 if (unsigned BuiltinOp = E->getBuiltinCallee())
9727 return VisitBuiltinCallExpr(E, BuiltinOp);
9728
9729 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9730}
9731
9732bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9733 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00009734 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009735 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00009736 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00009737
Erik Pilkington9c3b5882019-01-30 20:34:53 +00009738 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00009739 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00009740 // The type was checked when we built the expression.
9741 unsigned Type =
9742 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9743 assert(Type <= 3 && "unexpected type");
9744
George Burgess IVe3763372016-12-22 02:50:20 +00009745 uint64_t Size;
9746 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9747 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00009748
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009749 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00009750 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00009751
Richard Smith01ade172012-05-23 04:13:20 +00009752 // Expression had no side effects, but we couldn't statically determine the
9753 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009754 switch (Info.EvalMode) {
9755 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009756 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009757 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009758 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009759 return Error(E);
9760 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009761 // Reduce it to a constant now.
9762 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009763 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009764
9765 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009766 }
9767
Tim Northover314fbfa2018-11-02 13:14:11 +00009768 case Builtin::BI__builtin_os_log_format_buffer_size: {
9769 analyze_os_log::OSLogBufferLayout Layout;
9770 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9771 return Success(Layout.size().getQuantity(), E);
9772 }
9773
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009774 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009775 case Builtin::BI__builtin_bswap32:
9776 case Builtin::BI__builtin_bswap64: {
9777 APSInt Val;
9778 if (!EvaluateInteger(E->getArg(0), Val, Info))
9779 return false;
9780
9781 return Success(Val.byteSwap(), E);
9782 }
9783
Richard Smith8889a3d2013-06-13 06:26:32 +00009784 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009785 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009786
Craig Topperf95a6d92018-08-08 22:31:12 +00009787 case Builtin::BI__builtin_clrsb:
9788 case Builtin::BI__builtin_clrsbl:
9789 case Builtin::BI__builtin_clrsbll: {
9790 APSInt Val;
9791 if (!EvaluateInteger(E->getArg(0), Val, Info))
9792 return false;
9793
9794 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9795 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009796
Richard Smith80b3c8e2013-06-13 05:04:16 +00009797 case Builtin::BI__builtin_clz:
9798 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009799 case Builtin::BI__builtin_clzll:
9800 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009801 APSInt Val;
9802 if (!EvaluateInteger(E->getArg(0), Val, Info))
9803 return false;
9804 if (!Val)
9805 return Error(E);
9806
9807 return Success(Val.countLeadingZeros(), E);
9808 }
9809
Fangrui Song407659a2018-11-30 23:41:18 +00009810 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009811 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009812 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009813 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009814 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009815 // Outside a constant context, eagerly evaluate to false in the presence
9816 // of side-effects in order to avoid -Wunsequenced false-positives in
9817 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009818 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009819 }
David Blaikie639b3d12019-05-03 18:11:31 +00009820 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9821 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009822 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009823
Eric Fiselieradd16a82019-04-24 02:23:30 +00009824 case Builtin::BI__builtin_is_constant_evaluated:
9825 return Success(Info.InConstantContext, E);
9826
Richard Smith80b3c8e2013-06-13 05:04:16 +00009827 case Builtin::BI__builtin_ctz:
9828 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009829 case Builtin::BI__builtin_ctzll:
9830 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009831 APSInt Val;
9832 if (!EvaluateInteger(E->getArg(0), Val, Info))
9833 return false;
9834 if (!Val)
9835 return Error(E);
9836
9837 return Success(Val.countTrailingZeros(), E);
9838 }
9839
Richard Smith8889a3d2013-06-13 06:26:32 +00009840 case Builtin::BI__builtin_eh_return_data_regno: {
9841 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9842 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9843 return Success(Operand, E);
9844 }
9845
9846 case Builtin::BI__builtin_expect:
9847 return Visit(E->getArg(0));
9848
9849 case Builtin::BI__builtin_ffs:
9850 case Builtin::BI__builtin_ffsl:
9851 case Builtin::BI__builtin_ffsll: {
9852 APSInt Val;
9853 if (!EvaluateInteger(E->getArg(0), Val, Info))
9854 return false;
9855
9856 unsigned N = Val.countTrailingZeros();
9857 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9858 }
9859
9860 case Builtin::BI__builtin_fpclassify: {
9861 APFloat Val(0.0);
9862 if (!EvaluateFloat(E->getArg(5), Val, Info))
9863 return false;
9864 unsigned Arg;
9865 switch (Val.getCategory()) {
9866 case APFloat::fcNaN: Arg = 0; break;
9867 case APFloat::fcInfinity: Arg = 1; break;
9868 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9869 case APFloat::fcZero: Arg = 4; break;
9870 }
9871 return Visit(E->getArg(Arg));
9872 }
9873
9874 case Builtin::BI__builtin_isinf_sign: {
9875 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009876 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009877 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9878 }
9879
Richard Smithea3019d2013-10-15 19:07:14 +00009880 case Builtin::BI__builtin_isinf: {
9881 APFloat Val(0.0);
9882 return EvaluateFloat(E->getArg(0), Val, Info) &&
9883 Success(Val.isInfinity() ? 1 : 0, E);
9884 }
9885
9886 case Builtin::BI__builtin_isfinite: {
9887 APFloat Val(0.0);
9888 return EvaluateFloat(E->getArg(0), Val, Info) &&
9889 Success(Val.isFinite() ? 1 : 0, E);
9890 }
9891
9892 case Builtin::BI__builtin_isnan: {
9893 APFloat Val(0.0);
9894 return EvaluateFloat(E->getArg(0), Val, Info) &&
9895 Success(Val.isNaN() ? 1 : 0, E);
9896 }
9897
9898 case Builtin::BI__builtin_isnormal: {
9899 APFloat Val(0.0);
9900 return EvaluateFloat(E->getArg(0), Val, Info) &&
9901 Success(Val.isNormal() ? 1 : 0, E);
9902 }
9903
Richard Smith8889a3d2013-06-13 06:26:32 +00009904 case Builtin::BI__builtin_parity:
9905 case Builtin::BI__builtin_parityl:
9906 case Builtin::BI__builtin_parityll: {
9907 APSInt Val;
9908 if (!EvaluateInteger(E->getArg(0), Val, Info))
9909 return false;
9910
9911 return Success(Val.countPopulation() % 2, E);
9912 }
9913
Richard Smith80b3c8e2013-06-13 05:04:16 +00009914 case Builtin::BI__builtin_popcount:
9915 case Builtin::BI__builtin_popcountl:
9916 case Builtin::BI__builtin_popcountll: {
9917 APSInt Val;
9918 if (!EvaluateInteger(E->getArg(0), Val, Info))
9919 return false;
9920
9921 return Success(Val.countPopulation(), E);
9922 }
9923
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009924 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009925 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009926 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009927 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009928 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009929 << /*isConstexpr*/0 << /*isConstructor*/0
9930 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009931 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009932 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009933 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009934 case Builtin::BI__builtin_strlen:
9935 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009936 // As an extension, we support __builtin_strlen() as a constant expression,
9937 // and support folding strlen() to a constant.
9938 LValue String;
9939 if (!EvaluatePointer(E->getArg(0), String, Info))
9940 return false;
9941
Richard Smith8110c9d2016-11-29 19:45:17 +00009942 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9943
Richard Smithe6c19f22013-11-15 02:10:04 +00009944 // Fast path: if it's a string literal, search the string value.
9945 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9946 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009947 // The string literal may have embedded null characters. Find the first
9948 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009949 StringRef Str = S->getBytes();
9950 int64_t Off = String.Offset.getQuantity();
9951 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009952 S->getCharByteWidth() == 1 &&
9953 // FIXME: Add fast-path for wchar_t too.
9954 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009955 Str = Str.substr(Off);
9956
9957 StringRef::size_type Pos = Str.find(0);
9958 if (Pos != StringRef::npos)
9959 Str = Str.substr(0, Pos);
9960
9961 return Success(Str.size(), E);
9962 }
9963
9964 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009965 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009966
9967 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009968 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9969 APValue Char;
9970 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9971 !Char.isInt())
9972 return false;
9973 if (!Char.getInt())
9974 return Success(Strlen, E);
9975 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9976 return false;
9977 }
9978 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009979
Richard Smithe151bab2016-11-11 23:43:35 +00009980 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009981 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009982 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009983 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009984 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009985 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009986 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009987 // A call to strlen is not a constant expression.
9988 if (Info.getLangOpts().CPlusPlus11)
9989 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9990 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009991 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009992 else
9993 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009994 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009995 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009996 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009997 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009998 case Builtin::BI__builtin_wcsncmp:
9999 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010000 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010001 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +000010002 LValue String1, String2;
10003 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10004 !EvaluatePointer(E->getArg(1), String2, Info))
10005 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +000010006
Richard Smithe151bab2016-11-11 23:43:35 +000010007 uint64_t MaxLength = uint64_t(-1);
10008 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010009 BuiltinOp != Builtin::BIwcscmp &&
10010 BuiltinOp != Builtin::BI__builtin_strcmp &&
10011 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +000010012 APSInt N;
10013 if (!EvaluateInteger(E->getArg(2), N, Info))
10014 return false;
10015 MaxLength = N.getExtValue();
10016 }
Hubert Tong147b7432018-12-12 16:53:43 +000010017
10018 // Empty substrings compare equal by definition.
10019 if (MaxLength == 0u)
10020 return Success(0, E);
10021
10022 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10023 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10024 String1.Designator.Invalid || String2.Designator.Invalid)
10025 return false;
10026
10027 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10028 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10029
10030 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +000010031 BuiltinOp == Builtin::BIbcmp ||
10032 BuiltinOp == Builtin::BI__builtin_memcmp ||
10033 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010034
10035 assert(IsRawByte ||
10036 (Info.Ctx.hasSameUnqualifiedType(
10037 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
10038 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
10039
10040 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10041 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10042 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10043 Char1.isInt() && Char2.isInt();
10044 };
10045 const auto &AdvanceElems = [&] {
10046 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10047 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10048 };
10049
10050 if (IsRawByte) {
10051 uint64_t BytesRemaining = MaxLength;
10052 // Pointers to const void may point to objects of incomplete type.
10053 if (CharTy1->isIncompleteType()) {
10054 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10055 return false;
10056 }
10057 if (CharTy2->isIncompleteType()) {
10058 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10059 return false;
10060 }
10061 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10062 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10063 // Give up on comparing between elements with disparate widths.
10064 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10065 return false;
10066 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10067 assert(BytesRemaining && "BytesRemaining should not be zero: the "
10068 "following loop considers at least one element");
10069 while (true) {
10070 APValue Char1, Char2;
10071 if (!ReadCurElems(Char1, Char2))
10072 return false;
10073 // We have compatible in-memory widths, but a possible type and
10074 // (for `bool`) internal representation mismatch.
10075 // Assuming two's complement representation, including 0 for `false` and
10076 // 1 for `true`, we can check an appropriate number of elements for
10077 // equality even if they are not byte-sized.
10078 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10079 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10080 if (Char1InMem.ne(Char2InMem)) {
10081 // If the elements are byte-sized, then we can produce a three-way
10082 // comparison result in a straightforward manner.
10083 if (BytesPerElement == 1u) {
10084 // memcmp always compares unsigned chars.
10085 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10086 }
10087 // The result is byte-order sensitive, and we have multibyte elements.
10088 // FIXME: We can compare the remaining bytes in the correct order.
10089 return false;
10090 }
10091 if (!AdvanceElems())
10092 return false;
10093 if (BytesRemaining <= BytesPerElement)
10094 break;
10095 BytesRemaining -= BytesPerElement;
10096 }
10097 // Enough elements are equal to account for the memcmp limit.
10098 return Success(0, E);
10099 }
10100
Clement Courbet8c3343d2019-02-14 12:00:34 +000010101 bool StopAtNull =
10102 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10103 BuiltinOp != Builtin::BIwmemcmp &&
10104 BuiltinOp != Builtin::BI__builtin_memcmp &&
10105 BuiltinOp != Builtin::BI__builtin_bcmp &&
10106 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +000010107 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10108 BuiltinOp == Builtin::BIwcsncmp ||
10109 BuiltinOp == Builtin::BIwmemcmp ||
10110 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10111 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10112 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010113
Richard Smithe151bab2016-11-11 23:43:35 +000010114 for (; MaxLength; --MaxLength) {
10115 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +000010116 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +000010117 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +000010118 if (Char1.getInt() != Char2.getInt()) {
10119 if (IsWide) // wmemcmp compares with wchar_t signedness.
10120 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10121 // memcmp always compares unsigned chars.
10122 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10123 }
Richard Smithe151bab2016-11-11 23:43:35 +000010124 if (StopAtNull && !Char1.getInt())
10125 return Success(0, E);
10126 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +000010127 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +000010128 return false;
10129 }
10130 // We hit the strncmp / memcmp limit.
10131 return Success(0, E);
10132 }
10133
Richard Smith01ba47d2012-04-13 00:45:38 +000010134 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +000010135 case Builtin::BI__atomic_is_lock_free:
10136 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +000010137 APSInt SizeVal;
10138 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10139 return false;
10140
10141 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10142 // of two less than the maximum inline atomic width, we know it is
10143 // lock-free. If the size isn't a power of two, or greater than the
10144 // maximum alignment where we promote atomics, we know it is not lock-free
10145 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10146 // the answer can only be determined at runtime; for example, 16-byte
10147 // atomics have lock-free implementations on some, but not all,
10148 // x86-64 processors.
10149
10150 // Check power-of-two.
10151 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +000010152 if (Size.isPowerOfTwo()) {
10153 // Check against inlining width.
10154 unsigned InlineWidthBits =
10155 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10156 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10157 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10158 Size == CharUnits::One() ||
10159 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10160 Expr::NPC_NeverValueDependent))
10161 // OK, we will inline appropriately-aligned operations of this size,
10162 // and _Atomic(T) is appropriately-aligned.
10163 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010164
Richard Smith01ba47d2012-04-13 00:45:38 +000010165 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10166 castAs<PointerType>()->getPointeeType();
10167 if (!PointeeType->isIncompleteType() &&
10168 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10169 // OK, we will inline operations on this object.
10170 return Success(1, E);
10171 }
10172 }
10173 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010174
Richard Smith01ba47d2012-04-13 00:45:38 +000010175 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10176 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010177 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +000010178 case Builtin::BIomp_is_initial_device:
10179 // We can decide statically which value the runtime would return if called.
10180 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +000010181 case Builtin::BI__builtin_add_overflow:
10182 case Builtin::BI__builtin_sub_overflow:
10183 case Builtin::BI__builtin_mul_overflow:
10184 case Builtin::BI__builtin_sadd_overflow:
10185 case Builtin::BI__builtin_uadd_overflow:
10186 case Builtin::BI__builtin_uaddl_overflow:
10187 case Builtin::BI__builtin_uaddll_overflow:
10188 case Builtin::BI__builtin_usub_overflow:
10189 case Builtin::BI__builtin_usubl_overflow:
10190 case Builtin::BI__builtin_usubll_overflow:
10191 case Builtin::BI__builtin_umul_overflow:
10192 case Builtin::BI__builtin_umull_overflow:
10193 case Builtin::BI__builtin_umulll_overflow:
10194 case Builtin::BI__builtin_saddl_overflow:
10195 case Builtin::BI__builtin_saddll_overflow:
10196 case Builtin::BI__builtin_ssub_overflow:
10197 case Builtin::BI__builtin_ssubl_overflow:
10198 case Builtin::BI__builtin_ssubll_overflow:
10199 case Builtin::BI__builtin_smul_overflow:
10200 case Builtin::BI__builtin_smull_overflow:
10201 case Builtin::BI__builtin_smulll_overflow: {
10202 LValue ResultLValue;
10203 APSInt LHS, RHS;
10204
10205 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10206 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10207 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10208 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10209 return false;
10210
10211 APSInt Result;
10212 bool DidOverflow = false;
10213
10214 // If the types don't have to match, enlarge all 3 to the largest of them.
10215 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10216 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10217 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10218 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
10219 ResultType->isSignedIntegerOrEnumerationType();
10220 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
10221 ResultType->isSignedIntegerOrEnumerationType();
10222 uint64_t LHSSize = LHS.getBitWidth();
10223 uint64_t RHSSize = RHS.getBitWidth();
10224 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
10225 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
10226
10227 // Add an additional bit if the signedness isn't uniformly agreed to. We
10228 // could do this ONLY if there is a signed and an unsigned that both have
10229 // MaxBits, but the code to check that is pretty nasty. The issue will be
10230 // caught in the shrink-to-result later anyway.
10231 if (IsSigned && !AllSigned)
10232 ++MaxBits;
10233
Erich Keanefc3dfd32019-05-30 21:35:32 +000010234 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
10235 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +000010236 Result = APSInt(MaxBits, !IsSigned);
10237 }
10238
10239 // Find largest int.
10240 switch (BuiltinOp) {
10241 default:
10242 llvm_unreachable("Invalid value for BuiltinOp");
10243 case Builtin::BI__builtin_add_overflow:
10244 case Builtin::BI__builtin_sadd_overflow:
10245 case Builtin::BI__builtin_saddl_overflow:
10246 case Builtin::BI__builtin_saddll_overflow:
10247 case Builtin::BI__builtin_uadd_overflow:
10248 case Builtin::BI__builtin_uaddl_overflow:
10249 case Builtin::BI__builtin_uaddll_overflow:
10250 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10251 : LHS.uadd_ov(RHS, DidOverflow);
10252 break;
10253 case Builtin::BI__builtin_sub_overflow:
10254 case Builtin::BI__builtin_ssub_overflow:
10255 case Builtin::BI__builtin_ssubl_overflow:
10256 case Builtin::BI__builtin_ssubll_overflow:
10257 case Builtin::BI__builtin_usub_overflow:
10258 case Builtin::BI__builtin_usubl_overflow:
10259 case Builtin::BI__builtin_usubll_overflow:
10260 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10261 : LHS.usub_ov(RHS, DidOverflow);
10262 break;
10263 case Builtin::BI__builtin_mul_overflow:
10264 case Builtin::BI__builtin_smul_overflow:
10265 case Builtin::BI__builtin_smull_overflow:
10266 case Builtin::BI__builtin_smulll_overflow:
10267 case Builtin::BI__builtin_umul_overflow:
10268 case Builtin::BI__builtin_umull_overflow:
10269 case Builtin::BI__builtin_umulll_overflow:
10270 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10271 : LHS.umul_ov(RHS, DidOverflow);
10272 break;
10273 }
10274
10275 // In the case where multiple sizes are allowed, truncate and see if
10276 // the values are the same.
10277 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10278 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10279 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10280 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10281 // since it will give us the behavior of a TruncOrSelf in the case where
10282 // its parameter <= its size. We previously set Result to be at least the
10283 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10284 // will work exactly like TruncOrSelf.
10285 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10286 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10287
10288 if (!APSInt::isSameValue(Temp, Result))
10289 DidOverflow = true;
10290 Result = Temp;
10291 }
10292
10293 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000010294 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10295 return false;
Erich Keane00958272018-06-13 20:43:27 +000010296 return Success(DidOverflow, E);
10297 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010298 }
Chris Lattner7174bf32008-07-12 00:38:25 +000010299}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000010300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010301/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000010302/// object referred to by the lvalue.
10303static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10304 const LValue &LV) {
10305 // A null pointer can be viewed as being "past the end" but we don't
10306 // choose to look at it that way here.
10307 if (!LV.getLValueBase())
10308 return false;
10309
10310 // If the designator is valid and refers to a subobject, we're not pointing
10311 // past the end.
10312 if (!LV.getLValueDesignator().Invalid &&
10313 !LV.getLValueDesignator().isOnePastTheEnd())
10314 return false;
10315
David Majnemerc378ca52015-08-29 08:32:55 +000010316 // A pointer to an incomplete type might be past-the-end if the type's size is
10317 // zero. We cannot tell because the type is incomplete.
10318 QualType Ty = getType(LV.getLValueBase());
10319 if (Ty->isIncompleteType())
10320 return true;
10321
Richard Smithd20f1e62014-10-21 23:01:04 +000010322 // We're a past-the-end pointer if we point to the byte after the object,
10323 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000010324 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000010325 return LV.getLValueOffset() == Size;
10326}
10327
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010328namespace {
Richard Smith11562c52011-10-28 17:51:58 +000010329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010330/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010331///
10332/// We use a data recursive algorithm for binary operators so that we are able
10333/// to handle extreme cases of chained binary operators without causing stack
10334/// overflow.
10335class DataRecursiveIntBinOpEvaluator {
10336 struct EvalResult {
10337 APValue Val;
10338 bool Failed;
10339
10340 EvalResult() : Failed(false) { }
10341
10342 void swap(EvalResult &RHS) {
10343 Val.swap(RHS.Val);
10344 Failed = RHS.Failed;
10345 RHS.Failed = false;
10346 }
10347 };
10348
10349 struct Job {
10350 const Expr *E;
10351 EvalResult LHSResult; // meaningful only for binary operator expression.
10352 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000010353
David Blaikie73726062015-08-12 23:09:24 +000010354 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000010355 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000010356
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010357 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000010358 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010359 }
George Burgess IV8c892b52016-05-25 22:31:54 +000010360
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010361 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000010362 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010363 };
10364
10365 SmallVector<Job, 16> Queue;
10366
10367 IntExprEvaluator &IntEval;
10368 EvalInfo &Info;
10369 APValue &FinalResult;
10370
10371public:
10372 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10373 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010375 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010376 /// data recursively.
10377 /// We handle binary operators that are comma, logical, or that have operands
10378 /// with integral or enumeration type.
10379 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010380 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10381 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000010382 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010383 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000010384 }
10385
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010386 bool Traverse(const BinaryOperator *E) {
10387 enqueue(E);
10388 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000010389 while (!Queue.empty())
10390 process(PrevResult);
10391
10392 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010393
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010394 FinalResult.swap(PrevResult.Val);
10395 return true;
10396 }
10397
10398private:
10399 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10400 return IntEval.Success(Value, E, Result);
10401 }
10402 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10403 return IntEval.Success(Value, E, Result);
10404 }
10405 bool Error(const Expr *E) {
10406 return IntEval.Error(E);
10407 }
10408 bool Error(const Expr *E, diag::kind D) {
10409 return IntEval.Error(E, D);
10410 }
10411
10412 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10413 return Info.CCEDiag(E, D);
10414 }
10415
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010416 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010417 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010418 bool &SuppressRHSDiags);
10419
10420 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10421 const BinaryOperator *E, APValue &Result);
10422
10423 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10424 Result.Failed = !Evaluate(Result.Val, Info, E);
10425 if (Result.Failed)
10426 Result.Val = APValue();
10427 }
10428
Richard Trieuba4d0872012-03-21 23:30:30 +000010429 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010430
10431 void enqueue(const Expr *E) {
10432 E = E->IgnoreParens();
10433 Queue.resize(Queue.size()+1);
10434 Queue.back().E = E;
10435 Queue.back().Kind = Job::AnyExprKind;
10436 }
10437};
10438
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010439}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010440
10441bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010442 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010443 bool &SuppressRHSDiags) {
10444 if (E->getOpcode() == BO_Comma) {
10445 // Ignore LHS but note if we could not evaluate it.
10446 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000010447 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010448 return true;
10449 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010450
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010451 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010452 bool LHSAsBool;
10453 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010454 // We were able to evaluate the LHS, see if we can get away with not
10455 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000010456 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10457 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010458 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010459 }
10460 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010461 LHSResult.Failed = true;
10462
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010463 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000010464 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000010465 if (!Info.noteSideEffect())
10466 return false;
10467
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010468 // We can't evaluate the LHS; however, sometimes the result
10469 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10470 // Don't ignore RHS and suppress diagnostics from this arm.
10471 SuppressRHSDiags = true;
10472 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010473
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010474 return true;
10475 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010476
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010477 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10478 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000010479
George Burgess IVa145e252016-05-25 22:38:36 +000010480 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010481 return false; // Ignore RHS;
10482
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010483 return true;
10484}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010485
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000010486static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10487 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000010488 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10489 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10490 // offsets.
10491 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10492 CharUnits &Offset = LVal.getLValueOffset();
10493 uint64_t Offset64 = Offset.getQuantity();
10494 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10495 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10496 : Offset64 + Index64);
10497}
10498
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010499bool DataRecursiveIntBinOpEvaluator::
10500 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10501 const BinaryOperator *E, APValue &Result) {
10502 if (E->getOpcode() == BO_Comma) {
10503 if (RHSResult.Failed)
10504 return false;
10505 Result = RHSResult.Val;
10506 return true;
10507 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010508
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010509 if (E->isLogicalOp()) {
10510 bool lhsResult, rhsResult;
10511 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10512 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000010513
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010514 if (LHSIsOK) {
10515 if (RHSIsOK) {
10516 if (E->getOpcode() == BO_LOr)
10517 return Success(lhsResult || rhsResult, E, Result);
10518 else
10519 return Success(lhsResult && rhsResult, E, Result);
10520 }
10521 } else {
10522 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010523 // We can't evaluate the LHS; however, sometimes the result
10524 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10525 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010526 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010527 }
10528 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010529
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010530 return false;
10531 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010532
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010533 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10534 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000010535
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010536 if (LHSResult.Failed || RHSResult.Failed)
10537 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010538
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010539 const APValue &LHSVal = LHSResult.Val;
10540 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000010541
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010542 // Handle cases like (unsigned long)&a + 4.
10543 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10544 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010545 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010546 return true;
10547 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010548
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010549 // Handle cases like 4 + (unsigned long)&a
10550 if (E->getOpcode() == BO_Add &&
10551 RHSVal.isLValue() && LHSVal.isInt()) {
10552 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010553 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010554 return true;
10555 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010556
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010557 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10558 // Handle (intptr_t)&&A - (intptr_t)&&B.
10559 if (!LHSVal.getLValueOffset().isZero() ||
10560 !RHSVal.getLValueOffset().isZero())
10561 return false;
10562 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10563 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10564 if (!LHSExpr || !RHSExpr)
10565 return false;
10566 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10567 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10568 if (!LHSAddrExpr || !RHSAddrExpr)
10569 return false;
10570 // Make sure both labels come from the same function.
10571 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10572 RHSAddrExpr->getLabel()->getDeclContext())
10573 return false;
10574 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10575 return true;
10576 }
Richard Smith43e77732013-05-07 04:50:00 +000010577
10578 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010579 if (!LHSVal.isInt() || !RHSVal.isInt())
10580 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000010581
10582 // Set up the width and signedness manually, in case it can't be deduced
10583 // from the operation we're performing.
10584 // FIXME: Don't do this in the cases where we can deduce it.
10585 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10586 E->getType()->isUnsignedIntegerOrEnumerationType());
10587 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10588 RHSVal.getInt(), Value))
10589 return false;
10590 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010591}
10592
Richard Trieuba4d0872012-03-21 23:30:30 +000010593void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010594 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000010595
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010596 switch (job.Kind) {
10597 case Job::AnyExprKind: {
10598 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10599 if (shouldEnqueue(Bop)) {
10600 job.Kind = Job::BinOpKind;
10601 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010602 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010603 }
10604 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010605
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010606 EvaluateExpr(job.E, Result);
10607 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010608 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010609 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010610
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010611 case Job::BinOpKind: {
10612 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010613 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010614 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010615 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010616 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010617 }
10618 if (SuppressRHSDiags)
10619 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010620 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010621 job.Kind = Job::BinOpVisitedLHSKind;
10622 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010623 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010624 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010625
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010626 case Job::BinOpVisitedLHSKind: {
10627 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10628 EvalResult RHS;
10629 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000010630 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010631 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010632 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010633 }
10634 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010635
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010636 llvm_unreachable("Invalid Job::Kind!");
10637}
10638
George Burgess IV8c892b52016-05-25 22:31:54 +000010639namespace {
10640/// Used when we determine that we should fail, but can keep evaluating prior to
10641/// noting that we had a failure.
10642class DelayedNoteFailureRAII {
10643 EvalInfo &Info;
10644 bool NoteFailure;
10645
10646public:
10647 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10648 : Info(Info), NoteFailure(NoteFailure) {}
10649 ~DelayedNoteFailureRAII() {
10650 if (NoteFailure) {
10651 bool ContinueAfterFailure = Info.noteFailure();
10652 (void)ContinueAfterFailure;
10653 assert(ContinueAfterFailure &&
10654 "Shouldn't have kept evaluating on failure.");
10655 }
10656 }
10657};
10658}
10659
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010660template <class SuccessCB, class AfterCB>
10661static bool
10662EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10663 SuccessCB &&Success, AfterCB &&DoAfter) {
10664 assert(E->isComparisonOp() && "expected comparison operator");
10665 assert((E->getOpcode() == BO_Cmp ||
10666 E->getType()->isIntegralOrEnumerationType()) &&
10667 "unsupported binary expression evaluation");
10668 auto Error = [&](const Expr *E) {
10669 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10670 return false;
10671 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010672
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010673 using CCR = ComparisonCategoryResult;
10674 bool IsRelational = E->isRelationalOp();
10675 bool IsEquality = E->isEqualityOp();
10676 if (E->getOpcode() == BO_Cmp) {
10677 const ComparisonCategoryInfo &CmpInfo =
10678 Info.Ctx.CompCategories.getInfoForType(E->getType());
10679 IsRelational = CmpInfo.isOrdered();
10680 IsEquality = CmpInfo.isEquality();
10681 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000010682
Anders Carlssonacc79812008-11-16 07:17:21 +000010683 QualType LHSTy = E->getLHS()->getType();
10684 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010685
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010686 if (LHSTy->isIntegralOrEnumerationType() &&
10687 RHSTy->isIntegralOrEnumerationType()) {
10688 APSInt LHS, RHS;
10689 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10690 if (!LHSOK && !Info.noteFailure())
10691 return false;
10692 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10693 return false;
10694 if (LHS < RHS)
10695 return Success(CCR::Less, E);
10696 if (LHS > RHS)
10697 return Success(CCR::Greater, E);
10698 return Success(CCR::Equal, E);
10699 }
10700
Leonard Chance1d4f12019-02-21 20:50:09 +000010701 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10702 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10703 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10704
10705 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10706 if (!LHSOK && !Info.noteFailure())
10707 return false;
10708 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10709 return false;
10710 if (LHSFX < RHSFX)
10711 return Success(CCR::Less, E);
10712 if (LHSFX > RHSFX)
10713 return Success(CCR::Greater, E);
10714 return Success(CCR::Equal, E);
10715 }
10716
Chandler Carruthb29a7432014-10-11 11:03:30 +000010717 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010718 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000010719 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000010720 if (E->isAssignmentOp()) {
10721 LValue LV;
10722 EvaluateLValue(E->getLHS(), LV, Info);
10723 LHSOK = false;
10724 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000010725 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10726 if (LHSOK) {
10727 LHS.makeComplexFloat();
10728 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10729 }
10730 } else {
10731 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10732 }
George Burgess IVa145e252016-05-25 22:38:36 +000010733 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010734 return false;
10735
Chandler Carruthb29a7432014-10-11 11:03:30 +000010736 if (E->getRHS()->getType()->isRealFloatingType()) {
10737 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10738 return false;
10739 RHS.makeComplexFloat();
10740 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10741 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010742 return false;
10743
10744 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000010745 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010746 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000010747 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010748 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010749 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10750 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010751 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010752 assert(IsEquality && "invalid complex comparison");
10753 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10754 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10755 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010756 }
10757 }
Mike Stump11289f42009-09-09 15:08:12 +000010758
Anders Carlssonacc79812008-11-16 07:17:21 +000010759 if (LHSTy->isRealFloatingType() &&
10760 RHSTy->isRealFloatingType()) {
10761 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010762
Richard Smith253c2a32012-01-27 01:14:48 +000010763 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010764 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010765 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010766
Richard Smith253c2a32012-01-27 01:14:48 +000010767 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010768 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010769
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010770 assert(E->isComparisonOp() && "Invalid binary operator!");
10771 auto GetCmpRes = [&]() {
10772 switch (LHS.compare(RHS)) {
10773 case APFloat::cmpEqual:
10774 return CCR::Equal;
10775 case APFloat::cmpLessThan:
10776 return CCR::Less;
10777 case APFloat::cmpGreaterThan:
10778 return CCR::Greater;
10779 case APFloat::cmpUnordered:
10780 return CCR::Unordered;
10781 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010782 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010783 };
10784 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010785 }
Mike Stump11289f42009-09-09 15:08:12 +000010786
Eli Friedmana38da572009-04-28 19:17:36 +000010787 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010788 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010789
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010790 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10791 if (!LHSOK && !Info.noteFailure())
10792 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010793
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010794 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10795 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010796
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010797 // Reject differing bases from the normal codepath; we special-case
10798 // comparisons to null.
10799 if (!HasSameBase(LHSValue, RHSValue)) {
10800 // Inequalities and subtractions between unrelated pointers have
10801 // unspecified or undefined behavior.
10802 if (!IsEquality)
10803 return Error(E);
10804 // A constant address may compare equal to the address of a symbol.
10805 // The one exception is that address of an object cannot compare equal
10806 // to a null pointer constant.
10807 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10808 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10809 return Error(E);
10810 // It's implementation-defined whether distinct literals will have
10811 // distinct addresses. In clang, the result of such a comparison is
10812 // unspecified, so it is not a constant expression. However, we do know
10813 // that the address of a literal will be non-null.
10814 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10815 LHSValue.Base && RHSValue.Base)
10816 return Error(E);
10817 // We can't tell whether weak symbols will end up pointing to the same
10818 // object.
10819 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10820 return Error(E);
10821 // We can't compare the address of the start of one object with the
10822 // past-the-end address of another object, per C++ DR1652.
10823 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10824 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10825 (RHSValue.Base && RHSValue.Offset.isZero() &&
10826 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10827 return Error(E);
10828 // We can't tell whether an object is at the same address as another
10829 // zero sized object.
10830 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10831 (LHSValue.Base && isZeroSized(RHSValue)))
10832 return Error(E);
10833 return Success(CCR::Nonequal, E);
10834 }
Eli Friedman64004332009-03-23 04:38:34 +000010835
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010836 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10837 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010838
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010839 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10840 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010841
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010842 // C++11 [expr.rel]p3:
10843 // Pointers to void (after pointer conversions) can be compared, with a
10844 // result defined as follows: If both pointers represent the same
10845 // address or are both the null pointer value, the result is true if the
10846 // operator is <= or >= and false otherwise; otherwise the result is
10847 // unspecified.
10848 // We interpret this as applying to pointers to *cv* void.
10849 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10850 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010851
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010852 // C++11 [expr.rel]p2:
10853 // - If two pointers point to non-static data members of the same object,
10854 // or to subobjects or array elements fo such members, recursively, the
10855 // pointer to the later declared member compares greater provided the
10856 // two members have the same access control and provided their class is
10857 // not a union.
10858 // [...]
10859 // - Otherwise pointer comparisons are unspecified.
10860 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10861 bool WasArrayIndex;
10862 unsigned Mismatch = FindDesignatorMismatch(
10863 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10864 // At the point where the designators diverge, the comparison has a
10865 // specified value if:
10866 // - we are comparing array indices
10867 // - we are comparing fields of a union, or fields with the same access
10868 // Otherwise, the result is unspecified and thus the comparison is not a
10869 // constant expression.
10870 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10871 Mismatch < RHSDesignator.Entries.size()) {
10872 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10873 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10874 if (!LF && !RF)
10875 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10876 else if (!LF)
10877 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010878 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10879 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010880 else if (!RF)
10881 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010882 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10883 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010884 else if (!LF->getParent()->isUnion() &&
10885 LF->getAccess() != RF->getAccess())
10886 Info.CCEDiag(E,
10887 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010888 << LF << LF->getAccess() << RF << RF->getAccess()
10889 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010890 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010891 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010892
10893 // The comparison here must be unsigned, and performed with the same
10894 // width as the pointer.
10895 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10896 uint64_t CompareLHS = LHSOffset.getQuantity();
10897 uint64_t CompareRHS = RHSOffset.getQuantity();
10898 assert(PtrSize <= 64 && "Unexpected pointer width");
10899 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10900 CompareLHS &= Mask;
10901 CompareRHS &= Mask;
10902
10903 // If there is a base and this is a relational operator, we can only
10904 // compare pointers within the object in question; otherwise, the result
10905 // depends on where the object is located in memory.
10906 if (!LHSValue.Base.isNull() && IsRelational) {
10907 QualType BaseTy = getType(LHSValue.Base);
10908 if (BaseTy->isIncompleteType())
10909 return Error(E);
10910 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10911 uint64_t OffsetLimit = Size.getQuantity();
10912 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10913 return Error(E);
10914 }
10915
10916 if (CompareLHS < CompareRHS)
10917 return Success(CCR::Less, E);
10918 if (CompareLHS > CompareRHS)
10919 return Success(CCR::Greater, E);
10920 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010921 }
Richard Smith7bb00672012-02-01 01:42:44 +000010922
10923 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010924 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010925 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10926
10927 MemberPtr LHSValue, RHSValue;
10928
10929 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010930 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010931 return false;
10932
10933 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10934 return false;
10935
10936 // C++11 [expr.eq]p2:
10937 // If both operands are null, they compare equal. Otherwise if only one is
10938 // null, they compare unequal.
10939 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10940 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010941 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010942 }
10943
10944 // Otherwise if either is a pointer to a virtual member function, the
10945 // result is unspecified.
10946 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10947 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010948 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010949 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10950 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010951 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010952
10953 // Otherwise they compare equal if and only if they would refer to the
10954 // same member of the same most derived object or the same subobject if
10955 // they were dereferenced with a hypothetical object of the associated
10956 // class type.
10957 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010958 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010959 }
10960
Richard Smithab44d9b2012-02-14 22:35:28 +000010961 if (LHSTy->isNullPtrType()) {
10962 assert(E->isComparisonOp() && "unexpected nullptr operation");
10963 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10964 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10965 // are compared, the result is true of the operator is <=, >= or ==, and
10966 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010967 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010968 }
10969
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010970 return DoAfter();
10971}
10972
10973bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10974 if (!CheckLiteralType(Info, E))
10975 return false;
10976
10977 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10978 const BinaryOperator *E) {
10979 // Evaluation succeeded. Lookup the information for the comparison category
10980 // type and fetch the VarDecl for the result.
10981 const ComparisonCategoryInfo &CmpInfo =
10982 Info.Ctx.CompCategories.getInfoForType(E->getType());
10983 const VarDecl *VD =
10984 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10985 // Check and evaluate the result as a constant expression.
10986 LValue LV;
10987 LV.set(VD);
10988 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10989 return false;
10990 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10991 };
10992 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10993 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10994 });
10995}
10996
10997bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10998 // We don't call noteFailure immediately because the assignment happens after
10999 // we evaluate LHS and RHS.
11000 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11001 return Error(E);
11002
11003 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11004 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11005 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11006
11007 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
11008 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011009 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011010
11011 if (E->isComparisonOp()) {
11012 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11013 // comparisons and then translating the result.
11014 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11015 const BinaryOperator *E) {
11016 using CCR = ComparisonCategoryResult;
11017 bool IsEqual = ResKind == CCR::Equal,
11018 IsLess = ResKind == CCR::Less,
11019 IsGreater = ResKind == CCR::Greater;
11020 auto Op = E->getOpcode();
11021 switch (Op) {
11022 default:
11023 llvm_unreachable("unsupported binary operator");
11024 case BO_EQ:
11025 case BO_NE:
11026 return Success(IsEqual == (Op == BO_EQ), E);
11027 case BO_LT: return Success(IsLess, E);
11028 case BO_GT: return Success(IsGreater, E);
11029 case BO_LE: return Success(IsEqual || IsLess, E);
11030 case BO_GE: return Success(IsEqual || IsGreater, E);
11031 }
11032 };
11033 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11034 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11035 });
11036 }
11037
11038 QualType LHSTy = E->getLHS()->getType();
11039 QualType RHSTy = E->getRHS()->getType();
11040
11041 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11042 E->getOpcode() == BO_Sub) {
11043 LValue LHSValue, RHSValue;
11044
11045 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11046 if (!LHSOK && !Info.noteFailure())
11047 return false;
11048
11049 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11050 return false;
11051
11052 // Reject differing bases from the normal codepath; we special-case
11053 // comparisons to null.
11054 if (!HasSameBase(LHSValue, RHSValue)) {
11055 // Handle &&A - &&B.
11056 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11057 return Error(E);
11058 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11059 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11060 if (!LHSExpr || !RHSExpr)
11061 return Error(E);
11062 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11063 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11064 if (!LHSAddrExpr || !RHSAddrExpr)
11065 return Error(E);
11066 // Make sure both labels come from the same function.
11067 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11068 RHSAddrExpr->getLabel()->getDeclContext())
11069 return Error(E);
11070 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11071 }
11072 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11073 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11074
11075 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11076 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11077
11078 // C++11 [expr.add]p6:
11079 // Unless both pointers point to elements of the same array object, or
11080 // one past the last element of the array object, the behavior is
11081 // undefined.
11082 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11083 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11084 RHSDesignator))
11085 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11086
11087 QualType Type = E->getLHS()->getType();
11088 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
11089
11090 CharUnits ElementSize;
11091 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11092 return false;
11093
11094 // As an extension, a type may have zero size (empty struct or union in
11095 // C, array of zero length). Pointer subtraction in such cases has
11096 // undefined behavior, so is not constant.
11097 if (ElementSize.isZero()) {
11098 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11099 << ElementType;
11100 return false;
11101 }
11102
11103 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11104 // and produce incorrect results when it overflows. Such behavior
11105 // appears to be non-conforming, but is common, so perhaps we should
11106 // assume the standard intended for such cases to be undefined behavior
11107 // and check for them.
11108
11109 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11110 // overflow in the final conversion to ptrdiff_t.
11111 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11112 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11113 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11114 false);
11115 APSInt TrueResult = (LHS - RHS) / ElemSize;
11116 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11117
11118 if (Result.extend(65) != TrueResult &&
11119 !HandleOverflow(Info, E, TrueResult, E->getType()))
11120 return false;
11121 return Success(Result, E);
11122 }
11123
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011124 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000011125}
11126
Peter Collingbournee190dee2011-03-11 19:24:49 +000011127/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11128/// a result as the expression's type.
11129bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11130 const UnaryExprOrTypeTraitExpr *E) {
11131 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000011132 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000011133 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000011134 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000011135 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11136 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011137 else
Richard Smith6822bd72018-10-26 19:26:45 +000011138 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11139 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011140 }
Eli Friedman64004332009-03-23 04:38:34 +000011141
Peter Collingbournee190dee2011-03-11 19:24:49 +000011142 case UETT_VecStep: {
11143 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000011144
Peter Collingbournee190dee2011-03-11 19:24:49 +000011145 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000011146 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000011147
Peter Collingbournee190dee2011-03-11 19:24:49 +000011148 // The vec_step built-in functions that take a 3-component
11149 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11150 if (n == 3)
11151 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000011152
Peter Collingbournee190dee2011-03-11 19:24:49 +000011153 return Success(n, E);
11154 } else
11155 return Success(1, E);
11156 }
11157
11158 case UETT_SizeOf: {
11159 QualType SrcTy = E->getTypeOfArgument();
11160 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11161 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000011162 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11163 SrcTy = Ref->getPointeeType();
11164
Richard Smithd62306a2011-11-10 06:34:14 +000011165 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000011166 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000011167 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000011168 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011169 }
Alexey Bataev00396512015-07-02 03:40:19 +000011170 case UETT_OpenMPRequiredSimdAlign:
11171 assert(E->isArgumentType());
11172 return Success(
11173 Info.Ctx.toCharUnitsFromBits(
11174 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11175 .getQuantity(),
11176 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011177 }
11178
11179 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000011180}
11181
Peter Collingbournee9200682011-05-13 03:29:01 +000011182bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011183 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000011184 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000011185 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011186 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000011187 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000011188 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000011189 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000011190 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000011191 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000011192 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000011193 APSInt IdxResult;
11194 if (!EvaluateInteger(Idx, IdxResult, Info))
11195 return false;
11196 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11197 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011198 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011199 CurrentType = AT->getElementType();
11200 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11201 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000011202 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000011203 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011204
James Y Knight7281c352015-12-29 22:31:18 +000011205 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000011206 FieldDecl *MemberDecl = ON.getField();
11207 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011208 if (!RT)
11209 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011210 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011211 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000011212 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000011213 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000011214 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000011215 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000011216 CurrentType = MemberDecl->getType().getNonReferenceType();
11217 break;
11218 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011219
James Y Knight7281c352015-12-29 22:31:18 +000011220 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000011221 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000011222
James Y Knight7281c352015-12-29 22:31:18 +000011223 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000011224 CXXBaseSpecifier *BaseSpec = ON.getBase();
11225 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000011226 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011227
11228 // Find the layout of the class whose base we are looking into.
11229 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011230 if (!RT)
11231 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000011232 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011233 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000011234 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11235
11236 // Find the base class itself.
11237 CurrentType = BaseSpec->getType();
11238 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
11239 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011240 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000011241
Douglas Gregord1702062010-04-29 00:18:15 +000011242 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000011243 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000011244 break;
11245 }
Douglas Gregor882211c2010-04-28 22:16:22 +000011246 }
11247 }
Peter Collingbournee9200682011-05-13 03:29:01 +000011248 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011249}
11250
Chris Lattnere13042c2008-07-11 19:10:17 +000011251bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011252 switch (E->getOpcode()) {
11253 default:
11254 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11255 // See C99 6.6p3.
11256 return Error(E);
11257 case UO_Extension:
11258 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11259 // If so, we could clear the diagnostic ID.
11260 return Visit(E->getSubExpr());
11261 case UO_Plus:
11262 // The result is just the value.
11263 return Visit(E->getSubExpr());
11264 case UO_Minus: {
11265 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000011266 return false;
11267 if (!Result.isInt()) return Error(E);
11268 const APSInt &Value = Result.getInt();
11269 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11270 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11271 E->getType()))
11272 return false;
Richard Smithfe800032012-01-31 04:08:20 +000011273 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011274 }
11275 case UO_Not: {
11276 if (!Visit(E->getSubExpr()))
11277 return false;
11278 if (!Result.isInt()) return Error(E);
11279 return Success(~Result.getInt(), E);
11280 }
11281 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000011282 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000011283 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000011284 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000011285 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000011286 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011287 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011288}
Mike Stump11289f42009-09-09 15:08:12 +000011289
Chris Lattner477c4be2008-07-12 01:15:53 +000011290/// HandleCast - This is used to evaluate implicit or explicit casts where the
11291/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000011292bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11293 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011294 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000011295 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011296
Eli Friedmanc757de22011-03-25 00:43:55 +000011297 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000011298 case CK_BaseToDerived:
11299 case CK_DerivedToBase:
11300 case CK_UncheckedDerivedToBase:
11301 case CK_Dynamic:
11302 case CK_ToUnion:
11303 case CK_ArrayToPointerDecay:
11304 case CK_FunctionToPointerDecay:
11305 case CK_NullToPointer:
11306 case CK_NullToMemberPointer:
11307 case CK_BaseToDerivedMemberPointer:
11308 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000011309 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000011310 case CK_ConstructorConversion:
11311 case CK_IntegralToPointer:
11312 case CK_ToVoid:
11313 case CK_VectorSplat:
11314 case CK_IntegralToFloating:
11315 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011316 case CK_CPointerToObjCPointerCast:
11317 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011318 case CK_AnyPointerToBlockPointerCast:
11319 case CK_ObjCObjectLValueCast:
11320 case CK_FloatingRealToComplex:
11321 case CK_FloatingComplexToReal:
11322 case CK_FloatingComplexCast:
11323 case CK_FloatingComplexToIntegralComplex:
11324 case CK_IntegralRealToComplex:
11325 case CK_IntegralComplexCast:
11326 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000011327 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011328 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011329 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011330 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011331 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011332 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011333 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000011334 llvm_unreachable("invalid cast kind for integral value");
11335
Eli Friedman9faf2f92011-03-25 19:07:11 +000011336 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011337 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011338 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000011339 case CK_ARCProduceObject:
11340 case CK_ARCConsumeObject:
11341 case CK_ARCReclaimReturnedObject:
11342 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011343 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011344 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011345
Richard Smith4ef685b2012-01-17 21:17:26 +000011346 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000011347 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011348 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000011349 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011350 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011351 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011352
11353 case CK_MemberPointerToBoolean:
11354 case CK_PointerToBoolean:
11355 case CK_IntegralToBoolean:
11356 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011357 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000011358 case CK_FloatingComplexToBoolean:
11359 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011360 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000011361 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000011362 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000011363 uint64_t IntResult = BoolResult;
11364 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11365 IntResult = (uint64_t)-1;
11366 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011367 }
11368
Leonard Chan8f7caae2019-03-06 00:28:43 +000011369 case CK_FixedPointToIntegral: {
11370 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11371 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11372 return false;
11373 bool Overflowed;
11374 llvm::APSInt Result = Src.convertToInt(
11375 Info.Ctx.getIntWidth(DestType),
11376 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11377 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11378 return false;
11379 return Success(Result, E);
11380 }
11381
Leonard Chanb4ba4672018-10-23 17:55:35 +000011382 case CK_FixedPointToBoolean: {
11383 // Unsigned padding does not affect this.
11384 APValue Val;
11385 if (!Evaluate(Val, Info, SubExpr))
11386 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011387 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000011388 }
11389
Eli Friedmanc757de22011-03-25 00:43:55 +000011390 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000011391 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000011392 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000011393
Eli Friedman742421e2009-02-20 01:15:07 +000011394 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000011395 // Allow casts of address-of-label differences if they are no-ops
11396 // or narrowing. (The narrowing case isn't actually guaranteed to
11397 // be constant-evaluatable except in some narrow cases which are hard
11398 // to detect here. We let it through on the assumption the user knows
11399 // what they are doing.)
11400 if (Result.isAddrLabelDiff())
11401 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000011402 // Only allow casts of lvalues if they are lossless.
11403 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11404 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000011405
Richard Smith911e1422012-01-30 22:27:01 +000011406 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11407 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000011408 }
Mike Stump11289f42009-09-09 15:08:12 +000011409
Eli Friedmanc757de22011-03-25 00:43:55 +000011410 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000011411 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11412
John McCall45d55e42010-05-07 21:00:08 +000011413 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000011414 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000011415 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000011416
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011417 if (LV.getLValueBase()) {
11418 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000011419 // FIXME: Allow a larger integer size than the pointer size, and allow
11420 // narrowing back down to pointer width in subsequent integral casts.
11421 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011422 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011423 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011424
Richard Smithcf74da72011-11-16 07:18:12 +000011425 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000011426 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011427 return true;
11428 }
11429
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000011430 APSInt AsInt;
11431 APValue V;
11432 LV.moveInto(V);
11433 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11434 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000011435
Richard Smith911e1422012-01-30 22:27:01 +000011436 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011437 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011438
Eli Friedmanc757de22011-03-25 00:43:55 +000011439 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000011440 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011441 if (!EvaluateComplex(SubExpr, C, Info))
11442 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000011443 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011444 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000011445
Eli Friedmanc757de22011-03-25 00:43:55 +000011446 case CK_FloatingToIntegral: {
11447 APFloat F(0.0);
11448 if (!EvaluateFloat(SubExpr, F, Info))
11449 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000011450
Richard Smith357362d2011-12-13 06:39:58 +000011451 APSInt Value;
11452 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11453 return false;
11454 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011455 }
11456 }
Mike Stump11289f42009-09-09 15:08:12 +000011457
Eli Friedmanc757de22011-03-25 00:43:55 +000011458 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000011459}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011460
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011461bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11462 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011463 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011464 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11465 return false;
11466 if (!LV.isComplexInt())
11467 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011468 return Success(LV.getComplexIntReal(), E);
11469 }
11470
11471 return Visit(E->getSubExpr());
11472}
11473
Eli Friedman4e7a2412009-02-27 04:45:43 +000011474bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011475 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011476 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011477 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11478 return false;
11479 if (!LV.isComplexInt())
11480 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011481 return Success(LV.getComplexIntImag(), E);
11482 }
11483
Richard Smith4a678122011-10-24 18:44:57 +000011484 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000011485 return Success(0, E);
11486}
11487
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011488bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11489 return Success(E->getPackLength(), E);
11490}
11491
Sebastian Redl5f0180d2010-09-10 20:55:47 +000011492bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11493 return Success(E->getValue(), E);
11494}
11495
Leonard Chandb01c3a2018-06-20 17:19:40 +000011496bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11497 switch (E->getOpcode()) {
11498 default:
11499 // Invalid unary operators
11500 return Error(E);
11501 case UO_Plus:
11502 // The result is just the value.
11503 return Visit(E->getSubExpr());
11504 case UO_Minus: {
11505 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011506 if (!Result.isFixedPoint())
11507 return Error(E);
11508 bool Overflowed;
11509 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11510 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11511 return false;
11512 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011513 }
11514 case UO_LNot: {
11515 bool bres;
11516 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11517 return false;
11518 return Success(!bres, E);
11519 }
11520 }
11521}
11522
Leonard Chand3f3e162019-01-18 21:04:25 +000011523bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11524 const Expr *SubExpr = E->getSubExpr();
11525 QualType DestType = E->getType();
11526 assert(DestType->isFixedPointType() &&
11527 "Expected destination type to be a fixed point type");
11528 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11529
11530 switch (E->getCastKind()) {
11531 case CK_FixedPointCast: {
11532 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11533 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11534 return false;
11535 bool Overflowed;
11536 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11537 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11538 return false;
11539 return Success(Result, E);
11540 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011541 case CK_IntegralToFixedPoint: {
11542 APSInt Src;
11543 if (!EvaluateInteger(SubExpr, Src, Info))
11544 return false;
11545
11546 bool Overflowed;
11547 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11548 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11549
11550 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11551 return false;
11552
11553 return Success(IntResult, E);
11554 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011555 case CK_NoOp:
11556 case CK_LValueToRValue:
11557 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11558 default:
11559 return Error(E);
11560 }
11561}
11562
11563bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11564 const Expr *LHS = E->getLHS();
11565 const Expr *RHS = E->getRHS();
11566 FixedPointSemantics ResultFXSema =
11567 Info.Ctx.getFixedPointSemantics(E->getType());
11568
11569 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11570 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11571 return false;
11572 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11573 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11574 return false;
11575
11576 switch (E->getOpcode()) {
11577 case BO_Add: {
11578 bool AddOverflow, ConversionOverflow;
11579 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11580 .convert(ResultFXSema, &ConversionOverflow);
11581 if ((AddOverflow || ConversionOverflow) &&
11582 !HandleOverflow(Info, E, Result, E->getType()))
11583 return false;
11584 return Success(Result, E);
11585 }
11586 default:
11587 return false;
11588 }
11589 llvm_unreachable("Should've exited before this");
11590}
11591
Chris Lattner05706e882008-07-11 18:11:29 +000011592//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000011593// Float Evaluation
11594//===----------------------------------------------------------------------===//
11595
11596namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011597class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011598 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000011599 APFloat &Result;
11600public:
11601 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011602 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000011603
Richard Smith2e312c82012-03-03 22:46:17 +000011604 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011605 Result = V.getFloat();
11606 return true;
11607 }
Eli Friedman24c01542008-08-22 00:06:13 +000011608
Richard Smithfddd3842011-12-30 21:15:51 +000011609 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000011610 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11611 return true;
11612 }
11613
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011614 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011615
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011616 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011617 bool VisitBinaryOperator(const BinaryOperator *E);
11618 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011619 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000011620
John McCallb1fb0d32010-05-07 22:08:54 +000011621 bool VisitUnaryReal(const UnaryOperator *E);
11622 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000011623
Richard Smithfddd3842011-12-30 21:15:51 +000011624 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000011625};
11626} // end anonymous namespace
11627
11628static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011629 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011630 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000011631}
11632
Jay Foad39c79802011-01-12 09:06:06 +000011633static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000011634 QualType ResultTy,
11635 const Expr *Arg,
11636 bool SNaN,
11637 llvm::APFloat &Result) {
11638 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11639 if (!S) return false;
11640
11641 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11642
11643 llvm::APInt fill;
11644
11645 // Treat empty strings as if they were zero.
11646 if (S->getString().empty())
11647 fill = llvm::APInt(32, 0);
11648 else if (S->getString().getAsInteger(0, fill))
11649 return false;
11650
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000011651 if (Context.getTargetInfo().isNan2008()) {
11652 if (SNaN)
11653 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11654 else
11655 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11656 } else {
11657 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11658 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11659 // a different encoding to what became a standard in 2008, and for pre-
11660 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11661 // sNaN. This is now known as "legacy NaN" encoding.
11662 if (SNaN)
11663 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11664 else
11665 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11666 }
11667
John McCall16291492010-02-28 13:00:19 +000011668 return true;
11669}
11670
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011671bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000011672 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011673 default:
11674 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11675
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011676 case Builtin::BI__builtin_huge_val:
11677 case Builtin::BI__builtin_huge_valf:
11678 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011679 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011680 case Builtin::BI__builtin_inf:
11681 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011682 case Builtin::BI__builtin_infl:
11683 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011684 const llvm::fltSemantics &Sem =
11685 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000011686 Result = llvm::APFloat::getInf(Sem);
11687 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011688 }
Mike Stump11289f42009-09-09 15:08:12 +000011689
John McCall16291492010-02-28 13:00:19 +000011690 case Builtin::BI__builtin_nans:
11691 case Builtin::BI__builtin_nansf:
11692 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011693 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011694 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11695 true, Result))
11696 return Error(E);
11697 return true;
John McCall16291492010-02-28 13:00:19 +000011698
Chris Lattner0b7282e2008-10-06 06:31:58 +000011699 case Builtin::BI__builtin_nan:
11700 case Builtin::BI__builtin_nanf:
11701 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011702 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000011703 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000011704 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000011705 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11706 false, Result))
11707 return Error(E);
11708 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011709
11710 case Builtin::BI__builtin_fabs:
11711 case Builtin::BI__builtin_fabsf:
11712 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011713 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011714 if (!EvaluateFloat(E->getArg(0), Result, Info))
11715 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011716
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011717 if (Result.isNegative())
11718 Result.changeSign();
11719 return true;
11720
Richard Smith8889a3d2013-06-13 06:26:32 +000011721 // FIXME: Builtin::BI__builtin_powi
11722 // FIXME: Builtin::BI__builtin_powif
11723 // FIXME: Builtin::BI__builtin_powil
11724
Mike Stump11289f42009-09-09 15:08:12 +000011725 case Builtin::BI__builtin_copysign:
11726 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011727 case Builtin::BI__builtin_copysignl:
11728 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011729 APFloat RHS(0.);
11730 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11731 !EvaluateFloat(E->getArg(1), RHS, Info))
11732 return false;
11733 Result.copySign(RHS);
11734 return true;
11735 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011736 }
11737}
11738
John McCallb1fb0d32010-05-07 22:08:54 +000011739bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011740 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11741 ComplexValue CV;
11742 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11743 return false;
11744 Result = CV.FloatReal;
11745 return true;
11746 }
11747
11748 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000011749}
11750
11751bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011752 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11753 ComplexValue CV;
11754 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11755 return false;
11756 Result = CV.FloatImag;
11757 return true;
11758 }
11759
Richard Smith4a678122011-10-24 18:44:57 +000011760 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011761 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11762 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011763 return true;
11764}
11765
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011766bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011767 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011768 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011769 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011770 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011771 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011772 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11773 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011774 Result.changeSign();
11775 return true;
11776 }
11777}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011778
Eli Friedman24c01542008-08-22 00:06:13 +000011779bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011780 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11781 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011782
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011783 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011784 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011785 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011786 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011787 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11788 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011789}
11790
11791bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11792 Result = E->getValue();
11793 return true;
11794}
11795
Peter Collingbournee9200682011-05-13 03:29:01 +000011796bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11797 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011798
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011799 switch (E->getCastKind()) {
11800 default:
Richard Smith11562c52011-10-28 17:51:58 +000011801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011802
11803 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011804 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011805 return EvaluateInteger(SubExpr, IntResult, Info) &&
11806 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11807 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011808 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011809
11810 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011811 if (!Visit(SubExpr))
11812 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011813 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11814 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011815 }
John McCalld7646252010-11-14 08:17:51 +000011816
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011817 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011818 ComplexValue V;
11819 if (!EvaluateComplex(SubExpr, V, Info))
11820 return false;
11821 Result = V.getComplexFloatReal();
11822 return true;
11823 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011824 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011825}
11826
Eli Friedman24c01542008-08-22 00:06:13 +000011827//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011828// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011829//===----------------------------------------------------------------------===//
11830
11831namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011832class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011833 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011834 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011835
Anders Carlsson537969c2008-11-16 20:27:53 +000011836public:
John McCall93d91dc2010-05-07 17:22:02 +000011837 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011838 : ExprEvaluatorBaseTy(info), Result(Result) {}
11839
Richard Smith2e312c82012-03-03 22:46:17 +000011840 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011841 Result.setFrom(V);
11842 return true;
11843 }
Mike Stump11289f42009-09-09 15:08:12 +000011844
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011845 bool ZeroInitialization(const Expr *E);
11846
Anders Carlsson537969c2008-11-16 20:27:53 +000011847 //===--------------------------------------------------------------------===//
11848 // Visitor Methods
11849 //===--------------------------------------------------------------------===//
11850
Peter Collingbournee9200682011-05-13 03:29:01 +000011851 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011852 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011853 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011854 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011855 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011856};
11857} // end anonymous namespace
11858
John McCall93d91dc2010-05-07 17:22:02 +000011859static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11860 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011861 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011862 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011863}
11864
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011865bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011866 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011867 if (ElemTy->isRealFloatingType()) {
11868 Result.makeComplexFloat();
11869 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11870 Result.FloatReal = Zero;
11871 Result.FloatImag = Zero;
11872 } else {
11873 Result.makeComplexInt();
11874 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11875 Result.IntReal = Zero;
11876 Result.IntImag = Zero;
11877 }
11878 return true;
11879}
11880
Peter Collingbournee9200682011-05-13 03:29:01 +000011881bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11882 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011883
11884 if (SubExpr->getType()->isRealFloatingType()) {
11885 Result.makeComplexFloat();
11886 APFloat &Imag = Result.FloatImag;
11887 if (!EvaluateFloat(SubExpr, Imag, Info))
11888 return false;
11889
11890 Result.FloatReal = APFloat(Imag.getSemantics());
11891 return true;
11892 } else {
11893 assert(SubExpr->getType()->isIntegerType() &&
11894 "Unexpected imaginary literal.");
11895
11896 Result.makeComplexInt();
11897 APSInt &Imag = Result.IntImag;
11898 if (!EvaluateInteger(SubExpr, Imag, Info))
11899 return false;
11900
11901 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11902 return true;
11903 }
11904}
11905
Peter Collingbournee9200682011-05-13 03:29:01 +000011906bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011907
John McCallfcef3cf2010-12-14 17:51:41 +000011908 switch (E->getCastKind()) {
11909 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011910 case CK_BaseToDerived:
11911 case CK_DerivedToBase:
11912 case CK_UncheckedDerivedToBase:
11913 case CK_Dynamic:
11914 case CK_ToUnion:
11915 case CK_ArrayToPointerDecay:
11916 case CK_FunctionToPointerDecay:
11917 case CK_NullToPointer:
11918 case CK_NullToMemberPointer:
11919 case CK_BaseToDerivedMemberPointer:
11920 case CK_DerivedToBaseMemberPointer:
11921 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011922 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011923 case CK_ConstructorConversion:
11924 case CK_IntegralToPointer:
11925 case CK_PointerToIntegral:
11926 case CK_PointerToBoolean:
11927 case CK_ToVoid:
11928 case CK_VectorSplat:
11929 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011930 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011931 case CK_IntegralToBoolean:
11932 case CK_IntegralToFloating:
11933 case CK_FloatingToIntegral:
11934 case CK_FloatingToBoolean:
11935 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011936 case CK_CPointerToObjCPointerCast:
11937 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011938 case CK_AnyPointerToBlockPointerCast:
11939 case CK_ObjCObjectLValueCast:
11940 case CK_FloatingComplexToReal:
11941 case CK_FloatingComplexToBoolean:
11942 case CK_IntegralComplexToReal:
11943 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011944 case CK_ARCProduceObject:
11945 case CK_ARCConsumeObject:
11946 case CK_ARCReclaimReturnedObject:
11947 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011948 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011949 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011950 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011951 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011952 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011953 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011954 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011955 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011956 case CK_FixedPointToIntegral:
11957 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011958 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011959
John McCallfcef3cf2010-12-14 17:51:41 +000011960 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011961 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011962 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011963 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011964 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011965
11966 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011967 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011968 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011969 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011970
11971 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011972 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011973 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011974 return false;
11975
John McCallfcef3cf2010-12-14 17:51:41 +000011976 Result.makeComplexFloat();
11977 Result.FloatImag = APFloat(Real.getSemantics());
11978 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011979 }
11980
John McCallfcef3cf2010-12-14 17:51:41 +000011981 case CK_FloatingComplexCast: {
11982 if (!Visit(E->getSubExpr()))
11983 return false;
11984
11985 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11986 QualType From
11987 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11988
Richard Smith357362d2011-12-13 06:39:58 +000011989 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11990 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011991 }
11992
11993 case CK_FloatingComplexToIntegralComplex: {
11994 if (!Visit(E->getSubExpr()))
11995 return false;
11996
11997 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11998 QualType From
11999 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12000 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000012001 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12002 To, Result.IntReal) &&
12003 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12004 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012005 }
12006
12007 case CK_IntegralRealToComplex: {
12008 APSInt &Real = Result.IntReal;
12009 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12010 return false;
12011
12012 Result.makeComplexInt();
12013 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12014 return true;
12015 }
12016
12017 case CK_IntegralComplexCast: {
12018 if (!Visit(E->getSubExpr()))
12019 return false;
12020
12021 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12022 QualType From
12023 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12024
Richard Smith911e1422012-01-30 22:27:01 +000012025 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12026 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012027 return true;
12028 }
12029
12030 case CK_IntegralComplexToFloatingComplex: {
12031 if (!Visit(E->getSubExpr()))
12032 return false;
12033
Ted Kremenek28831752012-08-23 20:46:57 +000012034 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012035 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000012036 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012037 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000012038 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12039 To, Result.FloatReal) &&
12040 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12041 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012042 }
12043 }
12044
12045 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012046}
12047
John McCall93d91dc2010-05-07 17:22:02 +000012048bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012049 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000012050 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12051
Chandler Carrutha216cad2014-10-11 00:57:18 +000012052 // Track whether the LHS or RHS is real at the type system level. When this is
12053 // the case we can simplify our evaluation strategy.
12054 bool LHSReal = false, RHSReal = false;
12055
12056 bool LHSOK;
12057 if (E->getLHS()->getType()->isRealFloatingType()) {
12058 LHSReal = true;
12059 APFloat &Real = Result.FloatReal;
12060 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12061 if (LHSOK) {
12062 Result.makeComplexFloat();
12063 Result.FloatImag = APFloat(Real.getSemantics());
12064 }
12065 } else {
12066 LHSOK = Visit(E->getLHS());
12067 }
George Burgess IVa145e252016-05-25 22:38:36 +000012068 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000012069 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012070
John McCall93d91dc2010-05-07 17:22:02 +000012071 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012072 if (E->getRHS()->getType()->isRealFloatingType()) {
12073 RHSReal = true;
12074 APFloat &Real = RHS.FloatReal;
12075 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12076 return false;
12077 RHS.makeComplexFloat();
12078 RHS.FloatImag = APFloat(Real.getSemantics());
12079 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000012080 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012081
Chandler Carrutha216cad2014-10-11 00:57:18 +000012082 assert(!(LHSReal && RHSReal) &&
12083 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012084 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012085 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012086 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012087 if (Result.isComplexFloat()) {
12088 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12089 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012090 if (LHSReal)
12091 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12092 else if (!RHSReal)
12093 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12094 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012095 } else {
12096 Result.getComplexIntReal() += RHS.getComplexIntReal();
12097 Result.getComplexIntImag() += RHS.getComplexIntImag();
12098 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012099 break;
John McCalle3027922010-08-25 11:45:40 +000012100 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012101 if (Result.isComplexFloat()) {
12102 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12103 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012104 if (LHSReal) {
12105 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12106 Result.getComplexFloatImag().changeSign();
12107 } else if (!RHSReal) {
12108 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12109 APFloat::rmNearestTiesToEven);
12110 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012111 } else {
12112 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12113 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12114 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012115 break;
John McCalle3027922010-08-25 11:45:40 +000012116 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012117 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012118 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012119 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012120 // following naming scheme:
12121 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000012122 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012123 APFloat &A = LHS.getComplexFloatReal();
12124 APFloat &B = LHS.getComplexFloatImag();
12125 APFloat &C = RHS.getComplexFloatReal();
12126 APFloat &D = RHS.getComplexFloatImag();
12127 APFloat &ResR = Result.getComplexFloatReal();
12128 APFloat &ResI = Result.getComplexFloatImag();
12129 if (LHSReal) {
12130 assert(!RHSReal && "Cannot have two real operands for a complex op!");
12131 ResR = A * C;
12132 ResI = A * D;
12133 } else if (RHSReal) {
12134 ResR = C * A;
12135 ResI = C * B;
12136 } else {
12137 // In the fully general case, we need to handle NaNs and infinities
12138 // robustly.
12139 APFloat AC = A * C;
12140 APFloat BD = B * D;
12141 APFloat AD = A * D;
12142 APFloat BC = B * C;
12143 ResR = AC - BD;
12144 ResI = AD + BC;
12145 if (ResR.isNaN() && ResI.isNaN()) {
12146 bool Recalc = false;
12147 if (A.isInfinity() || B.isInfinity()) {
12148 A = APFloat::copySign(
12149 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12150 B = APFloat::copySign(
12151 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12152 if (C.isNaN())
12153 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12154 if (D.isNaN())
12155 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12156 Recalc = true;
12157 }
12158 if (C.isInfinity() || D.isInfinity()) {
12159 C = APFloat::copySign(
12160 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12161 D = APFloat::copySign(
12162 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12163 if (A.isNaN())
12164 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12165 if (B.isNaN())
12166 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12167 Recalc = true;
12168 }
12169 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12170 AD.isInfinity() || BC.isInfinity())) {
12171 if (A.isNaN())
12172 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12173 if (B.isNaN())
12174 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12175 if (C.isNaN())
12176 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12177 if (D.isNaN())
12178 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12179 Recalc = true;
12180 }
12181 if (Recalc) {
12182 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12183 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12184 }
12185 }
12186 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012187 } else {
John McCall93d91dc2010-05-07 17:22:02 +000012188 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000012189 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012190 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12191 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000012192 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012193 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12194 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12195 }
12196 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012197 case BO_Div:
12198 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012199 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012200 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012201 // following naming scheme:
12202 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012203 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012204 APFloat &A = LHS.getComplexFloatReal();
12205 APFloat &B = LHS.getComplexFloatImag();
12206 APFloat &C = RHS.getComplexFloatReal();
12207 APFloat &D = RHS.getComplexFloatImag();
12208 APFloat &ResR = Result.getComplexFloatReal();
12209 APFloat &ResI = Result.getComplexFloatImag();
12210 if (RHSReal) {
12211 ResR = A / C;
12212 ResI = B / C;
12213 } else {
12214 if (LHSReal) {
12215 // No real optimizations we can do here, stub out with zero.
12216 B = APFloat::getZero(A.getSemantics());
12217 }
12218 int DenomLogB = 0;
12219 APFloat MaxCD = maxnum(abs(C), abs(D));
12220 if (MaxCD.isFinite()) {
12221 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000012222 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
12223 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012224 }
12225 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000012226 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
12227 APFloat::rmNearestTiesToEven);
12228 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
12229 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012230 if (ResR.isNaN() && ResI.isNaN()) {
12231 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
12232 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
12233 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
12234 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
12235 D.isFinite()) {
12236 A = APFloat::copySign(
12237 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12238 B = APFloat::copySign(
12239 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12240 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
12241 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
12242 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
12243 C = APFloat::copySign(
12244 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12245 D = APFloat::copySign(
12246 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12247 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
12248 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12249 }
12250 }
12251 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012252 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012253 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12254 return Error(E, diag::note_expr_divide_by_zero);
12255
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012256 ComplexValue LHS = Result;
12257 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12258 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12259 Result.getComplexIntReal() =
12260 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12261 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12262 Result.getComplexIntImag() =
12263 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12264 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12265 }
12266 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012267 }
12268
John McCall93d91dc2010-05-07 17:22:02 +000012269 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012270}
12271
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012272bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12273 // Get the operand value into 'Result'.
12274 if (!Visit(E->getSubExpr()))
12275 return false;
12276
12277 switch (E->getOpcode()) {
12278 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012279 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012280 case UO_Extension:
12281 return true;
12282 case UO_Plus:
12283 // The result is always just the subexpr.
12284 return true;
12285 case UO_Minus:
12286 if (Result.isComplexFloat()) {
12287 Result.getComplexFloatReal().changeSign();
12288 Result.getComplexFloatImag().changeSign();
12289 }
12290 else {
12291 Result.getComplexIntReal() = -Result.getComplexIntReal();
12292 Result.getComplexIntImag() = -Result.getComplexIntImag();
12293 }
12294 return true;
12295 case UO_Not:
12296 if (Result.isComplexFloat())
12297 Result.getComplexFloatImag().changeSign();
12298 else
12299 Result.getComplexIntImag() = -Result.getComplexIntImag();
12300 return true;
12301 }
12302}
12303
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012304bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12305 if (E->getNumInits() == 2) {
12306 if (E->getType()->isComplexType()) {
12307 Result.makeComplexFloat();
12308 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12309 return false;
12310 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12311 return false;
12312 } else {
12313 Result.makeComplexInt();
12314 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12315 return false;
12316 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12317 return false;
12318 }
12319 return true;
12320 }
12321 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12322}
12323
Anders Carlsson537969c2008-11-16 20:27:53 +000012324//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000012325// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12326// implicit conversion.
12327//===----------------------------------------------------------------------===//
12328
12329namespace {
12330class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000012331 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012332 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000012333 APValue &Result;
12334public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012335 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12336 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000012337
12338 bool Success(const APValue &V, const Expr *E) {
12339 Result = V;
12340 return true;
12341 }
12342
12343 bool ZeroInitialization(const Expr *E) {
12344 ImplicitValueInitExpr VIE(
12345 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012346 // For atomic-qualified class (and array) types in C++, initialize the
12347 // _Atomic-wrapped subobject directly, in-place.
12348 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12349 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000012350 }
12351
12352 bool VisitCastExpr(const CastExpr *E) {
12353 switch (E->getCastKind()) {
12354 default:
12355 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12356 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012357 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12358 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000012359 }
12360 }
12361};
12362} // end anonymous namespace
12363
Richard Smith64cb9ca2017-02-22 22:09:50 +000012364static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12365 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000012366 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012367 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000012368}
12369
12370//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000012371// Void expression evaluation, primarily for a cast to void on the LHS of a
12372// comma operator
12373//===----------------------------------------------------------------------===//
12374
12375namespace {
12376class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012377 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000012378public:
12379 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12380
Richard Smith2e312c82012-03-03 22:46:17 +000012381 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000012382
Richard Smith7cd577b2017-08-17 19:35:50 +000012383 bool ZeroInitialization(const Expr *E) { return true; }
12384
Richard Smith42d3af92011-12-07 00:43:50 +000012385 bool VisitCastExpr(const CastExpr *E) {
12386 switch (E->getCastKind()) {
12387 default:
12388 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12389 case CK_ToVoid:
12390 VisitIgnoredValue(E->getSubExpr());
12391 return true;
12392 }
12393 }
Hal Finkela8443c32014-07-17 14:49:58 +000012394
12395 bool VisitCallExpr(const CallExpr *E) {
12396 switch (E->getBuiltinCallee()) {
12397 default:
12398 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12399 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000012400 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000012401 // The argument is not evaluated!
12402 return true;
12403 }
12404 }
Richard Smith42d3af92011-12-07 00:43:50 +000012405};
12406} // end anonymous namespace
12407
12408static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12409 assert(E->isRValue() && E->getType()->isVoidType());
12410 return VoidExprEvaluator(Info).Visit(E);
12411}
12412
12413//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000012414// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000012415//===----------------------------------------------------------------------===//
12416
Richard Smith2e312c82012-03-03 22:46:17 +000012417static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000012418 // In C, function designators are not lvalues, but we evaluate them as if they
12419 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000012420 QualType T = E->getType();
12421 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000012422 LValue LV;
12423 if (!EvaluateLValue(E, LV, Info))
12424 return false;
12425 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012426 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012427 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000012428 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012429 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012430 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012431 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012432 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000012433 LValue LV;
12434 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012435 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012436 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012437 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000012438 llvm::APFloat F(0.0);
12439 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012440 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000012441 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000012442 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000012443 ComplexValue C;
12444 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012445 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012446 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012447 } else if (T->isFixedPointType()) {
12448 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012449 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000012450 MemberPtr P;
12451 if (!EvaluateMemberPointer(E, P, Info))
12452 return false;
12453 P.moveInto(Result);
12454 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000012455 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012456 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012457 APValue &Value =
12458 Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012459 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000012460 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012461 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012462 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012463 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012464 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012465 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000012466 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012467 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012468 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012469 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000012470 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000012471 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000012472 if (!EvaluateVoid(E, Info))
12473 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012474 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012475 QualType Unqual = T.getAtomicUnqualifiedType();
12476 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12477 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012478 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012479 if (!EvaluateAtomic(E, &LV, Value, Info))
12480 return false;
12481 } else {
12482 if (!EvaluateAtomic(E, nullptr, Result, Info))
12483 return false;
12484 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012485 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000012486 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000012487 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012488 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000012489 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000012490 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012491 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012492
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000012493 return true;
12494}
12495
Richard Smithb228a862012-02-15 02:18:13 +000012496/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12497/// cases, the in-place evaluation is essential, since later initializers for
12498/// an object can indirectly refer to subobjects which were initialized earlier.
12499static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000012500 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000012501 assert(!E->isValueDependent());
12502
Richard Smith7525ff62013-05-09 07:14:00 +000012503 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000012504 return false;
12505
12506 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000012507 // Evaluate arrays and record types in-place, so that later initializers can
12508 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000012509 QualType T = E->getType();
12510 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000012511 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012512 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000012513 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012514 else if (T->isAtomicType()) {
12515 QualType Unqual = T.getAtomicUnqualifiedType();
12516 if (Unqual->isArrayType() || Unqual->isRecordType())
12517 return EvaluateAtomic(E, &This, Result, Info);
12518 }
Richard Smithed5165f2011-11-04 05:33:44 +000012519 }
12520
12521 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000012522 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000012523}
12524
Richard Smithf57d8cb2011-12-09 22:58:01 +000012525/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12526/// lvalue-to-rvalue cast if it is an lvalue.
12527static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Licker950b70d2019-09-13 09:46:16 +000012528 if (Info.EnableNewConstInterp) {
12529 auto &InterpCtx = Info.Ctx.getInterpContext();
12530 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
12531 case interp::InterpResult::Success:
12532 return true;
12533 case interp::InterpResult::Fail:
12534 return false;
12535 case interp::InterpResult::Bail:
12536 break;
12537 }
12538 }
12539
James Dennett0492ef02014-03-14 17:44:10 +000012540 if (E->getType().isNull())
12541 return false;
12542
Nick Lewyckyc190f962017-05-02 01:06:16 +000012543 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000012544 return false;
12545
Richard Smith2e312c82012-03-03 22:46:17 +000012546 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012547 return false;
12548
12549 if (E->isGLValue()) {
12550 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000012551 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000012552 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012553 return false;
12554 }
12555
Richard Smith2e312c82012-03-03 22:46:17 +000012556 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000012557 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012558}
Richard Smith11562c52011-10-28 17:51:58 +000012559
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012560static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000012561 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012562 // Fast-path evaluations of integer literals, since we sometimes see files
12563 // containing vast quantities of these.
12564 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12565 Result.Val = APValue(APSInt(L->getValue(),
12566 L->getType()->isUnsignedIntegerType()));
12567 IsConst = true;
12568 return true;
12569 }
James Dennett0492ef02014-03-14 17:44:10 +000012570
12571 // This case should be rare, but we need to check it before we check on
12572 // the type below.
12573 if (Exp->getType().isNull()) {
12574 IsConst = false;
12575 return true;
12576 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012577
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012578 // FIXME: Evaluating values of large array and record types can cause
12579 // performance problems. Only do so in C++11 for now.
12580 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12581 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000012582 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012583 IsConst = false;
12584 return true;
12585 }
12586 return false;
12587}
12588
Fangrui Song407659a2018-11-30 23:41:18 +000012589static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12590 Expr::SideEffectsKind SEK) {
12591 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12592 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12593}
12594
12595static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12596 const ASTContext &Ctx, EvalInfo &Info) {
12597 bool IsConst;
12598 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12599 return IsConst;
12600
12601 return EvaluateAsRValue(Info, E, Result.Val);
12602}
12603
12604static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12605 const ASTContext &Ctx,
12606 Expr::SideEffectsKind AllowSideEffects,
12607 EvalInfo &Info) {
12608 if (!E->getType()->isIntegralOrEnumerationType())
12609 return false;
12610
12611 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12612 !ExprResult.Val.isInt() ||
12613 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12614 return false;
12615
12616 return true;
12617}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012618
Leonard Chand3f3e162019-01-18 21:04:25 +000012619static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12620 const ASTContext &Ctx,
12621 Expr::SideEffectsKind AllowSideEffects,
12622 EvalInfo &Info) {
12623 if (!E->getType()->isFixedPointType())
12624 return false;
12625
12626 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12627 return false;
12628
12629 if (!ExprResult.Val.isFixedPoint() ||
12630 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12631 return false;
12632
12633 return true;
12634}
12635
Richard Smith7b553f12011-10-29 00:50:52 +000012636/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000012637/// any crazy technique (that has nothing to do with language standards) that
12638/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000012639/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12640/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000012641bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12642 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012643 assert(!isValueDependent() &&
12644 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000012645 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012646 Info.InConstantContext = InConstantContext;
12647 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000012648}
12649
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012650bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12651 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012652 assert(!isValueDependent() &&
12653 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000012654 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012655 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000012656 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000012657}
12658
Fangrui Song407659a2018-11-30 23:41:18 +000012659bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012660 SideEffectsKind AllowSideEffects,
12661 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012662 assert(!isValueDependent() &&
12663 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000012664 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012665 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000012666 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000012667}
12668
Leonard Chand3f3e162019-01-18 21:04:25 +000012669bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012670 SideEffectsKind AllowSideEffects,
12671 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012672 assert(!isValueDependent() &&
12673 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000012674 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012675 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000012676 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12677}
12678
Richard Trieube234c32016-04-21 21:04:55 +000012679bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012680 SideEffectsKind AllowSideEffects,
12681 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012682 assert(!isValueDependent() &&
12683 "Expression evaluator can't be called on a dependent expression.");
12684
Richard Trieube234c32016-04-21 21:04:55 +000012685 if (!getType()->isRealFloatingType())
12686 return false;
12687
12688 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012689 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12690 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000012691 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000012692 return false;
12693
12694 Result = ExprResult.Val.getFloat();
12695 return true;
12696}
12697
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012698bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12699 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012700 assert(!isValueDependent() &&
12701 "Expression evaluator can't be called on a dependent expression.");
12702
Richard Smith6d4c6582013-11-05 22:18:15 +000012703 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012704 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000012705 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000012706 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
12707 Result.HasSideEffects ||
Richard Smithb228a862012-02-15 02:18:13 +000012708 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000012709 Ctx.getLValueReferenceType(getType()), LV,
12710 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000012711 return false;
12712
Richard Smith2e312c82012-03-03 22:46:17 +000012713 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000012714 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000012715}
12716
Reid Kleckner1a840d22018-05-10 18:57:35 +000012717bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12718 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012719 assert(!isValueDependent() &&
12720 "Expression evaluator can't be called on a dependent expression.");
12721
Reid Kleckner1a840d22018-05-10 18:57:35 +000012722 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12723 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000012724 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000012725
Reid Kleckner1a840d22018-05-10 18:57:35 +000012726 if (!::Evaluate(Result.Val, Info, this))
12727 return false;
12728
Richard Smith457226e2019-09-23 03:48:44 +000012729 if (!Info.discardCleanups())
12730 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
12731
Reid Kleckner1a840d22018-05-10 18:57:35 +000012732 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12733 Usage);
12734}
12735
Richard Smithd0b4dd62011-12-19 06:19:21 +000012736bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12737 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012738 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012739 assert(!isValueDependent() &&
12740 "Expression evaluator can't be called on a dependent expression.");
12741
Richard Smithdafff942012-01-14 04:30:29 +000012742 // FIXME: Evaluating initializers for large array and record types can cause
12743 // performance problems. Only do so in C++11 for now.
12744 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012745 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000012746 return false;
12747
Richard Smithd0b4dd62011-12-19 06:19:21 +000012748 Expr::EvalStatus EStatus;
12749 EStatus.Diag = &Notes;
12750
Nandor Licker950b70d2019-09-13 09:46:16 +000012751 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000012752 ? EvalInfo::EM_ConstantExpression
12753 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000012754 Info.setEvaluatingDecl(VD, Value);
12755 Info.InConstantContext = true;
12756
12757 SourceLocation DeclLoc = VD->getLocation();
12758 QualType DeclTy = VD->getType();
12759
12760 if (Info.EnableNewConstInterp) {
12761 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
12762 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
12763 case interp::InterpResult::Fail:
12764 // Bail out if an error was encountered.
12765 return false;
12766 case interp::InterpResult::Success:
12767 // Evaluation succeeded and value was set.
12768 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
12769 case interp::InterpResult::Bail:
12770 // Evaluate the value again for the tree evaluator to use.
12771 break;
12772 }
12773 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000012774
12775 LValue LVal;
12776 LVal.set(VD);
12777
Richard Smithfddd3842011-12-30 21:15:51 +000012778 // C++11 [basic.start.init]p2:
12779 // Variables with static storage duration or thread storage duration shall be
12780 // zero-initialized before any other initialization takes place.
12781 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012782 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Nandor Licker950b70d2019-09-13 09:46:16 +000012783 !DeclTy->isReferenceType()) {
12784 ImplicitValueInitExpr VIE(DeclTy);
12785 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000012786 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000012787 return false;
12788 }
12789
Nandor Licker950b70d2019-09-13 09:46:16 +000012790 if (!EvaluateInPlace(Value, Info, LVal, this,
Richard Smith7525ff62013-05-09 07:14:00 +000012791 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012792 EStatus.HasSideEffects)
12793 return false;
12794
Richard Smith457226e2019-09-23 03:48:44 +000012795 // At this point, any lifetime-extended temporaries are completely
12796 // initialized.
12797 Info.performLifetimeExtension();
12798
12799 if (!Info.discardCleanups())
12800 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
12801
Nandor Licker950b70d2019-09-13 09:46:16 +000012802 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012803}
12804
Richard Smith7b553f12011-10-29 00:50:52 +000012805/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12806/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012807bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012808 assert(!isValueDependent() &&
12809 "Expression evaluator can't be called on a dependent expression.");
12810
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012811 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012812 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012813 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012814}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012815
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012816APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012817 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012818 assert(!isValueDependent() &&
12819 "Expression evaluator can't be called on a dependent expression.");
12820
Fangrui Song407659a2018-11-30 23:41:18 +000012821 EvalResult EVResult;
12822 EVResult.Diag = Diag;
12823 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12824 Info.InConstantContext = true;
12825
12826 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012827 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012828 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012829 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012830
Fangrui Song407659a2018-11-30 23:41:18 +000012831 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012832}
John McCall864e3962010-05-07 05:32:02 +000012833
David Bolvansky3b6ae572018-10-18 20:49:06 +000012834APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12835 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012836 assert(!isValueDependent() &&
12837 "Expression evaluator can't be called on a dependent expression.");
12838
Fangrui Song407659a2018-11-30 23:41:18 +000012839 EvalResult EVResult;
12840 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000012841 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012842 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000012843 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000012844
12845 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012846 (void)Result;
12847 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012848 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012849
Fangrui Song407659a2018-11-30 23:41:18 +000012850 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012851}
12852
Richard Smithe9ff7702013-11-05 22:23:30 +000012853void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012854 assert(!isValueDependent() &&
12855 "Expression evaluator can't be called on a dependent expression.");
12856
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012857 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012858 EvalResult EVResult;
12859 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000012860 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12861 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000012862 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012863 }
12864}
12865
Richard Smithe6c01442013-06-05 00:46:14 +000012866bool Expr::EvalResult::isGlobalLValue() const {
12867 assert(Val.isLValue());
12868 return IsGlobalLValue(Val.getLValueBase());
12869}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012870
12871
John McCall864e3962010-05-07 05:32:02 +000012872/// isIntegerConstantExpr - this recursive routine will test if an expression is
12873/// an integer constant expression.
12874
12875/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12876/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012877
12878// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012879// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12880// and a (possibly null) SourceLocation indicating the location of the problem.
12881//
John McCall864e3962010-05-07 05:32:02 +000012882// Note that to reduce code duplication, this helper does no evaluation
12883// itself; the caller checks whether the expression is evaluatable, and
12884// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012885// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012886
Dan Gohman28ade552010-07-26 21:25:24 +000012887namespace {
12888
Richard Smith9e575da2012-12-28 13:25:52 +000012889enum ICEKind {
12890 /// This expression is an ICE.
12891 IK_ICE,
12892 /// This expression is not an ICE, but if it isn't evaluated, it's
12893 /// a legal subexpression for an ICE. This return value is used to handle
12894 /// the comma operator in C99 mode, and non-constant subexpressions.
12895 IK_ICEIfUnevaluated,
12896 /// This expression is not an ICE, and is not a legal subexpression for one.
12897 IK_NotICE
12898};
12899
John McCall864e3962010-05-07 05:32:02 +000012900struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012901 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012902 SourceLocation Loc;
12903
Richard Smith9e575da2012-12-28 13:25:52 +000012904 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012905};
12906
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012907}
Dan Gohman28ade552010-07-26 21:25:24 +000012908
Richard Smith9e575da2012-12-28 13:25:52 +000012909static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12910
12911static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012912
Craig Toppera31a8822013-08-22 07:09:37 +000012913static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012914 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012915 Expr::EvalStatus Status;
12916 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12917
12918 Info.InConstantContext = true;
12919 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012920 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012921 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012922
John McCall864e3962010-05-07 05:32:02 +000012923 return NoDiag();
12924}
12925
Craig Toppera31a8822013-08-22 07:09:37 +000012926static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012927 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012928 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012929 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012930
12931 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012932#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012933#define STMT(Node, Base) case Expr::Node##Class:
12934#define EXPR(Node, Base)
12935#include "clang/AST/StmtNodes.inc"
12936 case Expr::PredefinedExprClass:
12937 case Expr::FloatingLiteralClass:
12938 case Expr::ImaginaryLiteralClass:
12939 case Expr::StringLiteralClass:
12940 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012941 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012942 case Expr::MemberExprClass:
12943 case Expr::CompoundAssignOperatorClass:
12944 case Expr::CompoundLiteralExprClass:
12945 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012946 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012947 case Expr::ArrayInitLoopExprClass:
12948 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012949 case Expr::NoInitExprClass:
12950 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012951 case Expr::ImplicitValueInitExprClass:
12952 case Expr::ParenListExprClass:
12953 case Expr::VAArgExprClass:
12954 case Expr::AddrLabelExprClass:
12955 case Expr::StmtExprClass:
12956 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012957 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012958 case Expr::CXXDynamicCastExprClass:
12959 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012960 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012961 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012962 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012963 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012964 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012965 case Expr::CXXThisExprClass:
12966 case Expr::CXXThrowExprClass:
12967 case Expr::CXXNewExprClass:
12968 case Expr::CXXDeleteExprClass:
12969 case Expr::CXXPseudoDestructorExprClass:
12970 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012971 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012972 case Expr::DependentScopeDeclRefExprClass:
12973 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012974 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012975 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012976 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012977 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012978 case Expr::CXXTemporaryObjectExprClass:
12979 case Expr::CXXUnresolvedConstructExprClass:
12980 case Expr::CXXDependentScopeMemberExprClass:
12981 case Expr::UnresolvedMemberExprClass:
12982 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012983 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012984 case Expr::ObjCArrayLiteralClass:
12985 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012986 case Expr::ObjCEncodeExprClass:
12987 case Expr::ObjCMessageExprClass:
12988 case Expr::ObjCSelectorExprClass:
12989 case Expr::ObjCProtocolExprClass:
12990 case Expr::ObjCIvarRefExprClass:
12991 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012992 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012993 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012994 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012995 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012996 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012997 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012998 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012999 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000013000 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000013001 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000013002 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000013003 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000013004 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000013005 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000013006 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000013007 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000013008 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000013009 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013010 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000013011 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013012 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013013 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000013014
Richard Smithf137f932014-01-25 20:50:08 +000013015 case Expr::InitListExprClass: {
13016 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13017 // form "T x = { a };" is equivalent to "T x = a;".
13018 // Unless we're initializing a reference, T is a scalar as it is known to be
13019 // of integral or enumeration type.
13020 if (E->isRValue())
13021 if (cast<InitListExpr>(E)->getNumInits() == 1)
13022 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013023 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000013024 }
13025
Douglas Gregor820ba7b2011-01-04 17:33:58 +000013026 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000013027 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000013028 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000013029 return NoDiag();
13030
John McCall7c454bb2011-07-15 05:09:51 +000013031 case Expr::SubstNonTypeTemplateParmExprClass:
13032 return
13033 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13034
Bill Wendling7c44da22018-10-31 03:48:47 +000013035 case Expr::ConstantExprClass:
13036 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13037
John McCall864e3962010-05-07 05:32:02 +000013038 case Expr::ParenExprClass:
13039 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000013040 case Expr::GenericSelectionExprClass:
13041 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013042 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000013043 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013044 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013045 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000013046 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000013047 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000013048 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000013049 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000013050 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000013051 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013052 return NoDiag();
13053 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000013054 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000013055 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13056 // constant expressions, but they can never be ICEs because an ICE cannot
13057 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000013058 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000013059 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000013060 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013061 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013062 }
Richard Smith6365c912012-02-24 22:12:32 +000013063 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013064 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13065 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000013066 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000013067 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000013068 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000013069 // Parameter variables are never constants. Without this check,
13070 // getAnyInitializer() can find a default argument, which leads
13071 // to chaos.
13072 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000013073 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013074
13075 // C++ 7.1.5.1p2
13076 // A variable of non-volatile const-qualified integral or enumeration
13077 // type initialized by an ICE can be used in ICEs.
13078 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000013079 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000013080 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000013081
Richard Smithd0b4dd62011-12-19 06:19:21 +000013082 const VarDecl *VD;
13083 // Look for a declaration of this variable that has an initializer, and
13084 // check whether it is an ICE.
13085 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13086 return NoDiag();
13087 else
Richard Smith9e575da2012-12-28 13:25:52 +000013088 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013089 }
13090 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013091 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000013092 }
John McCall864e3962010-05-07 05:32:02 +000013093 case Expr::UnaryOperatorClass: {
13094 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13095 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013096 case UO_PostInc:
13097 case UO_PostDec:
13098 case UO_PreInc:
13099 case UO_PreDec:
13100 case UO_AddrOf:
13101 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000013102 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000013103 // C99 6.6/3 allows increment and decrement within unevaluated
13104 // subexpressions of constant expressions, but they can never be ICEs
13105 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013106 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000013107 case UO_Extension:
13108 case UO_LNot:
13109 case UO_Plus:
13110 case UO_Minus:
13111 case UO_Not:
13112 case UO_Real:
13113 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000013114 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013115 }
Reid Klecknere540d972018-11-01 17:51:48 +000013116 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000013117 }
13118 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000013119 // Note that per C99, offsetof must be an ICE. And AFAIK, using
13120 // EvaluateAsRValue matches the proposed gcc behavior for cases like
13121 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
13122 // compliance: we should warn earlier for offsetof expressions with
13123 // array subscripts that aren't ICEs, and if the array subscripts
13124 // are ICEs, the value of the offsetof must be an integer constant.
13125 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000013126 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000013127 case Expr::UnaryExprOrTypeTraitExprClass: {
13128 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
13129 if ((Exp->getKind() == UETT_SizeOf) &&
13130 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013131 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013132 return NoDiag();
13133 }
13134 case Expr::BinaryOperatorClass: {
13135 const BinaryOperator *Exp = cast<BinaryOperator>(E);
13136 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013137 case BO_PtrMemD:
13138 case BO_PtrMemI:
13139 case BO_Assign:
13140 case BO_MulAssign:
13141 case BO_DivAssign:
13142 case BO_RemAssign:
13143 case BO_AddAssign:
13144 case BO_SubAssign:
13145 case BO_ShlAssign:
13146 case BO_ShrAssign:
13147 case BO_AndAssign:
13148 case BO_XorAssign:
13149 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000013150 // C99 6.6/3 allows assignments within unevaluated subexpressions of
13151 // constant expressions, but they can never be ICEs because an ICE cannot
13152 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013153 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013154
John McCalle3027922010-08-25 11:45:40 +000013155 case BO_Mul:
13156 case BO_Div:
13157 case BO_Rem:
13158 case BO_Add:
13159 case BO_Sub:
13160 case BO_Shl:
13161 case BO_Shr:
13162 case BO_LT:
13163 case BO_GT:
13164 case BO_LE:
13165 case BO_GE:
13166 case BO_EQ:
13167 case BO_NE:
13168 case BO_And:
13169 case BO_Xor:
13170 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000013171 case BO_Comma:
13172 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000013173 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13174 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000013175 if (Exp->getOpcode() == BO_Div ||
13176 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000013177 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000013178 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000013179 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000013180 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000013181 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013182 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013183 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000013184 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000013185 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013186 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013187 }
13188 }
13189 }
John McCalle3027922010-08-25 11:45:40 +000013190 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013191 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000013192 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
13193 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000013194 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013195 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013196 } else {
13197 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013198 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013199 }
13200 }
Richard Smith9e575da2012-12-28 13:25:52 +000013201 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000013202 }
John McCalle3027922010-08-25 11:45:40 +000013203 case BO_LAnd:
13204 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000013205 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13206 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013207 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000013208 // Rare case where the RHS has a comma "side-effect"; we need
13209 // to actually check the condition to see whether the side
13210 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000013211 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000013212 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000013213 return RHSResult;
13214 return NoDiag();
13215 }
13216
Richard Smith9e575da2012-12-28 13:25:52 +000013217 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000013218 }
13219 }
Reid Klecknere540d972018-11-01 17:51:48 +000013220 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000013221 }
13222 case Expr::ImplicitCastExprClass:
13223 case Expr::CStyleCastExprClass:
13224 case Expr::CXXFunctionalCastExprClass:
13225 case Expr::CXXStaticCastExprClass:
13226 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000013227 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000013228 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013229 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000013230 if (isa<ExplicitCastExpr>(E)) {
13231 if (const FloatingLiteral *FL
13232 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
13233 unsigned DestWidth = Ctx.getIntWidth(E->getType());
13234 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
13235 APSInt IgnoredVal(DestWidth, !DestSigned);
13236 bool Ignored;
13237 // If the value does not fit in the destination type, the behavior is
13238 // undefined, so we are not required to treat it as a constant
13239 // expression.
13240 if (FL->getValue().convertToInteger(IgnoredVal,
13241 llvm::APFloat::rmTowardZero,
13242 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013243 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000013244 return NoDiag();
13245 }
13246 }
Eli Friedman76d4e432011-09-29 21:49:34 +000013247 switch (cast<CastExpr>(E)->getCastKind()) {
13248 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000013249 case CK_AtomicToNonAtomic:
13250 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000013251 case CK_NoOp:
13252 case CK_IntegralToBoolean:
13253 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000013254 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000013255 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013256 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000013257 }
John McCall864e3962010-05-07 05:32:02 +000013258 }
John McCallc07a0c72011-02-17 10:25:35 +000013259 case Expr::BinaryConditionalOperatorClass: {
13260 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
13261 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013262 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000013263 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013264 if (FalseResult.Kind == IK_NotICE) return FalseResult;
13265 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
13266 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000013267 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000013268 return FalseResult;
13269 }
John McCall864e3962010-05-07 05:32:02 +000013270 case Expr::ConditionalOperatorClass: {
13271 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
13272 // If the condition (ignoring parens) is a __builtin_constant_p call,
13273 // then only the true side is actually considered in an integer constant
13274 // expression, and it is fully evaluated. This is an important GNU
13275 // extension. See GCC PR38377 for discussion.
13276 if (const CallExpr *CallCE
13277 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000013278 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000013279 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000013280 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000013281 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000013282 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000013283
Richard Smithf57d8cb2011-12-09 22:58:01 +000013284 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
13285 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000013286
Richard Smith9e575da2012-12-28 13:25:52 +000013287 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000013288 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013289 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000013290 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013291 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000013292 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013293 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000013294 return NoDiag();
13295 // Rare case where the diagnostics depend on which side is evaluated
13296 // Note that if we get here, CondResult is 0, and at least one of
13297 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000013298 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000013299 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000013300 return TrueResult;
13301 }
13302 case Expr::CXXDefaultArgExprClass:
13303 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000013304 case Expr::CXXDefaultInitExprClass:
13305 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013306 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000013307 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013308 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000013309 case Expr::BuiltinBitCastExprClass: {
13310 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13311 return ICEDiag(IK_NotICE, E->getBeginLoc());
13312 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13313 }
John McCall864e3962010-05-07 05:32:02 +000013314 }
13315
David Blaikiee4d798f2012-01-20 21:50:17 +000013316 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000013317}
13318
Richard Smithf57d8cb2011-12-09 22:58:01 +000013319/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000013320static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013321 const Expr *E,
13322 llvm::APSInt *Value,
13323 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000013324 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000013325 if (Loc) *Loc = E->getExprLoc();
13326 return false;
13327 }
13328
Richard Smith66e05fe2012-01-18 05:21:49 +000013329 APValue Result;
13330 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000013331 return false;
13332
Richard Smith98710fc2014-11-13 23:03:19 +000013333 if (!Result.isInt()) {
13334 if (Loc) *Loc = E->getExprLoc();
13335 return false;
13336 }
13337
Richard Smith66e05fe2012-01-18 05:21:49 +000013338 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000013339 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013340}
13341
Craig Toppera31a8822013-08-22 07:09:37 +000013342bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13343 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013344 assert(!isValueDependent() &&
13345 "Expression evaluator can't be called on a dependent expression.");
13346
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013347 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000013348 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013349
Richard Smith9e575da2012-12-28 13:25:52 +000013350 ICEDiag D = CheckICE(this, Ctx);
13351 if (D.Kind != IK_ICE) {
13352 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000013353 return false;
13354 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000013355 return true;
13356}
13357
Craig Toppera31a8822013-08-22 07:09:37 +000013358bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013359 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013360 assert(!isValueDependent() &&
13361 "Expression evaluator can't be called on a dependent expression.");
13362
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013363 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000013364 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13365
13366 if (!isIntegerConstantExpr(Ctx, Loc))
13367 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000013368
Richard Smith5c40f092015-12-04 03:00:44 +000013369 // The only possible side-effects here are due to UB discovered in the
13370 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13371 // required to treat the expression as an ICE, so we produce the folded
13372 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000013373 EvalResult ExprResult;
13374 Expr::EvalStatus Status;
13375 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13376 Info.InConstantContext = true;
13377
13378 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000013379 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000013380
13381 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000013382 return true;
13383}
Richard Smith66e05fe2012-01-18 05:21:49 +000013384
Craig Toppera31a8822013-08-22 07:09:37 +000013385bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013386 assert(!isValueDependent() &&
13387 "Expression evaluator can't be called on a dependent expression.");
13388
Richard Smith9e575da2012-12-28 13:25:52 +000013389 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000013390}
13391
Craig Toppera31a8822013-08-22 07:09:37 +000013392bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000013393 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013394 assert(!isValueDependent() &&
13395 "Expression evaluator can't be called on a dependent expression.");
13396
Richard Smith66e05fe2012-01-18 05:21:49 +000013397 // We support this checking in C++98 mode in order to diagnose compatibility
13398 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013399 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000013400
Richard Smith98a0a492012-02-14 21:38:30 +000013401 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000013402 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013403 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000013404 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000013405 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000013406
13407 APValue Scratch;
Richard Smith457226e2019-09-23 03:48:44 +000013408 bool IsConstExpr =
13409 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
13410 // FIXME: We don't produce a diagnostic for this, but the callers that
13411 // call us on arbitrary full-expressions should generally not care.
13412 Info.discardCleanups();
Richard Smith66e05fe2012-01-18 05:21:49 +000013413
13414 if (!Diags.empty()) {
13415 IsConstExpr = false;
13416 if (Loc) *Loc = Diags[0].first;
13417 } else if (!IsConstExpr) {
13418 // FIXME: This shouldn't happen.
13419 if (Loc) *Loc = getExprLoc();
13420 }
13421
13422 return IsConstExpr;
13423}
Richard Smith253c2a32012-01-27 01:14:48 +000013424
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013425bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13426 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000013427 ArrayRef<const Expr*> Args,
13428 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013429 assert(!isValueDependent() &&
13430 "Expression evaluator can't be called on a dependent expression.");
13431
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013432 Expr::EvalStatus Status;
13433 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013434 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013435
George Burgess IV177399e2017-01-09 04:12:14 +000013436 LValue ThisVal;
13437 const LValue *ThisPtr = nullptr;
13438 if (This) {
13439#ifndef NDEBUG
13440 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13441 assert(MD && "Don't provide `this` for non-methods.");
13442 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13443#endif
13444 if (EvaluateObjectArgument(Info, This, ThisVal))
13445 ThisPtr = &ThisVal;
13446 if (Info.EvalStatus.HasSideEffects)
13447 return false;
13448 }
13449
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013450 ArgVector ArgValues(Args.size());
13451 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13452 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000013453 if ((*I)->isValueDependent() ||
13454 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013455 // If evaluation fails, throw away the argument entirely.
13456 ArgValues[I - Args.begin()] = APValue();
13457 if (Info.EvalStatus.HasSideEffects)
13458 return false;
13459 }
13460
13461 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000013462 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013463 ArgValues.data());
Richard Smith457226e2019-09-23 03:48:44 +000013464 return Evaluate(Value, Info, this) && Info.discardCleanups() &&
13465 !Info.EvalStatus.HasSideEffects;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013466}
13467
Richard Smith253c2a32012-01-27 01:14:48 +000013468bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013469 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000013470 PartialDiagnosticAt> &Diags) {
13471 // FIXME: It would be useful to check constexpr function templates, but at the
13472 // moment the constant expression evaluator cannot cope with the non-rigorous
13473 // ASTs which we build for dependent expressions.
13474 if (FD->isDependentContext())
13475 return true;
13476
13477 Expr::EvalStatus Status;
13478 Status.Diag = &Diags;
13479
Richard Smith045b2272019-09-10 21:24:09 +000013480 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000013481 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013482 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000013483
Nandor Licker950b70d2019-09-13 09:46:16 +000013484 // The constexpr VM attempts to compile all methods to bytecode here.
13485 if (Info.EnableNewConstInterp) {
13486 auto &InterpCtx = Info.Ctx.getInterpContext();
13487 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
13488 case interp::InterpResult::Success:
13489 case interp::InterpResult::Fail:
13490 return Diags.empty();
13491 case interp::InterpResult::Bail:
13492 break;
13493 }
13494 }
13495
Richard Smith253c2a32012-01-27 01:14:48 +000013496 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000013497 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000013498
Richard Smith7525ff62013-05-09 07:14:00 +000013499 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000013500 // is a temporary being used as the 'this' pointer.
13501 LValue This;
13502 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000013503 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000013504
Richard Smith253c2a32012-01-27 01:14:48 +000013505 ArrayRef<const Expr*> Args;
13506
Richard Smith2e312c82012-03-03 22:46:17 +000013507 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000013508 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13509 // Evaluate the call as a constant initializer, to allow the construction
13510 // of objects of non-literal types.
13511 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000013512 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13513 } else {
13514 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000013515 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000013516 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000013517 }
Richard Smith253c2a32012-01-27 01:14:48 +000013518
13519 return Diags.empty();
13520}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013521
13522bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13523 const FunctionDecl *FD,
13524 SmallVectorImpl<
13525 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013526 assert(!E->isValueDependent() &&
13527 "Expression evaluator can't be called on a dependent expression.");
13528
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013529 Expr::EvalStatus Status;
13530 Status.Diag = &Diags;
13531
13532 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000013533 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013534 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013535 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013536
13537 // Fabricate a call stack frame to give the arguments a plausible cover story.
13538 ArrayRef<const Expr*> Args;
13539 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013540 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013541 (void)Success;
13542 assert(Success &&
13543 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000013544 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013545
13546 APValue ResultScratch;
13547 Evaluate(ResultScratch, Info, E);
13548 return Diags.empty();
13549}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013550
13551bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13552 unsigned Type) const {
13553 if (!getType()->isPointerType())
13554 return false;
13555
13556 Expr::EvalStatus Status;
13557 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000013558 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013559}