blob: 2d538eda8128e5f353c3a74e832d992cd531efdb [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
George Burgess IVe3763372016-12-22 02:50:20 +0000137 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
138 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
139 const FunctionDecl *Callee = CE->getDirectCallee();
140 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
141 }
142
143 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
144 /// This will look through a single cast.
145 ///
146 /// Returns null if we couldn't unwrap a function with alloc_size.
147 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
148 if (!E->getType()->isPointerType())
149 return nullptr;
150
151 E = E->IgnoreParens();
152 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000153 // probably be a cast of some kind. In exotic cases, we might also see a
154 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000155 if (const auto *FE = dyn_cast<FullExpr>(E))
156 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000157
George Burgess IVe3763372016-12-22 02:50:20 +0000158 if (const auto *Cast = dyn_cast<CastExpr>(E))
159 E = Cast->getSubExpr()->IgnoreParens();
160
161 if (const auto *CE = dyn_cast<CallExpr>(E))
162 return getAllocSizeAttr(CE) ? CE : nullptr;
163 return nullptr;
164 }
165
166 /// Determines whether or not the given Base contains a call to a function
167 /// with the alloc_size attribute.
168 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
169 const auto *E = Base.dyn_cast<const Expr *>();
170 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
171 }
172
Richard Smith6f4f0f12017-10-20 22:56:25 +0000173 /// The bound to claim that an array of unknown bound has.
174 /// The value in MostDerivedArraySize is undefined in this case. So, set it
175 /// to an arbitrary value that's likely to loudly break things if it's used.
176 static const uint64_t AssumedSizeForUnsizedArray =
177 std::numeric_limits<uint64_t>::max() / 2;
178
George Burgess IVe3763372016-12-22 02:50:20 +0000179 /// Determines if an LValue with the given LValueBase will have an unsized
180 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000181 /// Find the path length and type of the most-derived subobject in the given
182 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000183 static unsigned
184 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
185 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000186 uint64_t &ArraySize, QualType &Type, bool &IsArray,
187 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000188 // This only accepts LValueBases from APValues, and APValues don't support
189 // arrays that lack size info.
190 assert(!isBaseAnAllocSizeCall(Base) &&
191 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000193 Type = getType(Base);
194
Richard Smith80815602011-11-07 05:07:52 +0000195 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000196 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000197 const ArrayType *AT = Ctx.getAsArrayType(Type);
198 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000200 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000201
202 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
203 ArraySize = CAT->getSize().getZExtValue();
204 } else {
205 assert(I == 0 && "unexpected unsized array designator");
206 FirstEntryIsUnsizedArray = true;
207 ArraySize = AssumedSizeForUnsizedArray;
208 }
Richard Smith66c96992012-02-18 22:04:06 +0000209 } else if (Type->isAnyComplexType()) {
210 const ComplexType *CT = Type->castAs<ComplexType>();
211 Type = CT->getElementType();
212 ArraySize = 2;
213 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000214 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 } else if (const FieldDecl *FD = getAsField(Path[I])) {
216 Type = FD->getType();
217 ArraySize = 0;
218 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000219 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 } else {
Richard Smith80815602011-11-07 05:07:52 +0000221 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 }
Richard Smith80815602011-11-07 05:07:52 +0000225 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000227 }
228
Richard Smith96e0c102011-11-04 02:25:55 +0000229 /// A path from a glvalue to a subobject of that glvalue.
230 struct SubobjectDesignator {
231 /// True if the subobject was named in a manner not supported by C++11. Such
232 /// lvalues can still be folded, but they are not core constant expressions
233 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000234 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000235
Richard Smitha8105bc2012-01-06 16:39:00 +0000236 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000237 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000238
Daniel Jasperffdee092017-05-02 19:21:42 +0000239 /// Indicator of whether the first entry is an unsized array.
240 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000241
George Burgess IVa51c4072015-10-16 01:49:01 +0000242 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000243 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000244
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 /// The length of the path to the most-derived object of which this is a
246 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000247 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248
George Burgess IVa51c4072015-10-16 01:49:01 +0000249 /// The size of the array of which the most-derived object is an element.
250 /// This will always be 0 if the most-derived object is not an array
251 /// element. 0 is not an indicator of whether or not the most-derived object
252 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000253 ///
254 /// If the current array is an unsized array, the value of this is
255 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000256 uint64_t MostDerivedArraySize;
257
258 /// The type of the most derived object referred to by this address.
259 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000260
Richard Smith80815602011-11-07 05:07:52 +0000261 typedef APValue::LValuePathEntry PathEntry;
262
Richard Smith96e0c102011-11-04 02:25:55 +0000263 /// The entries on the path from the glvalue to the designated subobject.
264 SmallVector<PathEntry, 8> Entries;
265
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000267
Richard Smitha8105bc2012-01-06 16:39:00 +0000268 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000269 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000270 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000271 MostDerivedPathLength(0), MostDerivedArraySize(0),
272 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000273
274 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000277 MostDerivedPathLength(0), MostDerivedArraySize(0) {
278 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000279 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000280 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000281 ArrayRef<PathEntry> VEntries = V.getLValuePath();
282 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000283 if (V.getLValueBase()) {
284 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000285 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000286 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000287 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000288 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000289 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000290 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000291 }
Richard Smith80815602011-11-07 05:07:52 +0000292 }
293 }
294
Richard Smith31c69a32019-05-21 23:15:20 +0000295 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
296 unsigned NewLength) {
297 if (Invalid)
298 return;
299
300 assert(Base && "cannot truncate path for null pointer");
301 assert(NewLength <= Entries.size() && "not a truncation");
302
303 if (NewLength == Entries.size())
304 return;
305 Entries.resize(NewLength);
306
307 bool IsArray = false;
308 bool FirstIsUnsizedArray = false;
309 MostDerivedPathLength = findMostDerivedSubobject(
310 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
311 FirstIsUnsizedArray);
312 MostDerivedIsArrayElement = IsArray;
313 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
314 }
315
Richard Smith96e0c102011-11-04 02:25:55 +0000316 void setInvalid() {
317 Invalid = true;
318 Entries.clear();
319 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000320
George Burgess IVe3763372016-12-22 02:50:20 +0000321 /// Determine whether the most derived subobject is an array without a
322 /// known bound.
323 bool isMostDerivedAnUnsizedArray() const {
324 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000325 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000326 }
327
328 /// Determine what the most derived array's size is. Results in an assertion
329 /// failure if the most derived array lacks a size.
330 uint64_t getMostDerivedArraySize() const {
331 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
332 return MostDerivedArraySize;
333 }
334
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 /// Determine whether this is a one-past-the-end pointer.
336 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000337 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000338 if (IsOnePastTheEnd)
339 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000340 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000341 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
342 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 return true;
344 return false;
345 }
346
Richard Smith06f71b52018-08-04 00:57:17 +0000347 /// Get the range of valid index adjustments in the form
348 /// {maximum value that can be subtracted from this pointer,
349 /// maximum value that can be added to this pointer}
350 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
351 if (Invalid || isMostDerivedAnUnsizedArray())
352 return {0, 0};
353
354 // [expr.add]p4: For the purposes of these operators, a pointer to a
355 // nonarray object behaves the same as a pointer to the first element of
356 // an array of length one with the type of the object as its element type.
357 bool IsArray = MostDerivedPathLength == Entries.size() &&
358 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000359 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
360 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000361 uint64_t ArraySize =
362 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
363 return {ArrayIndex, ArraySize - ArrayIndex};
364 }
365
Richard Smitha8105bc2012-01-06 16:39:00 +0000366 /// Check that this refers to a valid subobject.
367 bool isValidSubobject() const {
368 if (Invalid)
369 return false;
370 return !isOnePastTheEnd();
371 }
372 /// Check that this refers to a valid subobject, and if not, produce a
373 /// relevant diagnostic and set the designator as invalid.
374 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
375
Richard Smith06f71b52018-08-04 00:57:17 +0000376 /// Get the type of the designated object.
377 QualType getType(ASTContext &Ctx) const {
378 assert(!Invalid && "invalid designator has no subobject type");
379 return MostDerivedPathLength == Entries.size()
380 ? MostDerivedType
381 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
382 }
383
Richard Smitha8105bc2012-01-06 16:39:00 +0000384 /// Update this designator to refer to the first element within this array.
385 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000386 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000387
388 // This is a most-derived object.
389 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000390 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000391 MostDerivedArraySize = CAT->getSize().getZExtValue();
392 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000393 }
George Burgess IVe3763372016-12-22 02:50:20 +0000394 /// Update this designator to refer to the first element within the array of
395 /// elements of type T. This is an array of unknown size.
396 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000397 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000398
399 MostDerivedType = ElemTy;
400 MostDerivedIsArrayElement = true;
401 // The value in MostDerivedArraySize is undefined in this case. So, set it
402 // to an arbitrary value that's likely to loudly break things if it's
403 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000404 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000405 MostDerivedPathLength = Entries.size();
406 }
Richard Smith96e0c102011-11-04 02:25:55 +0000407 /// Update this designator to refer to the given base or member of this
408 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000409 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000410 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000411
412 // If this isn't a base class, it's a new most-derived object.
413 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
414 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000415 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000416 MostDerivedArraySize = 0;
417 MostDerivedPathLength = Entries.size();
418 }
Richard Smith96e0c102011-11-04 02:25:55 +0000419 }
Richard Smith66c96992012-02-18 22:04:06 +0000420 /// Update this designator to refer to the given complex component.
421 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000422 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000423
424 // This is technically a most-derived object, though in practice this
425 // is unlikely to matter.
426 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000427 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000428 MostDerivedArraySize = 2;
429 MostDerivedPathLength = Entries.size();
430 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000431 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000432 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
433 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000434 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000435 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
436 if (Invalid || !N) return;
437 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
438 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000439 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000440 // Can't verify -- trust that the user is doing the right thing (or if
441 // not, trust that the caller will catch the bad behavior).
442 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000443 Entries.back() = PathEntry::ArrayIndex(
444 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000445 return;
446 }
447
448 // [expr.add]p4: For the purposes of these operators, a pointer to a
449 // nonarray object behaves the same as a pointer to the first element of
450 // an array of length one with the type of the object as its element type.
451 bool IsArray = MostDerivedPathLength == Entries.size() &&
452 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000453 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
454 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000455 uint64_t ArraySize =
456 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
457
458 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
459 // Calculate the actual index in a wide enough type, so we can include
460 // it in the note.
461 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
462 (llvm::APInt&)N += ArrayIndex;
463 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
464 diagnosePointerArithmetic(Info, E, N);
465 setInvalid();
466 return;
467 }
468
469 ArrayIndex += TruncatedN;
470 assert(ArrayIndex <= ArraySize &&
471 "bounds check succeeded for out-of-bounds index");
472
473 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000474 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000475 else
476 IsOnePastTheEnd = (ArrayIndex != 0);
477 }
Richard Smith96e0c102011-11-04 02:25:55 +0000478 };
479
Richard Smith254a73d2011-10-28 22:34:42 +0000480 /// A stack frame in the constexpr call stack.
Nandor Licker950b70d2019-09-13 09:46:16 +0000481 class CallStackFrame : public interp::Frame {
482 public:
Richard Smith254a73d2011-10-28 22:34:42 +0000483 EvalInfo &Info;
484
485 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000487
Richard Smithf6f003a2011-12-16 19:06:07 +0000488 /// Callee - The function which was called.
489 const FunctionDecl *Callee;
490
Richard Smithd62306a2011-11-10 06:34:14 +0000491 /// This - The binding for the this pointer in this call, if any.
492 const LValue *This;
493
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000494 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000495 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000496 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000497
Eric Fiselier708afb52019-05-16 21:04:15 +0000498 /// Source location information about the default argument or default
499 /// initializer expression we're evaluating, if any.
500 CurrentSourceLocExprScope CurSourceLocExprScope;
501
Eli Friedman4830ec82012-06-25 21:21:08 +0000502 // Note that we intentionally use std::map here so that references to
503 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000504 typedef std::pair<const void *, unsigned> MapKeyTy;
505 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000506 /// Temporaries - Temporary lvalues materialized within this stack frame.
507 MapTy Temporaries;
508
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000509 /// CallLoc - The location of the call expression for this call.
510 SourceLocation CallLoc;
511
512 /// Index - The call index of this call.
513 unsigned Index;
514
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000515 /// The stack of integers for tracking version numbers for temporaries.
516 SmallVector<unsigned, 2> TempVersionStack = {1};
517 unsigned CurTempVersion = TempVersionStack.back();
518
519 unsigned getTempVersion() const { return TempVersionStack.back(); }
520
521 void pushTempVersion() {
522 TempVersionStack.push_back(++CurTempVersion);
523 }
524
525 void popTempVersion() {
526 TempVersionStack.pop_back();
527 }
528
Faisal Vali051e3a22017-02-16 04:12:21 +0000529 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000530 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000531 // (We should cache this map rather than recomputing it repeatedly.)
532 // But let's try this and see how it goes; we can look into caching the map
533 // as a later change.
534
535 /// LambdaCaptureFields - Mapping from captured variables/this to
536 /// corresponding data members in the closure class.
537 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
538 FieldDecl *LambdaThisCaptureField;
539
Richard Smithf6f003a2011-12-16 19:06:07 +0000540 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
541 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000542 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000543 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000544
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000545 // Return the temporary for Key whose version number is Version.
546 APValue *getTemporary(const void *Key, unsigned Version) {
547 MapKeyTy KV(Key, Version);
548 auto LB = Temporaries.lower_bound(KV);
549 if (LB != Temporaries.end() && LB->first == KV)
550 return &LB->second;
551 // Pair (Key,Version) wasn't found in the map. Check that no elements
552 // in the map have 'Key' as their key.
553 assert((LB == Temporaries.end() || LB->first.first != Key) &&
554 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
555 "Element with key 'Key' found in map");
556 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000557 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000558
559 // Return the current temporary for Key in the map.
560 APValue *getCurrentTemporary(const void *Key) {
561 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
562 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
563 return &std::prev(UB)->second;
564 return nullptr;
565 }
566
567 // Return the version number of the current temporary for Key.
568 unsigned getCurrentTemporaryVersion(const void *Key) const {
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)->first.second;
572 return 0;
573 }
574
Richard Smith08d6a2c2013-07-24 07:11:57 +0000575 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Nandor Licker950b70d2019-09-13 09:46:16 +0000576
577 void describe(llvm::raw_ostream &OS) override;
578
579 Frame *getCaller() const override { return Caller; }
580 SourceLocation getCallLocation() const override { return CallLoc; }
581 const FunctionDecl *getCallee() const override { return Callee; }
Richard Smith254a73d2011-10-28 22:34:42 +0000582 };
583
Richard Smith852c9db2013-04-20 22:23:05 +0000584 /// Temporarily override 'this'.
585 class ThisOverrideRAII {
586 public:
587 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
588 : Frame(Frame), OldThis(Frame.This) {
589 if (Enable)
590 Frame.This = NewThis;
591 }
592 ~ThisOverrideRAII() {
593 Frame.This = OldThis;
594 }
595 private:
596 CallStackFrame &Frame;
597 const LValue *OldThis;
598 };
599
Richard Smith08d6a2c2013-07-24 07:11:57 +0000600 /// A cleanup, and a flag indicating whether it is lifetime-extended.
601 class Cleanup {
602 llvm::PointerIntPair<APValue*, 1, bool> Value;
603
604 public:
605 Cleanup(APValue *Val, bool IsLifetimeExtended)
606 : Value(Val, IsLifetimeExtended) {}
607
608 bool isLifetimeExtended() const { return Value.getInt(); }
609 void endLifetime() {
610 *Value.getPointer() = APValue();
611 }
612 };
613
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000614 /// A reference to an object whose construction we are currently evaluating.
615 struct ObjectUnderConstruction {
616 APValue::LValueBase Base;
617 ArrayRef<APValue::LValuePathEntry> Path;
618 friend bool operator==(const ObjectUnderConstruction &LHS,
619 const ObjectUnderConstruction &RHS) {
620 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
621 }
622 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
623 return llvm::hash_combine(Obj.Base, Obj.Path);
624 }
625 };
626 enum class ConstructionPhase { None, Bases, AfterBases };
627}
628
629namespace llvm {
630template<> struct DenseMapInfo<ObjectUnderConstruction> {
631 using Base = DenseMapInfo<APValue::LValueBase>;
632 static ObjectUnderConstruction getEmptyKey() {
633 return {Base::getEmptyKey(), {}}; }
634 static ObjectUnderConstruction getTombstoneKey() {
635 return {Base::getTombstoneKey(), {}};
636 }
637 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
638 return hash_value(Object);
639 }
640 static bool isEqual(const ObjectUnderConstruction &LHS,
641 const ObjectUnderConstruction &RHS) {
642 return LHS == RHS;
643 }
644};
645}
646
647namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000648 /// EvalInfo - This is a private struct used by the evaluator to capture
649 /// information about a subexpression as it is folded. It retains information
650 /// about the AST context, but also maintains information about the folded
651 /// expression.
652 ///
653 /// If an expression could be evaluated, it is still possible it is not a C
654 /// "integer constant expression" or constant expression. If not, this struct
655 /// captures information about how and why not.
656 ///
657 /// One bit of information passed *into* the request for constant folding
658 /// indicates whether the subexpression is "evaluated" or not according to C
659 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
660 /// evaluate the expression regardless of what the RHS is, but C only allows
661 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000662 class EvalInfo : public interp::State {
663 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000664 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000665
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000666 /// EvalStatus - Contains information about the evaluation.
667 Expr::EvalStatus &EvalStatus;
668
669 /// CurrentCall - The top of the constexpr call stack.
670 CallStackFrame *CurrentCall;
671
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000672 /// CallStackDepth - The number of calls in the call stack right now.
673 unsigned CallStackDepth;
674
Richard Smithb228a862012-02-15 02:18:13 +0000675 /// NextCallIndex - The next call index to assign.
676 unsigned NextCallIndex;
677
Richard Smitha3d3bd22013-05-08 02:12:03 +0000678 /// StepsLeft - The remaining number of evaluation steps we're permitted
679 /// to perform. This is essentially a limit for the number of statements
680 /// we will evaluate.
681 unsigned StepsLeft;
682
Nandor Licker950b70d2019-09-13 09:46:16 +0000683 /// Force the use of the experimental new constant interpreter, bailing out
684 /// with an error if a feature is not supported.
685 bool ForceNewConstInterp;
686
687 /// Enable the experimental new constant interpreter.
688 bool EnableNewConstInterp;
689
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000690 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000691 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000692 CallStackFrame BottomFrame;
693
Richard Smith08d6a2c2013-07-24 07:11:57 +0000694 /// A stack of values whose lifetimes end at the end of some surrounding
695 /// evaluation frame.
696 llvm::SmallVector<Cleanup, 16> CleanupStack;
697
Richard Smithd62306a2011-11-10 06:34:14 +0000698 /// EvaluatingDecl - This is the declaration whose initializer is being
699 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000700 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000701
702 /// EvaluatingDeclValue - This is the value being constructed for the
703 /// declaration whose initializer is being evaluated, if any.
704 APValue *EvaluatingDeclValue;
705
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000706 /// Set of objects that are currently being constructed.
707 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
708 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000709
710 struct EvaluatingConstructorRAII {
711 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000712 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000713 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000714 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
715 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000716 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000717 DidInsert =
718 EI.ObjectsUnderConstruction
719 .insert({Object, HasBases ? ConstructionPhase::Bases
720 : ConstructionPhase::AfterBases})
721 .second;
722 }
723 void finishedConstructingBases() {
724 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000725 }
726 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000727 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000728 }
729 };
730
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000731 ConstructionPhase
732 isEvaluatingConstructor(APValue::LValueBase Base,
733 ArrayRef<APValue::LValuePathEntry> Path) {
734 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000735 }
736
Richard Smith37be3362019-05-04 04:00:45 +0000737 /// If we're currently speculatively evaluating, the outermost call stack
738 /// depth at which we can mutate state, otherwise 0.
739 unsigned SpeculativeEvaluationDepth = 0;
740
Richard Smith410306b2016-12-12 02:53:20 +0000741 /// The current array initialization index, if we're performing array
742 /// initialization.
743 uint64_t ArrayInitIndex = -1;
744
Richard Smith357362d2011-12-13 06:39:58 +0000745 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
746 /// notes attached to it will also be stored, otherwise they will not be.
747 bool HasActiveDiagnostic;
748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000749 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000750 /// fold (not just why it's not strictly a constant expression)?
751 bool HasFoldFailureDiagnostic;
752
Fangrui Song407659a2018-11-30 23:41:18 +0000753 /// Whether or not we're in a context where the front end requires a
754 /// constant value.
755 bool InConstantContext;
756
Richard Smith045b2272019-09-10 21:24:09 +0000757 /// Whether we're checking that an expression is a potential constant
758 /// expression. If so, do not fail on constructs that could become constant
759 /// later on (such as a use of an undefined global).
760 bool CheckingPotentialConstantExpression = false;
761
762 /// Whether we're checking for an expression that has undefined behavior.
763 /// If so, we will produce warnings if we encounter an operation that is
764 /// always undefined.
765 bool CheckingForUndefinedBehavior = false;
766
Richard Smith6d4c6582013-11-05 22:18:15 +0000767 enum EvaluationMode {
768 /// Evaluate as a constant expression. Stop if we find that the expression
769 /// is not a constant expression.
770 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000771
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000772 /// Evaluate as a constant expression. Stop if we find that the expression
773 /// is not a constant expression. Some expressions can be retried in the
774 /// optimizer if we don't constant fold them here, but in an unevaluated
775 /// context we try to fold them immediately since the optimizer never
776 /// gets a chance to look at it.
777 EM_ConstantExpressionUnevaluated,
778
Richard Smith045b2272019-09-10 21:24:09 +0000779 /// Fold the expression to a constant. Stop if we hit a side-effect that
780 /// we can't model.
781 EM_ConstantFold,
782
783 /// Evaluate in any way we know how. Don't worry about side-effects that
784 /// can't be modeled.
785 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000786 } EvalMode;
787
788 /// Are we checking whether the expression is a potential constant
789 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000790 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000791 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000792 }
793
794 /// Are we checking an expression for overflow?
795 // FIXME: We should check for any kind of undefined or suspicious behavior
796 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000797 bool checkingForUndefinedBehavior() const override {
798 return CheckingForUndefinedBehavior;
799 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000800
801 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000802 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
803 CallStackDepth(0), NextCallIndex(1),
804 StepsLeft(getLangOpts().ConstexprStepLimit),
805 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
806 EnableNewConstInterp(ForceNewConstInterp ||
807 getLangOpts().EnableNewConstInterp),
808 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
809 EvaluatingDecl((const ValueDecl *)nullptr),
810 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
811 HasFoldFailureDiagnostic(false), InConstantContext(false),
812 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000813
Richard Smith7525ff62013-05-09 07:14:00 +0000814 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
815 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000816 EvaluatingDeclValue = &Value;
817 }
818
Richard Smith357362d2011-12-13 06:39:58 +0000819 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000820 // Don't perform any constexpr calls (other than the call we're checking)
821 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000823 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000824 if (NextCallIndex == 0) {
825 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000826 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000827 return false;
828 }
Richard Smith357362d2011-12-13 06:39:58 +0000829 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
830 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000831 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000832 << getLangOpts().ConstexprCallDepth;
833 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000834 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000835
Richard Smith37be3362019-05-04 04:00:45 +0000836 std::pair<CallStackFrame *, unsigned>
837 getCallFrameAndDepth(unsigned CallIndex) {
838 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000839 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
840 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000841 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000842 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000843 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000844 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000845 --Depth;
846 }
847 if (Frame->Index == CallIndex)
848 return {Frame, Depth};
849 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000850 }
851
Richard Smitha3d3bd22013-05-08 02:12:03 +0000852 bool nextStep(const Stmt *S) {
853 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000854 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000855 return false;
856 }
857 --StepsLeft;
858 return true;
859 }
860
Richard Smith357362d2011-12-13 06:39:58 +0000861 private:
Nandor Licker950b70d2019-09-13 09:46:16 +0000862 interp::Frame *getCurrentFrame() override { return CurrentCall; }
863 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
864
865 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
866 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
867
868 void setFoldFailureDiagnostic(bool Flag) override {
869 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +0000870 }
871
Nandor Licker950b70d2019-09-13 09:46:16 +0000872 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +0000873
Nandor Licker950b70d2019-09-13 09:46:16 +0000874 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +0000875
Nandor Licker950b70d2019-09-13 09:46:16 +0000876 // If we have a prior diagnostic, it will be noting that the expression
877 // isn't a constant expression. This diagnostic is more important,
878 // unless we require this evaluation to produce a constant expression.
879 //
880 // FIXME: We might want to show both diagnostics to the user in
881 // EM_ConstantFold mode.
882 bool hasPriorDiagnostic() override {
883 if (!EvalStatus.Diag->empty()) {
884 switch (EvalMode) {
885 case EM_ConstantFold:
886 case EM_IgnoreSideEffects:
887 if (!HasFoldFailureDiagnostic)
888 break;
889 // We've already failed to fold something. Keep that diagnostic.
890 LLVM_FALLTHROUGH;
891 case EM_ConstantExpression:
892 case EM_ConstantExpressionUnevaluated:
893 setActiveDiagnostic(false);
894 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000896 }
Nandor Licker950b70d2019-09-13 09:46:16 +0000897 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000898 }
Nandor Licker950b70d2019-09-13 09:46:16 +0000899
900 unsigned getCallStackDepth() override { return CallStackDepth; }
901
Faisal Valie690b7a2016-07-02 22:34:24 +0000902 public:
Richard Smith6d4c6582013-11-05 22:18:15 +0000903 /// Should we continue evaluation after encountering a side-effect that we
904 /// couldn't model?
905 bool keepEvaluatingAfterSideEffect() {
906 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000907 case EM_IgnoreSideEffects:
908 return true;
909
Richard Smith6d4c6582013-11-05 22:18:15 +0000910 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000911 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000912 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +0000913 // By default, assume any side effect might be valid in some other
914 // evaluation of this expression from a different context.
915 return checkingPotentialConstantExpression() ||
916 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +0000917 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000918 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000919 }
920
921 /// Note that we have had a side-effect, and determine whether we should
922 /// keep evaluating.
923 bool noteSideEffect() {
924 EvalStatus.HasSideEffects = true;
925 return keepEvaluatingAfterSideEffect();
926 }
927
Richard Smithce8eca52015-12-08 03:21:47 +0000928 /// Should we continue evaluation after encountering undefined behavior?
929 bool keepEvaluatingAfterUndefinedBehavior() {
930 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +0000931 case EM_IgnoreSideEffects:
932 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000933 return true;
934
Richard Smithce8eca52015-12-08 03:21:47 +0000935 case EM_ConstantExpression:
936 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +0000937 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +0000938 }
939 llvm_unreachable("Missed EvalMode case");
940 }
941
942 /// Note that we hit something that was technically undefined behavior, but
943 /// that we can evaluate past it (such as signed overflow or floating-point
944 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +0000945 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +0000946 EvalStatus.HasUndefinedBehavior = true;
947 return keepEvaluatingAfterUndefinedBehavior();
948 }
949
Richard Smith253c2a32012-01-27 01:14:48 +0000950 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000951 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +0000952 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 if (!StepsLeft)
954 return false;
955
956 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000957 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000958 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 case EM_ConstantFold:
960 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +0000961 return checkingPotentialConstantExpression() ||
962 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +0000963 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000964 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000965 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000966
George Burgess IV8c892b52016-05-25 22:31:54 +0000967 /// Notes that we failed to evaluate an expression that other expressions
968 /// directly depend on, and determine if we should keep evaluating. This
969 /// should only be called if we actually intend to keep evaluating.
970 ///
971 /// Call noteSideEffect() instead if we may be able to ignore the value that
972 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
973 ///
974 /// (Foo(), 1) // use noteSideEffect
975 /// (Foo() || true) // use noteSideEffect
976 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000977 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000978 // Failure when evaluating some expression often means there is some
979 // subexpression whose evaluation was skipped. Therefore, (because we
980 // don't track whether we skipped an expression when unwinding after an
981 // evaluation failure) every evaluation failure that bubbles up from a
982 // subexpression implies that a side-effect has potentially happened. We
983 // skip setting the HasSideEffects flag to true until we decide to
984 // continue evaluating after that point, which happens here.
985 bool KeepGoing = keepEvaluatingAfterFailure();
986 EvalStatus.HasSideEffects |= KeepGoing;
987 return KeepGoing;
988 }
989
Richard Smith410306b2016-12-12 02:53:20 +0000990 class ArrayInitLoopIndex {
991 EvalInfo &Info;
992 uint64_t OuterIndex;
993
994 public:
995 ArrayInitLoopIndex(EvalInfo &Info)
996 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
997 Info.ArrayInitIndex = 0;
998 }
999 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1000
1001 operator uint64_t&() { return Info.ArrayInitIndex; }
1002 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001003 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001004
1005 /// Object used to treat all foldable expressions as constant expressions.
1006 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001007 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001008 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001009 bool HadNoPriorDiags;
1010 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001011
Richard Smith6d4c6582013-11-05 22:18:15 +00001012 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1013 : Info(Info),
1014 Enabled(Enabled),
1015 HadNoPriorDiags(Info.EvalStatus.Diag &&
1016 Info.EvalStatus.Diag->empty() &&
1017 !Info.EvalStatus.HasSideEffects),
1018 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001019 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001020 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001021 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 void keepDiagnostics() { Enabled = false; }
1023 ~FoldConstant() {
1024 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001025 !Info.EvalStatus.HasSideEffects)
1026 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001027 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001028 }
1029 };
Richard Smith17100ba2012-02-16 02:46:34 +00001030
James Y Knight892b09b2018-10-10 02:53:43 +00001031 /// RAII object used to set the current evaluation mode to ignore
1032 /// side-effects.
1033 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001034 EvalInfo &Info;
1035 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001036 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001037 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001038 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001039 }
1040
James Y Knight892b09b2018-10-10 02:53:43 +00001041 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001042 };
1043
George Burgess IV8c892b52016-05-25 22:31:54 +00001044 /// RAII object used to optionally suppress diagnostics and side-effects from
1045 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001046 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001047 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001048 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001049 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001050
George Burgess IV8c892b52016-05-25 22:31:54 +00001051 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001052 Info = Other.Info;
1053 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001054 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001055 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001056 }
1057
1058 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001059 if (!Info)
1060 return;
1061
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001062 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001063 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001064 }
1065
Richard Smith17100ba2012-02-16 02:46:34 +00001066 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001067 SpeculativeEvaluationRAII() = default;
1068
1069 SpeculativeEvaluationRAII(
1070 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001071 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001072 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001073 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001074 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001075 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001076
1077 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1078 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1079 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001080 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001081
1082 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1083 maybeRestoreState();
1084 moveFromAndCancel(std::move(Other));
1085 return *this;
1086 }
1087
1088 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001089 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001090
1091 /// RAII object wrapping a full-expression or block scope, and handling
1092 /// the ending of the lifetime of temporaries created within it.
1093 template<bool IsFullExpression>
1094 class ScopeRAII {
1095 EvalInfo &Info;
1096 unsigned OldStackSize;
1097 public:
1098 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001099 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1100 // Push a new temporary version. This is needed to distinguish between
1101 // temporaries created in different iterations of a loop.
1102 Info.CurrentCall->pushTempVersion();
1103 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001104 ~ScopeRAII() {
1105 // Body moved to a static method to encourage the compiler to inline away
1106 // instances of this class.
1107 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001108 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001109 }
1110 private:
1111 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1112 unsigned NewEnd = OldStackSize;
1113 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1114 I != N; ++I) {
1115 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1116 // Full-expression cleanup of a lifetime-extended temporary: nothing
1117 // to do, just move this cleanup to the right place in the stack.
1118 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1119 ++NewEnd;
1120 } else {
1121 // End the lifetime of the object.
1122 Info.CleanupStack[I].endLifetime();
1123 }
1124 }
1125 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1126 Info.CleanupStack.end());
1127 }
1128 };
1129 typedef ScopeRAII<false> BlockScopeRAII;
1130 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001131}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001132
Richard Smitha8105bc2012-01-06 16:39:00 +00001133bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1134 CheckSubobjectKind CSK) {
1135 if (Invalid)
1136 return false;
1137 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001138 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001139 << CSK;
1140 setInvalid();
1141 return false;
1142 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001143 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1144 // must actually be at least one array element; even a VLA cannot have a
1145 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001146 return true;
1147}
1148
Richard Smith6f4f0f12017-10-20 22:56:25 +00001149void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1150 const Expr *E) {
1151 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1152 // Do not set the designator as invalid: we can represent this situation,
1153 // and correct handling of __builtin_object_size requires us to do so.
1154}
1155
Richard Smitha8105bc2012-01-06 16:39:00 +00001156void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001157 const Expr *E,
1158 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001159 // If we're complaining, we must be able to statically determine the size of
1160 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001161 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001162 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001163 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001164 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001165 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001166 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001167 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001168 setInvalid();
1169}
1170
Richard Smithf6f003a2011-12-16 19:06:07 +00001171CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1172 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001173 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001174 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1175 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001176 Info.CurrentCall = this;
1177 ++Info.CallStackDepth;
1178}
1179
1180CallStackFrame::~CallStackFrame() {
1181 assert(Info.CurrentCall == this && "calls retired out of order");
1182 --Info.CallStackDepth;
1183 Info.CurrentCall = Caller;
1184}
1185
Richard Smith08d6a2c2013-07-24 07:11:57 +00001186APValue &CallStackFrame::createTemporary(const void *Key,
1187 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001188 unsigned Version = Info.CurrentCall->getTempVersion();
1189 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001190 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001191 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1192 return Result;
1193}
1194
Richard Smithc667cdc2019-09-18 17:37:44 +00001195static bool isRead(AccessKinds AK) {
1196 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1197}
1198
Richard Smithdebad642019-05-12 09:39:08 +00001199static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001200 switch (AK) {
1201 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001202 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001203 case AK_MemberCall:
1204 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001205 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001206 return false;
1207 case AK_Assign:
1208 case AK_Increment:
1209 case AK_Decrement:
1210 return true;
1211 }
1212 llvm_unreachable("unknown access kind");
1213}
1214
1215/// Is this an access per the C++ definition?
1216static bool isFormalAccess(AccessKinds AK) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001217 return isRead(AK) || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001218}
1219
Richard Smithf6f003a2011-12-16 19:06:07 +00001220namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001221 struct ComplexValue {
1222 private:
1223 bool IsInt;
1224
1225 public:
1226 APSInt IntReal, IntImag;
1227 APFloat FloatReal, FloatImag;
1228
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001229 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001230
1231 void makeComplexFloat() { IsInt = false; }
1232 bool isComplexFloat() const { return !IsInt; }
1233 APFloat &getComplexFloatReal() { return FloatReal; }
1234 APFloat &getComplexFloatImag() { return FloatImag; }
1235
1236 void makeComplexInt() { IsInt = true; }
1237 bool isComplexInt() const { return IsInt; }
1238 APSInt &getComplexIntReal() { return IntReal; }
1239 APSInt &getComplexIntImag() { return IntImag; }
1240
Richard Smith2e312c82012-03-03 22:46:17 +00001241 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001242 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001243 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001244 else
Richard Smith2e312c82012-03-03 22:46:17 +00001245 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001246 }
Richard Smith2e312c82012-03-03 22:46:17 +00001247 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001248 assert(v.isComplexFloat() || v.isComplexInt());
1249 if (v.isComplexFloat()) {
1250 makeComplexFloat();
1251 FloatReal = v.getComplexFloatReal();
1252 FloatImag = v.getComplexFloatImag();
1253 } else {
1254 makeComplexInt();
1255 IntReal = v.getComplexIntReal();
1256 IntImag = v.getComplexIntImag();
1257 }
1258 }
John McCall93d91dc2010-05-07 17:22:02 +00001259 };
John McCall45d55e42010-05-07 21:00:08 +00001260
1261 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001262 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001263 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001264 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001265 bool IsNullPtr : 1;
1266 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001267
Richard Smithce40ad62011-11-12 22:28:03 +00001268 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001269 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001270 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001271 SubobjectDesignator &getLValueDesignator() { return Designator; }
1272 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001273 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001274
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001275 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1276 unsigned getLValueVersion() const { return Base.getVersion(); }
1277
Richard Smith2e312c82012-03-03 22:46:17 +00001278 void moveInto(APValue &V) const {
1279 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001280 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001281 else {
1282 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001283 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001284 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001285 }
John McCall45d55e42010-05-07 21:00:08 +00001286 }
Richard Smith2e312c82012-03-03 22:46:17 +00001287 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001288 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001289 Base = V.getLValueBase();
1290 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001291 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001292 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001293 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001294 }
1295
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001296 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001297#ifndef NDEBUG
1298 // We only allow a few types of invalid bases. Enforce that here.
1299 if (BInvalid) {
1300 const auto *E = B.get<const Expr *>();
1301 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1302 "Unexpected type of invalid base");
1303 }
1304#endif
1305
Richard Smithce40ad62011-11-12 22:28:03 +00001306 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001307 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001308 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001309 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001310 IsNullPtr = false;
1311 }
1312
1313 void setNull(QualType PointerTy, uint64_t TargetVal) {
1314 Base = (Expr *)nullptr;
1315 Offset = CharUnits::fromQuantity(TargetVal);
1316 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001317 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1318 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001319 }
1320
George Burgess IV3a03fab2015-09-04 21:28:13 +00001321 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001322 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001323 }
1324
Hubert Tong147b7432018-12-12 16:53:43 +00001325 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001326 // Check that this LValue is not based on a null pointer. If it is, produce
1327 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001328 template <typename GenDiagType>
1329 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001330 if (Designator.Invalid)
1331 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001332 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001333 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001334 Designator.setInvalid();
1335 return false;
1336 }
1337 return true;
1338 }
1339
Hubert Tong147b7432018-12-12 16:53:43 +00001340 public:
1341 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1342 CheckSubobjectKind CSK) {
1343 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1344 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1345 });
1346 }
1347
1348 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1349 AccessKinds AK) {
1350 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1351 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1352 });
1353 }
1354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 // Check this LValue refers to an object. If not, set the designator to be
1356 // invalid and emit a diagnostic.
1357 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001358 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001359 Designator.checkSubobject(Info, E, CSK);
1360 }
1361
1362 void addDecl(EvalInfo &Info, const Expr *E,
1363 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001364 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1365 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001366 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001367 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1368 if (!Designator.Entries.empty()) {
1369 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1370 Designator.setInvalid();
1371 return;
1372 }
Richard Smithefdb5032017-11-15 03:03:56 +00001373 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1374 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1375 Designator.FirstEntryIsAnUnsizedArray = true;
1376 Designator.addUnsizedArrayUnchecked(ElemTy);
1377 }
George Burgess IVe3763372016-12-22 02:50:20 +00001378 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001379 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001380 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1381 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001382 }
Richard Smith66c96992012-02-18 22:04:06 +00001383 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001384 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1385 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001386 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001387 void clearIsNullPointer() {
1388 IsNullPtr = false;
1389 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001390 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1391 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001392 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1393 // but we're not required to diagnose it and it's valid in C++.)
1394 if (!Index)
1395 return;
1396
1397 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1398 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1399 // offsets.
1400 uint64_t Offset64 = Offset.getQuantity();
1401 uint64_t ElemSize64 = ElementSize.getQuantity();
1402 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1403 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1404
1405 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001406 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001407 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001408 }
1409 void adjustOffset(CharUnits N) {
1410 Offset += N;
1411 if (N.getQuantity())
1412 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001413 }
John McCall45d55e42010-05-07 21:00:08 +00001414 };
Richard Smith027bf112011-11-17 22:56:20 +00001415
1416 struct MemberPtr {
1417 MemberPtr() {}
1418 explicit MemberPtr(const ValueDecl *Decl) :
1419 DeclAndIsDerivedMember(Decl, false), Path() {}
1420
1421 /// The member or (direct or indirect) field referred to by this member
1422 /// pointer, or 0 if this is a null member pointer.
1423 const ValueDecl *getDecl() const {
1424 return DeclAndIsDerivedMember.getPointer();
1425 }
1426 /// Is this actually a member of some type derived from the relevant class?
1427 bool isDerivedMember() const {
1428 return DeclAndIsDerivedMember.getInt();
1429 }
1430 /// Get the class which the declaration actually lives in.
1431 const CXXRecordDecl *getContainingRecord() const {
1432 return cast<CXXRecordDecl>(
1433 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1434 }
1435
Richard Smith2e312c82012-03-03 22:46:17 +00001436 void moveInto(APValue &V) const {
1437 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001438 }
Richard Smith2e312c82012-03-03 22:46:17 +00001439 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001440 assert(V.isMemberPointer());
1441 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1442 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1443 Path.clear();
1444 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1445 Path.insert(Path.end(), P.begin(), P.end());
1446 }
1447
1448 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1449 /// whether the member is a member of some class derived from the class type
1450 /// of the member pointer.
1451 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1452 /// Path - The path of base/derived classes from the member declaration's
1453 /// class (exclusive) to the class type of the member pointer (inclusive).
1454 SmallVector<const CXXRecordDecl*, 4> Path;
1455
1456 /// Perform a cast towards the class of the Decl (either up or down the
1457 /// hierarchy).
1458 bool castBack(const CXXRecordDecl *Class) {
1459 assert(!Path.empty());
1460 const CXXRecordDecl *Expected;
1461 if (Path.size() >= 2)
1462 Expected = Path[Path.size() - 2];
1463 else
1464 Expected = getContainingRecord();
1465 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1466 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1467 // if B does not contain the original member and is not a base or
1468 // derived class of the class containing the original member, the result
1469 // of the cast is undefined.
1470 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1471 // (D::*). We consider that to be a language defect.
1472 return false;
1473 }
1474 Path.pop_back();
1475 return true;
1476 }
1477 /// Perform a base-to-derived member pointer cast.
1478 bool castToDerived(const CXXRecordDecl *Derived) {
1479 if (!getDecl())
1480 return true;
1481 if (!isDerivedMember()) {
1482 Path.push_back(Derived);
1483 return true;
1484 }
1485 if (!castBack(Derived))
1486 return false;
1487 if (Path.empty())
1488 DeclAndIsDerivedMember.setInt(false);
1489 return true;
1490 }
1491 /// Perform a derived-to-base member pointer cast.
1492 bool castToBase(const CXXRecordDecl *Base) {
1493 if (!getDecl())
1494 return true;
1495 if (Path.empty())
1496 DeclAndIsDerivedMember.setInt(true);
1497 if (isDerivedMember()) {
1498 Path.push_back(Base);
1499 return true;
1500 }
1501 return castBack(Base);
1502 }
1503 };
Richard Smith357362d2011-12-13 06:39:58 +00001504
Richard Smith7bb00672012-02-01 01:42:44 +00001505 /// Compare two member pointers, which are assumed to be of the same type.
1506 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1507 if (!LHS.getDecl() || !RHS.getDecl())
1508 return !LHS.getDecl() && !RHS.getDecl();
1509 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1510 return false;
1511 return LHS.Path == RHS.Path;
1512 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001513}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001514
Richard Smith2e312c82012-03-03 22:46:17 +00001515static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001516static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1517 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001518 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001519static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1520 bool InvalidBaseOK = false);
1521static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1522 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001523static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1524 EvalInfo &Info);
1525static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001526static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001527static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001528 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001529static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001530static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001531static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1532 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001533static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001534
Leonard Chand3f3e162019-01-18 21:04:25 +00001535/// Evaluate an integer or fixed point expression into an APResult.
1536static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1537 EvalInfo &Info);
1538
1539/// Evaluate only a fixed point expression into an APResult.
1540static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1541 EvalInfo &Info);
1542
Chris Lattner05706e882008-07-11 18:11:29 +00001543//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001544// Misc utilities
1545//===----------------------------------------------------------------------===//
1546
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001547/// A helper function to create a temporary and set an LValue.
1548template <class KeyTy>
1549static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1550 LValue &LV, CallStackFrame &Frame) {
1551 LV.set({Key, Frame.Info.CurrentCall->Index,
1552 Frame.Info.CurrentCall->getTempVersion()});
1553 return Frame.createTemporary(Key, IsLifetimeExtended);
1554}
1555
Richard Smithd6cc1982017-01-31 02:23:02 +00001556/// Negate an APSInt in place, converting it to a signed form if necessary, and
1557/// preserving its value (by extending by up to one bit as needed).
1558static void negateAsSigned(APSInt &Int) {
1559 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1560 Int = Int.extend(Int.getBitWidth() + 1);
1561 Int.setIsSigned(true);
1562 }
1563 Int = -Int;
1564}
1565
Richard Smith84401042013-06-03 05:03:02 +00001566/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001567void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001568 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001569 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1570 !isa<CXXConstructorDecl>(Callee) &&
1571 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001572
1573 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001574 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001575
Nandor Licker950b70d2019-09-13 09:46:16 +00001576 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001577 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001578 This->moveInto(Val);
1579 Val.printPretty(Out, Info.Ctx,
1580 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001581 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001582 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001583 IsMemberCall = false;
1584 }
1585
Nandor Licker950b70d2019-09-13 09:46:16 +00001586 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1587 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001588 if (ArgIndex > (unsigned)IsMemberCall)
1589 Out << ", ";
1590
1591 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001592 const APValue &Arg = Arguments[ArgIndex];
1593 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001594
1595 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001596 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001597 }
1598
1599 Out << ')';
1600}
1601
Richard Smithd9f663b2013-04-22 15:31:51 +00001602/// Evaluate an expression to see if it had side-effects, and discard its
1603/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001604/// \return \c true if the caller should keep evaluating.
1605static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001606 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001607 if (!Evaluate(Scratch, Info, E))
1608 // We don't need the value, but we might have skipped a side effect here.
1609 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001610 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001611}
1612
Richard Smithd62306a2011-11-10 06:34:14 +00001613/// Should this call expression be treated as a string literal?
1614static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001615 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001616 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1617 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1618}
1619
Richard Smithce40ad62011-11-12 22:28:03 +00001620static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001621 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1622 // constant expression of pointer type that evaluates to...
1623
1624 // ... a null pointer value, or a prvalue core constant expression of type
1625 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001626 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001627
Richard Smithce40ad62011-11-12 22:28:03 +00001628 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1629 // ... the address of an object with static storage duration,
1630 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1631 return VD->hasGlobalStorage();
1632 // ... the address of a function,
1633 return isa<FunctionDecl>(D);
1634 }
1635
Richard Smithee0ce3022019-05-17 07:06:46 +00001636 if (B.is<TypeInfoLValue>())
1637 return true;
1638
Richard Smithce40ad62011-11-12 22:28:03 +00001639 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001640 switch (E->getStmtClass()) {
1641 default:
1642 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001643 case Expr::CompoundLiteralExprClass: {
1644 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1645 return CLE->isFileScope() && CLE->isLValue();
1646 }
Richard Smithe6c01442013-06-05 00:46:14 +00001647 case Expr::MaterializeTemporaryExprClass:
1648 // A materialized temporary might have been lifetime-extended to static
1649 // storage duration.
1650 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001651 // A string literal has static storage duration.
1652 case Expr::StringLiteralClass:
1653 case Expr::PredefinedExprClass:
1654 case Expr::ObjCStringLiteralClass:
1655 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001656 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001657 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001658 case Expr::ObjCBoxedExprClass:
1659 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001660 case Expr::CallExprClass:
1661 return IsStringLiteralCall(cast<CallExpr>(E));
1662 // For GCC compatibility, &&label has static storage duration.
1663 case Expr::AddrLabelExprClass:
1664 return true;
1665 // A Block literal expression may be used as the initialization value for
1666 // Block variables at global or local static scope.
1667 case Expr::BlockExprClass:
1668 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001669 case Expr::ImplicitValueInitExprClass:
1670 // FIXME:
1671 // We can never form an lvalue with an implicit value initialization as its
1672 // base through expression evaluation, so these only appear in one case: the
1673 // implicit variable declaration we invent when checking whether a constexpr
1674 // constructor can produce a constant expression. We must assume that such
1675 // an expression might be a global lvalue.
1676 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001677 }
John McCall95007602010-05-10 23:27:23 +00001678}
1679
Richard Smith06f71b52018-08-04 00:57:17 +00001680static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1681 return LVal.Base.dyn_cast<const ValueDecl*>();
1682}
1683
1684static bool IsLiteralLValue(const LValue &Value) {
1685 if (Value.getLValueCallIndex())
1686 return false;
1687 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1688 return E && !isa<MaterializeTemporaryExpr>(E);
1689}
1690
1691static bool IsWeakLValue(const LValue &Value) {
1692 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1693 return Decl && Decl->isWeak();
1694}
1695
1696static bool isZeroSized(const LValue &Value) {
1697 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1698 if (Decl && isa<VarDecl>(Decl)) {
1699 QualType Ty = Decl->getType();
1700 if (Ty->isArrayType())
1701 return Ty->isIncompleteType() ||
1702 Decl->getASTContext().getTypeSize(Ty) == 0;
1703 }
1704 return false;
1705}
1706
1707static bool HasSameBase(const LValue &A, const LValue &B) {
1708 if (!A.getLValueBase())
1709 return !B.getLValueBase();
1710 if (!B.getLValueBase())
1711 return false;
1712
1713 if (A.getLValueBase().getOpaqueValue() !=
1714 B.getLValueBase().getOpaqueValue()) {
1715 const Decl *ADecl = GetLValueBaseDecl(A);
1716 if (!ADecl)
1717 return false;
1718 const Decl *BDecl = GetLValueBaseDecl(B);
1719 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1720 return false;
1721 }
1722
1723 return IsGlobalLValue(A.getLValueBase()) ||
1724 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1725 A.getLValueVersion() == B.getLValueVersion());
1726}
1727
Richard Smithb228a862012-02-15 02:18:13 +00001728static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1729 assert(Base && "no location for a null lvalue");
1730 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1731 if (VD)
1732 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001733 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1734 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1735 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001736}
1737
Richard Smith80815602011-11-07 05:07:52 +00001738/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001739/// value for an address or reference constant expression. Return true if we
1740/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001741static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001742 QualType Type, const LValue &LVal,
1743 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001744 bool IsReferenceType = Type->isReferenceType();
1745
Richard Smith357362d2011-12-13 06:39:58 +00001746 APValue::LValueBase Base = LVal.getLValueBase();
1747 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1748
Richard Smith0dea49e2012-02-18 04:58:18 +00001749 // Check that the object is a global. Note that the fake 'this' object we
1750 // manufacture when checking potential constant expressions is conservatively
1751 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001752 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001753 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001754 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001755 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001756 << IsReferenceType << !Designator.Entries.empty()
1757 << !!VD << VD;
1758 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001759 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001760 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001761 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001762 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001763 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001764 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001765 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001766 LVal.getLValueCallIndex() == 0) &&
1767 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001768
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001769 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1770 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001771 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001772 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001773 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001774
Hans Wennborg82dd8772014-06-25 22:19:48 +00001775 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001776 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001777 return false;
1778 }
1779 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1780 // __declspec(dllimport) must be handled very carefully:
1781 // We must never initialize an expression with the thunk in C++.
1782 // Doing otherwise would allow the same id-expression to yield
1783 // different addresses for the same function in different translation
1784 // units. However, this means that we must dynamically initialize the
1785 // expression with the contents of the import address table at runtime.
1786 //
1787 // The C language has no notion of ODR; furthermore, it has no notion of
1788 // dynamic initialization. This means that we are permitted to
1789 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001790 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1791 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001792 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001793 }
1794 }
1795
Richard Smitha8105bc2012-01-06 16:39:00 +00001796 // Allow address constant expressions to be past-the-end pointers. This is
1797 // an extension: the standard requires them to point to an object.
1798 if (!IsReferenceType)
1799 return true;
1800
1801 // A reference constant expression must refer to an object.
1802 if (!Base) {
1803 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001804 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001805 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001806 }
1807
Richard Smith357362d2011-12-13 06:39:58 +00001808 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001809 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001810 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001811 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001812 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001813 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001814 }
1815
Richard Smith80815602011-11-07 05:07:52 +00001816 return true;
1817}
1818
Reid Klecknercd016d82017-07-07 22:04:29 +00001819/// Member pointers are constant expressions unless they point to a
1820/// non-virtual dllimport member function.
1821static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1822 SourceLocation Loc,
1823 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001824 const APValue &Value,
1825 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001826 const ValueDecl *Member = Value.getMemberPointerDecl();
1827 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1828 if (!FD)
1829 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001830 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1831 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001832}
1833
Richard Smithfddd3842011-12-30 21:15:51 +00001834/// Check that this core constant expression is of literal type, and if not,
1835/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001836static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001837 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001838 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001839 return true;
1840
Richard Smith7525ff62013-05-09 07:14:00 +00001841 // C++1y: A constant initializer for an object o [...] may also invoke
1842 // constexpr constructors for o and its subobjects even if those objects
1843 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001844 //
1845 // C++11 missed this detail for aggregates, so classes like this:
1846 // struct foo_t { union { int i; volatile int j; } u; };
1847 // are not (obviously) initializable like so:
1848 // __attribute__((__require_constant_initialization__))
1849 // static const foo_t x = {{0}};
1850 // because "i" is a subobject with non-literal initialization (due to the
1851 // volatile member of the union). See:
1852 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1853 // Therefore, we use the C++1y behavior.
1854 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001855 return true;
1856
Richard Smithfddd3842011-12-30 21:15:51 +00001857 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001858 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001859 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001860 << E->getType();
1861 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001862 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001863 return false;
1864}
1865
Richard Smithc667cdc2019-09-18 17:37:44 +00001866enum class CheckEvaluationResultKind {
1867 ConstantExpression,
1868 FullyInitialized,
1869};
1870
Reid Kleckner1a840d22018-05-10 18:57:35 +00001871static bool
Richard Smithc667cdc2019-09-18 17:37:44 +00001872CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
1873 SourceLocation DiagLoc, QualType Type,
1874 const APValue &Value, Expr::ConstExprUsage Usage,
1875 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00001876 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001877 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001878 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00001879 if (SubobjectLoc.isValid())
1880 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00001881 return false;
1882 }
1883
Richard Smith77be48a2014-07-31 06:31:19 +00001884 // We allow _Atomic(T) to be initialized from anything that T can be
1885 // initialized from.
1886 if (const AtomicType *AT = Type->getAs<AtomicType>())
1887 Type = AT->getValueType();
1888
Richard Smithb228a862012-02-15 02:18:13 +00001889 // Core issue 1454: For a literal constant expression of array or class type,
1890 // each subobject of its value shall have been initialized by a constant
1891 // expression.
1892 if (Value.isArray()) {
1893 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1894 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001895 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1896 Value.getArrayInitializedElt(I), Usage,
1897 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00001898 return false;
1899 }
1900 if (!Value.hasArrayFiller())
1901 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00001902 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1903 Value.getArrayFiller(), Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00001904 }
Richard Smithb228a862012-02-15 02:18:13 +00001905 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001906 return CheckEvaluationResult(
1907 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
1908 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00001909 }
1910 if (Value.isStruct()) {
1911 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1912 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1913 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001914 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001915 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
1916 Value.getStructBase(BaseIndex), Usage,
1917 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00001918 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001920 }
1921 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001922 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001923 if (I->isUnnamedBitfield())
1924 continue;
1925
Richard Smithc667cdc2019-09-18 17:37:44 +00001926 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
1927 Value.getStructField(I->getFieldIndex()),
1928 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00001929 return false;
1930 }
1931 }
1932
Richard Smithc667cdc2019-09-18 17:37:44 +00001933 if (Value.isLValue() &&
1934 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00001935 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001936 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001937 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001938 }
1939
Richard Smithc667cdc2019-09-18 17:37:44 +00001940 if (Value.isMemberPointer() &&
1941 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00001942 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001943
Richard Smithb228a862012-02-15 02:18:13 +00001944 // Everything else is fine.
1945 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001946}
1947
Richard Smithc667cdc2019-09-18 17:37:44 +00001948/// Check that this core constant expression value is a valid value for a
1949/// constant expression. If not, report an appropriate diagnostic. Does not
1950/// check that the expression is of literal type.
1951static bool
1952CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1953 const APValue &Value,
1954 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1955 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
1956 Info, DiagLoc, Type, Value, Usage);
1957}
1958
1959/// Check that this evaluated value is fully-initialized and can be loaded by
1960/// an lvalue-to-rvalue conversion.
1961static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
1962 QualType Type, const APValue &Value) {
1963 return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
1964 Info, DiagLoc, Type, Value,
1965 Expr::EvaluateForCodeGen);
1966}
1967
Richard Smith2e312c82012-03-03 22:46:17 +00001968static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001969 // A null base expression indicates a null pointer. These are always
1970 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001971 if (!Value.getLValueBase()) {
1972 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001973 return true;
1974 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001975
Richard Smith027bf112011-11-17 22:56:20 +00001976 // We have a non-null base. These are generally known to be true, but if it's
1977 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001978 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001979 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001980 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001981}
1982
Richard Smith2e312c82012-03-03 22:46:17 +00001983static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001984 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00001985 case APValue::None:
1986 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00001987 return false;
1988 case APValue::Int:
1989 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001990 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00001991 case APValue::FixedPoint:
1992 Result = Val.getFixedPoint().getBoolValue();
1993 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001994 case APValue::Float:
1995 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001996 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001997 case APValue::ComplexInt:
1998 Result = Val.getComplexIntReal().getBoolValue() ||
1999 Val.getComplexIntImag().getBoolValue();
2000 return true;
2001 case APValue::ComplexFloat:
2002 Result = !Val.getComplexFloatReal().isZero() ||
2003 !Val.getComplexFloatImag().isZero();
2004 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002005 case APValue::LValue:
2006 return EvalPointerValueAsBool(Val, Result);
2007 case APValue::MemberPointer:
2008 Result = Val.getMemberPointerDecl();
2009 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002010 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002011 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002012 case APValue::Struct:
2013 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002014 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002015 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002016 }
2017
Richard Smith11562c52011-10-28 17:51:58 +00002018 llvm_unreachable("unknown APValue kind");
2019}
2020
2021static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2022 EvalInfo &Info) {
2023 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002024 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002025 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002026 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002027 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002028}
2029
Richard Smith357362d2011-12-13 06:39:58 +00002030template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002031static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002032 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002033 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002034 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002035 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002036}
2037
2038static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2039 QualType SrcType, const APFloat &Value,
2040 QualType DestType, APSInt &Result) {
2041 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002042 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002043 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002044
Richard Smith357362d2011-12-13 06:39:58 +00002045 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002046 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002047 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2048 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002049 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002050 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002051}
2052
Richard Smith357362d2011-12-13 06:39:58 +00002053static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2054 QualType SrcType, QualType DestType,
2055 APFloat &Result) {
2056 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002057 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002058 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2059 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002060 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002061}
2062
Richard Smith911e1422012-01-30 22:27:01 +00002063static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2064 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002065 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002066 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002067 // Figure out if this is a truncate, extend or noop cast.
2068 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002069 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002070 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002071 if (DestType->isBooleanType())
2072 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002073 return Result;
2074}
2075
Richard Smith357362d2011-12-13 06:39:58 +00002076static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2077 QualType SrcType, const APSInt &Value,
2078 QualType DestType, APFloat &Result) {
2079 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002080 Result.convertFromAPInt(Value, Value.isSigned(),
2081 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002082 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002083}
2084
Richard Smith49ca8aa2013-08-06 07:09:20 +00002085static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2086 APValue &Value, const FieldDecl *FD) {
2087 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2088
2089 if (!Value.isInt()) {
2090 // Trying to store a pointer-cast-to-integer into a bitfield.
2091 // FIXME: In this case, we should provide the diagnostic for casting
2092 // a pointer to an integer.
2093 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002094 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002095 return false;
2096 }
2097
2098 APSInt &Int = Value.getInt();
2099 unsigned OldBitWidth = Int.getBitWidth();
2100 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2101 if (NewBitWidth < OldBitWidth)
2102 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2103 return true;
2104}
2105
Eli Friedman803acb32011-12-22 03:51:45 +00002106static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2107 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002108 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002109 if (!Evaluate(SVal, Info, E))
2110 return false;
2111 if (SVal.isInt()) {
2112 Res = SVal.getInt();
2113 return true;
2114 }
2115 if (SVal.isFloat()) {
2116 Res = SVal.getFloat().bitcastToAPInt();
2117 return true;
2118 }
2119 if (SVal.isVector()) {
2120 QualType VecTy = E->getType();
2121 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2122 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2123 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2124 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2125 Res = llvm::APInt::getNullValue(VecSize);
2126 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2127 APValue &Elt = SVal.getVectorElt(i);
2128 llvm::APInt EltAsInt;
2129 if (Elt.isInt()) {
2130 EltAsInt = Elt.getInt();
2131 } else if (Elt.isFloat()) {
2132 EltAsInt = Elt.getFloat().bitcastToAPInt();
2133 } else {
2134 // Don't try to handle vectors of anything other than int or float
2135 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002136 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002137 return false;
2138 }
2139 unsigned BaseEltSize = EltAsInt.getBitWidth();
2140 if (BigEndian)
2141 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2142 else
2143 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2144 }
2145 return true;
2146 }
2147 // Give up if the input isn't an int, float, or vector. For example, we
2148 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002149 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002150 return false;
2151}
2152
Richard Smith43e77732013-05-07 04:50:00 +00002153/// Perform the given integer operation, which is known to need at most BitWidth
2154/// bits, and check for overflow in the original type (if that type was not an
2155/// unsigned type).
2156template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002157static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2158 const APSInt &LHS, const APSInt &RHS,
2159 unsigned BitWidth, Operation Op,
2160 APSInt &Result) {
2161 if (LHS.isUnsigned()) {
2162 Result = Op(LHS, RHS);
2163 return true;
2164 }
Richard Smith43e77732013-05-07 04:50:00 +00002165
2166 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002167 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002168 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002169 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002170 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002171 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002172 << Result.toString(10) << E->getType();
2173 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002174 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002175 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002176 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002177}
2178
2179/// Perform the given binary integer operation.
2180static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2181 BinaryOperatorKind Opcode, APSInt RHS,
2182 APSInt &Result) {
2183 switch (Opcode) {
2184 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002185 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002186 return false;
2187 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002188 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2189 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002190 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002191 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2192 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002193 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002194 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2195 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002196 case BO_And: Result = LHS & RHS; return true;
2197 case BO_Xor: Result = LHS ^ RHS; return true;
2198 case BO_Or: Result = LHS | RHS; return true;
2199 case BO_Div:
2200 case BO_Rem:
2201 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002202 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002203 return false;
2204 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002205 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2206 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2207 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002208 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2209 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002210 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2211 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002212 return true;
2213 case BO_Shl: {
2214 if (Info.getLangOpts().OpenCL)
2215 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2216 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2217 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2218 RHS.isUnsigned());
2219 else if (RHS.isSigned() && RHS.isNegative()) {
2220 // During constant-folding, a negative shift is an opposite shift. Such
2221 // a shift is not a constant expression.
2222 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2223 RHS = -RHS;
2224 goto shift_right;
2225 }
2226 shift_left:
2227 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2228 // the shifted type.
2229 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2230 if (SA != RHS) {
2231 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2232 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002233 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002234 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2235 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002236 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2237 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002238 if (LHS.isNegative())
2239 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2240 else if (LHS.countLeadingZeros() < SA)
2241 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2242 }
2243 Result = LHS << SA;
2244 return true;
2245 }
2246 case BO_Shr: {
2247 if (Info.getLangOpts().OpenCL)
2248 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2249 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2250 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2251 RHS.isUnsigned());
2252 else if (RHS.isSigned() && RHS.isNegative()) {
2253 // During constant-folding, a negative shift is an opposite shift. Such a
2254 // shift is not a constant expression.
2255 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2256 RHS = -RHS;
2257 goto shift_left;
2258 }
2259 shift_right:
2260 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2261 // shifted type.
2262 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2263 if (SA != RHS)
2264 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2265 << RHS << E->getType() << LHS.getBitWidth();
2266 Result = LHS >> SA;
2267 return true;
2268 }
2269
2270 case BO_LT: Result = LHS < RHS; return true;
2271 case BO_GT: Result = LHS > RHS; return true;
2272 case BO_LE: Result = LHS <= RHS; return true;
2273 case BO_GE: Result = LHS >= RHS; return true;
2274 case BO_EQ: Result = LHS == RHS; return true;
2275 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002276 case BO_Cmp:
2277 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002278 }
2279}
2280
Richard Smith861b5b52013-05-07 23:34:45 +00002281/// Perform the given binary floating-point operation, in-place, on LHS.
2282static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2283 APFloat &LHS, BinaryOperatorKind Opcode,
2284 const APFloat &RHS) {
2285 switch (Opcode) {
2286 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002287 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002288 return false;
2289 case BO_Mul:
2290 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2291 break;
2292 case BO_Add:
2293 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2294 break;
2295 case BO_Sub:
2296 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2297 break;
2298 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002299 // [expr.mul]p4:
2300 // If the second operand of / or % is zero the behavior is undefined.
2301 if (RHS.isZero())
2302 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002303 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2304 break;
2305 }
2306
Richard Smith9e52c432019-07-06 21:05:52 +00002307 // [expr.pre]p4:
2308 // If during the evaluation of an expression, the result is not
2309 // mathematically defined [...], the behavior is undefined.
2310 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2311 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002312 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002313 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002314 }
Richard Smith861b5b52013-05-07 23:34:45 +00002315 return true;
2316}
2317
Richard Smitha8105bc2012-01-06 16:39:00 +00002318/// Cast an lvalue referring to a base subobject to a derived class, by
2319/// truncating the lvalue's path to the given length.
2320static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2321 const RecordDecl *TruncatedType,
2322 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002323 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002324
2325 // Check we actually point to a derived class object.
2326 if (TruncatedElements == D.Entries.size())
2327 return true;
2328 assert(TruncatedElements >= D.MostDerivedPathLength &&
2329 "not casting to a derived class");
2330 if (!Result.checkSubobject(Info, E, CSK_Derived))
2331 return false;
2332
2333 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002334 const RecordDecl *RD = TruncatedType;
2335 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002336 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002337 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2338 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002339 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002340 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002341 else
Richard Smithd62306a2011-11-10 06:34:14 +00002342 Result.Offset -= Layout.getBaseClassOffset(Base);
2343 RD = Base;
2344 }
Richard Smith027bf112011-11-17 22:56:20 +00002345 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002346 return true;
2347}
2348
John McCalld7bca762012-05-01 00:38:49 +00002349static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002350 const CXXRecordDecl *Derived,
2351 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002352 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002353 if (!RL) {
2354 if (Derived->isInvalidDecl()) return false;
2355 RL = &Info.Ctx.getASTRecordLayout(Derived);
2356 }
2357
Richard Smithd62306a2011-11-10 06:34:14 +00002358 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002359 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002360 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002361}
2362
Richard Smitha8105bc2012-01-06 16:39:00 +00002363static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002364 const CXXRecordDecl *DerivedDecl,
2365 const CXXBaseSpecifier *Base) {
2366 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2367
John McCalld7bca762012-05-01 00:38:49 +00002368 if (!Base->isVirtual())
2369 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002370
Richard Smitha8105bc2012-01-06 16:39:00 +00002371 SubobjectDesignator &D = Obj.Designator;
2372 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002373 return false;
2374
Richard Smitha8105bc2012-01-06 16:39:00 +00002375 // Extract most-derived object and corresponding type.
2376 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2377 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2378 return false;
2379
2380 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002381 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002382 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2383 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002384 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002385 return true;
2386}
2387
Richard Smith84401042013-06-03 05:03:02 +00002388static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2389 QualType Type, LValue &Result) {
2390 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2391 PathE = E->path_end();
2392 PathI != PathE; ++PathI) {
2393 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2394 *PathI))
2395 return false;
2396 Type = (*PathI)->getType();
2397 }
2398 return true;
2399}
2400
Richard Smith921f1322019-05-13 23:35:21 +00002401/// Cast an lvalue referring to a derived class to a known base subobject.
2402static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2403 const CXXRecordDecl *DerivedRD,
2404 const CXXRecordDecl *BaseRD) {
2405 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2406 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2407 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2408 llvm_unreachable("Class must be derived from the passed in base class!");
2409
2410 for (CXXBasePathElement &Elem : Paths.front())
2411 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2412 return false;
2413 return true;
2414}
2415
Richard Smithd62306a2011-11-10 06:34:14 +00002416/// Update LVal to refer to the given field, which must be a member of the type
2417/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002418static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002419 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002420 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002421 if (!RL) {
2422 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002423 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002424 }
Richard Smithd62306a2011-11-10 06:34:14 +00002425
2426 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002427 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002428 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002429 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002430}
2431
Richard Smith1b78b3d2012-01-25 22:15:11 +00002432/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002433static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002434 LValue &LVal,
2435 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002436 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002437 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002438 return false;
2439 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002440}
2441
Richard Smithd62306a2011-11-10 06:34:14 +00002442/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002443static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2444 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002445 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2446 // extension.
2447 if (Type->isVoidType() || Type->isFunctionType()) {
2448 Size = CharUnits::One();
2449 return true;
2450 }
2451
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002452 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002453 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002454 return false;
2455 }
2456
Richard Smithd62306a2011-11-10 06:34:14 +00002457 if (!Type->isConstantSizeType()) {
2458 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002459 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002460 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002461 return false;
2462 }
2463
2464 Size = Info.Ctx.getTypeSizeInChars(Type);
2465 return true;
2466}
2467
2468/// Update a pointer value to model pointer arithmetic.
2469/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002470/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002471/// \param LVal - The pointer value to be updated.
2472/// \param EltTy - The pointee type represented by LVal.
2473/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002474static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2475 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002476 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002477 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002478 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002479 return false;
2480
Yaxun Liu402804b2016-12-15 08:09:08 +00002481 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002482 return true;
2483}
2484
Richard Smithd6cc1982017-01-31 02:23:02 +00002485static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2486 LValue &LVal, QualType EltTy,
2487 int64_t Adjustment) {
2488 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2489 APSInt::get(Adjustment));
2490}
2491
Richard Smith66c96992012-02-18 22:04:06 +00002492/// Update an lvalue to refer to a component of a complex number.
2493/// \param Info - Information about the ongoing evaluation.
2494/// \param LVal - The lvalue to be updated.
2495/// \param EltTy - The complex number's component type.
2496/// \param Imag - False for the real component, true for the imaginary.
2497static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2498 LValue &LVal, QualType EltTy,
2499 bool Imag) {
2500 if (Imag) {
2501 CharUnits SizeOfComponent;
2502 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2503 return false;
2504 LVal.Offset += SizeOfComponent;
2505 }
2506 LVal.addComplex(Info, E, EltTy, Imag);
2507 return true;
2508}
2509
Richard Smith27908702011-10-24 17:54:18 +00002510/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002511///
2512/// \param Info Information about the ongoing evaluation.
2513/// \param E An expression to be used when printing diagnostics.
2514/// \param VD The variable whose initializer should be obtained.
2515/// \param Frame The frame in which the variable was created. Must be null
2516/// if this variable is not local to the evaluation.
2517/// \param Result Filled in with a pointer to the value of the variable.
2518static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2519 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002520 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002521
Richard Smith254a73d2011-10-28 22:34:42 +00002522 // If this is a parameter to an active constexpr function call, perform
2523 // argument substitution.
2524 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002525 // Assume arguments of a potential constant expression are unknown
2526 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002527 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002528 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002529 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002530 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002531 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002532 }
Richard Smith3229b742013-05-05 21:17:10 +00002533 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002534 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002535 }
Richard Smith27908702011-10-24 17:54:18 +00002536
Richard Smithd9f663b2013-04-22 15:31:51 +00002537 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002538 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002539 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2540 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002541 if (!Result) {
2542 // Assume variables referenced within a lambda's call operator that were
2543 // not declared within the call operator are captures and during checking
2544 // of a potential constant expression, assume they are unknown constant
2545 // expressions.
2546 assert(isLambdaCallOperator(Frame->Callee) &&
2547 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2548 "missing value for local variable");
2549 if (Info.checkingPotentialConstantExpression())
2550 return false;
2551 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002552 Info.FFDiag(E->getBeginLoc(),
2553 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002554 << "captures not currently allowed";
2555 return false;
2556 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002557 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002558 }
2559
Richard Smithd0b4dd62011-12-19 06:19:21 +00002560 // Dig out the initializer, and use the declaration which it's attached to.
2561 const Expr *Init = VD->getAnyInitializer(VD);
2562 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002563 // If we're checking a potential constant expression, the variable could be
2564 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002565 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002566 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002567 return false;
2568 }
2569
Richard Smithd62306a2011-11-10 06:34:14 +00002570 // If we're currently evaluating the initializer of this declaration, use that
2571 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002572 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002573 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002574 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002575 }
2576
Richard Smithcecf1842011-11-01 21:06:14 +00002577 // Never evaluate the initializer of a weak variable. We can't be sure that
2578 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002579 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002580 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002581 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002582 }
Richard Smithcecf1842011-11-01 21:06:14 +00002583
Richard Smithd0b4dd62011-12-19 06:19:21 +00002584 // Check that we can fold the initializer. In C++, we will have already done
2585 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002586 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002587 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002588 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002589 Notes.size() + 1) << VD;
2590 Info.Note(VD->getLocation(), diag::note_declared_at);
2591 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002592 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002593 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002594 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002595 Notes.size() + 1) << VD;
2596 Info.Note(VD->getLocation(), diag::note_declared_at);
2597 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002598 }
Richard Smith27908702011-10-24 17:54:18 +00002599
Richard Smith3229b742013-05-05 21:17:10 +00002600 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002601 return true;
Richard Smith27908702011-10-24 17:54:18 +00002602}
2603
Richard Smith11562c52011-10-28 17:51:58 +00002604static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002605 Qualifiers Quals = T.getQualifiers();
2606 return Quals.hasConst() && !Quals.hasVolatile();
2607}
2608
Richard Smithe97cbd72011-11-11 04:05:33 +00002609/// Get the base index of the given base class within an APValue representing
2610/// the given derived class.
2611static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2612 const CXXRecordDecl *Base) {
2613 Base = Base->getCanonicalDecl();
2614 unsigned Index = 0;
2615 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2616 E = Derived->bases_end(); I != E; ++I, ++Index) {
2617 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2618 return Index;
2619 }
2620
2621 llvm_unreachable("base class missing from derived class's bases list");
2622}
2623
Richard Smith3da88fa2013-04-26 14:36:30 +00002624/// Extract the value of a character from a string literal.
2625static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2626 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002627 assert(!isa<SourceLocExpr>(Lit) &&
2628 "SourceLocExpr should have already been converted to a StringLiteral");
2629
Akira Hatanakabc332642017-01-31 02:31:39 +00002630 // FIXME: Support MakeStringConstant
2631 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2632 std::string Str;
2633 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2634 assert(Index <= Str.size() && "Index too large");
2635 return APSInt::getUnsigned(Str.c_str()[Index]);
2636 }
2637
Alexey Bataevec474782014-10-09 08:45:04 +00002638 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2639 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 const StringLiteral *S = cast<StringLiteral>(Lit);
2641 const ConstantArrayType *CAT =
2642 Info.Ctx.getAsConstantArrayType(S->getType());
2643 assert(CAT && "string literal isn't an array");
2644 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002645 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002646
2647 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002648 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002649 if (Index < S->getLength())
2650 Value = S->getCodeUnit(Index);
2651 return Value;
2652}
2653
Richard Smith3da88fa2013-04-26 14:36:30 +00002654// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002655//
2656// FIXME: This is inefficient; we should probably introduce something similar
2657// to the LLVM ConstantDataArray to make this cheaper.
2658static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002659 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002660 const ConstantArrayType *CAT =
2661 Info.Ctx.getAsConstantArrayType(S->getType());
2662 assert(CAT && "string literal isn't an array");
2663 QualType CharType = CAT->getElementType();
2664 assert(CharType->isIntegerType() && "unexpected character type");
2665
2666 unsigned Elts = CAT->getSize().getZExtValue();
2667 Result = APValue(APValue::UninitArray(),
2668 std::min(S->getLength(), Elts), Elts);
2669 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2670 CharType->isUnsignedIntegerType());
2671 if (Result.hasArrayFiller())
2672 Result.getArrayFiller() = APValue(Value);
2673 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2674 Value = S->getCodeUnit(I);
2675 Result.getArrayInitializedElt(I) = APValue(Value);
2676 }
2677}
2678
2679// Expand an array so that it has more than Index filled elements.
2680static void expandArray(APValue &Array, unsigned Index) {
2681 unsigned Size = Array.getArraySize();
2682 assert(Index < Size);
2683
2684 // Always at least double the number of elements for which we store a value.
2685 unsigned OldElts = Array.getArrayInitializedElts();
2686 unsigned NewElts = std::max(Index+1, OldElts * 2);
2687 NewElts = std::min(Size, std::max(NewElts, 8u));
2688
2689 // Copy the data across.
2690 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2691 for (unsigned I = 0; I != OldElts; ++I)
2692 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2693 for (unsigned I = OldElts; I != NewElts; ++I)
2694 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2695 if (NewValue.hasArrayFiller())
2696 NewValue.getArrayFiller() = Array.getArrayFiller();
2697 Array.swap(NewValue);
2698}
2699
Richard Smithb01fe402014-09-16 01:24:02 +00002700/// Determine whether a type would actually be read by an lvalue-to-rvalue
2701/// conversion. If it's of class type, we may assume that the copy operation
2702/// is trivial. Note that this is never true for a union type with fields
2703/// (because the copy always "reads" the active member) and always true for
2704/// a non-class type.
2705static bool isReadByLvalueToRvalueConversion(QualType T) {
2706 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2707 if (!RD || (RD->isUnion() && !RD->field_empty()))
2708 return true;
2709 if (RD->isEmpty())
2710 return false;
2711
2712 for (auto *Field : RD->fields())
2713 if (isReadByLvalueToRvalueConversion(Field->getType()))
2714 return true;
2715
2716 for (auto &BaseSpec : RD->bases())
2717 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2718 return true;
2719
2720 return false;
2721}
2722
2723/// Diagnose an attempt to read from any unreadable field within the specified
2724/// type, which might be a class type.
2725static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2726 QualType T) {
2727 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2728 if (!RD)
2729 return false;
2730
2731 if (!RD->hasMutableFields())
2732 return false;
2733
2734 for (auto *Field : RD->fields()) {
2735 // If we're actually going to read this field in some way, then it can't
2736 // be mutable. If we're in a union, then assigning to a mutable field
2737 // (even an empty one) can change the active member, so that's not OK.
2738 // FIXME: Add core issue number for the union case.
2739 if (Field->isMutable() &&
2740 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002741 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002742 Info.Note(Field->getLocation(), diag::note_declared_at);
2743 return true;
2744 }
2745
2746 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2747 return true;
2748 }
2749
2750 for (auto &BaseSpec : RD->bases())
2751 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2752 return true;
2753
2754 // All mutable fields were empty, and thus not actually read.
2755 return false;
2756}
2757
Richard Smithdebad642019-05-12 09:39:08 +00002758static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2759 APValue::LValueBase Base) {
2760 // A temporary we created.
2761 if (Base.getCallIndex())
2762 return true;
2763
2764 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2765 if (!Evaluating)
2766 return false;
2767
2768 // The variable whose initializer we're evaluating.
2769 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2770 if (declaresSameEntity(Evaluating, BaseD))
2771 return true;
2772
2773 // A temporary lifetime-extended by the variable whose initializer we're
2774 // evaluating.
2775 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2776 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2777 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2778 return true;
2779
2780 return false;
2781}
2782
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002783namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002784/// A handle to a complete object (an object that is not a subobject of
2785/// another object).
2786struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002787 /// The identity of the object.
2788 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002789 /// The value of the complete object.
2790 APValue *Value;
2791 /// The type of the complete object.
2792 QualType Type;
2793
Craig Topper36250ad2014-05-12 05:36:57 +00002794 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002795 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2796 : Base(Base), Value(Value), Type(Type) {}
2797
2798 bool mayReadMutableMembers(EvalInfo &Info) const {
2799 // In C++14 onwards, it is permitted to read a mutable member whose
2800 // lifetime began within the evaluation.
2801 // FIXME: Should we also allow this in C++11?
2802 if (!Info.getLangOpts().CPlusPlus14)
2803 return false;
2804 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002805 }
2806
Richard Smithdebad642019-05-12 09:39:08 +00002807 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002808};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002809} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002810
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002811static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2812 bool IsMutable = false) {
2813 // C++ [basic.type.qualifier]p1:
2814 // - A const object is an object of type const T or a non-mutable subobject
2815 // of a const object.
2816 if (ObjType.isConstQualified() && !IsMutable)
2817 SubobjType.addConst();
2818 // - A volatile object is an object of type const T or a subobject of a
2819 // volatile object.
2820 if (ObjType.isVolatileQualified())
2821 SubobjType.addVolatile();
2822 return SubobjType;
2823}
2824
Richard Smith3da88fa2013-04-26 14:36:30 +00002825/// Find the designated sub-object of an rvalue.
2826template<typename SubobjectHandler>
2827typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002828findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002830 if (Sub.Invalid)
2831 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002832 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002833 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002835 Info.FFDiag(E, Sub.isOnePastTheEnd()
2836 ? diag::note_constexpr_access_past_end
2837 : diag::note_constexpr_access_unsized_array)
2838 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002842 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002843
Richard Smith3229b742013-05-05 21:17:10 +00002844 APValue *O = Obj.Value;
2845 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002846 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002847 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002848
Richard Smithd62306a2011-11-10 06:34:14 +00002849 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002850 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00002851 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithc667cdc2019-09-18 17:37:44 +00002852 if (O->isAbsent() ||
2853 (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
2854 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002855 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002856 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00002857 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00002858 return handler.failed();
2859 }
2860
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002861 // C++ [class.ctor]p5:
2862 // const and volatile semantics are not applied on an object under
2863 // construction.
2864 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2865 ObjType->isRecordType() &&
2866 Info.isEvaluatingConstructor(
2867 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2868 Sub.Entries.begin() + I)) !=
2869 ConstructionPhase::None) {
2870 ObjType = Info.Ctx.getCanonicalType(ObjType);
2871 ObjType.removeLocalConst();
2872 ObjType.removeLocalVolatile();
2873 }
2874
2875 // If this is our last pass, check that the final object type is OK.
2876 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2877 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00002878 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002879 if (Info.getLangOpts().CPlusPlus) {
2880 int DiagKind;
2881 SourceLocation Loc;
2882 const NamedDecl *Decl = nullptr;
2883 if (VolatileField) {
2884 DiagKind = 2;
2885 Loc = VolatileField->getLocation();
2886 Decl = VolatileField;
2887 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
2888 DiagKind = 1;
2889 Loc = VD->getLocation();
2890 Decl = VD;
2891 } else {
2892 DiagKind = 0;
2893 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
2894 Loc = E->getExprLoc();
2895 }
2896 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2897 << handler.AccessKind << DiagKind << Decl;
2898 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
2899 } else {
2900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2901 }
2902 return handler.failed();
2903 }
2904
Richard Smithb01fe402014-09-16 01:24:02 +00002905 // If we are reading an object of class type, there may still be more
2906 // things we need to check: if there are any mutable subobjects, we
2907 // cannot perform this read. (This only happens when performing a trivial
2908 // copy or assignment.)
Richard Smithc667cdc2019-09-18 17:37:44 +00002909 if (ObjType->isRecordType() && isRead(handler.AccessKind) &&
Richard Smithdebad642019-05-12 09:39:08 +00002910 !Obj.mayReadMutableMembers(Info) &&
2911 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002912 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002913 }
Richard Smithb01fe402014-09-16 01:24:02 +00002914
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002915 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00002916 if (!handler.found(*O, ObjType))
2917 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002918
Richard Smith49ca8aa2013-08-06 07:09:20 +00002919 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00002920 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00002921 LastField && LastField->isBitField() &&
2922 !truncateBitfieldValue(Info, E, *O, LastField))
2923 return false;
2924
2925 return true;
2926 }
2927
Craig Topper36250ad2014-05-12 05:36:57 +00002928 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002929 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002930 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002931 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002932 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00002933 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002934 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002935 // Note, it should not be possible to form a pointer with a valid
2936 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002938 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002939 << handler.AccessKind;
2940 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002941 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002942 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002943 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002944
2945 ObjType = CAT->getElementType();
2946
Richard Smith3da88fa2013-04-26 14:36:30 +00002947 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002948 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00002949 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002950 expandArray(*O, Index);
2951 O = &O->getArrayInitializedElt(Index);
2952 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002953 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002954 } else if (ObjType->isAnyComplexType()) {
2955 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00002956 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00002957 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002958 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002959 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002960 << handler.AccessKind;
2961 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002962 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002963 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002964 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002965
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002966 ObjType = getSubobjectType(
2967 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00002968
Richard Smith66c96992012-02-18 22:04:06 +00002969 assert(I == N - 1 && "extracting subobject of scalar?");
2970 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 return handler.found(Index ? O->getComplexIntImag()
2972 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002973 } else {
2974 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002975 return handler.found(Index ? O->getComplexFloatImag()
2976 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002977 }
Richard Smithd62306a2011-11-10 06:34:14 +00002978 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002979 if (Field->isMutable() && isRead(handler.AccessKind) &&
Richard Smithdebad642019-05-12 09:39:08 +00002980 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002981 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002982 << Field;
2983 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002984 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002985 }
2986
Richard Smithd62306a2011-11-10 06:34:14 +00002987 // Next subobject is a class, struct or union field.
2988 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2989 if (RD->isUnion()) {
2990 const FieldDecl *UnionField = O->getUnionField();
2991 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002992 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002993 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002994 << handler.AccessKind << Field << !UnionField << UnionField;
2995 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002996 }
Richard Smithd62306a2011-11-10 06:34:14 +00002997 O = &O->getUnionValue();
2998 } else
2999 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003000
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003001 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003002 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003003 if (Field->getType().isVolatileQualified())
3004 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003005 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003006 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003007 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3008 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3009 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003010
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003011 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003012 }
3013 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003014}
3015
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003016namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003017struct ExtractSubobjectHandler {
3018 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003019 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003020 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003021 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003022
3023 typedef bool result_type;
3024 bool failed() { return false; }
3025 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003026 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003027 if (AccessKind == AK_ReadObjectRepresentation)
3028 return true;
3029 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003030 }
3031 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003032 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003033 return true;
3034 }
3035 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003036 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003037 return true;
3038 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003039};
Richard Smith3229b742013-05-05 21:17:10 +00003040} // end anonymous namespace
3041
Richard Smith3da88fa2013-04-26 14:36:30 +00003042/// Extract the designated sub-object of an rvalue.
3043static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003044 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003045 const SubobjectDesignator &Sub, APValue &Result,
3046 AccessKinds AK = AK_Read) {
3047 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3048 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003049 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003050}
3051
Richard Smith3229b742013-05-05 21:17:10 +00003052namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003053struct ModifySubobjectHandler {
3054 EvalInfo &Info;
3055 APValue &NewVal;
3056 const Expr *E;
3057
3058 typedef bool result_type;
3059 static const AccessKinds AccessKind = AK_Assign;
3060
3061 bool checkConst(QualType QT) {
3062 // Assigning to a const object has undefined behavior.
3063 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003065 return false;
3066 }
3067 return true;
3068 }
3069
3070 bool failed() { return false; }
3071 bool found(APValue &Subobj, QualType SubobjType) {
3072 if (!checkConst(SubobjType))
3073 return false;
3074 // We've been given ownership of NewVal, so just swap it in.
3075 Subobj.swap(NewVal);
3076 return true;
3077 }
3078 bool found(APSInt &Value, QualType SubobjType) {
3079 if (!checkConst(SubobjType))
3080 return false;
3081 if (!NewVal.isInt()) {
3082 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003083 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003084 return false;
3085 }
3086 Value = NewVal.getInt();
3087 return true;
3088 }
3089 bool found(APFloat &Value, QualType SubobjType) {
3090 if (!checkConst(SubobjType))
3091 return false;
3092 Value = NewVal.getFloat();
3093 return true;
3094 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003095};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003096} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003097
Richard Smith3229b742013-05-05 21:17:10 +00003098const AccessKinds ModifySubobjectHandler::AccessKind;
3099
Richard Smith3da88fa2013-04-26 14:36:30 +00003100/// Update the designated sub-object of an rvalue to the given value.
3101static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003102 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003103 const SubobjectDesignator &Sub,
3104 APValue &NewVal) {
3105 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003106 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003107}
3108
Richard Smith84f6dcf2012-02-02 01:16:57 +00003109/// Find the position where two subobject designators diverge, or equivalently
3110/// the length of the common initial subsequence.
3111static unsigned FindDesignatorMismatch(QualType ObjType,
3112 const SubobjectDesignator &A,
3113 const SubobjectDesignator &B,
3114 bool &WasArrayIndex) {
3115 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3116 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003117 if (!ObjType.isNull() &&
3118 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003119 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003120 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003121 WasArrayIndex = true;
3122 return I;
3123 }
Richard Smith66c96992012-02-18 22:04:06 +00003124 if (ObjType->isAnyComplexType())
3125 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3126 else
3127 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003128 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003129 if (A.Entries[I].getAsBaseOrMember() !=
3130 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003131 WasArrayIndex = false;
3132 return I;
3133 }
3134 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3135 // Next subobject is a field.
3136 ObjType = FD->getType();
3137 else
3138 // Next subobject is a base class.
3139 ObjType = QualType();
3140 }
3141 }
3142 WasArrayIndex = false;
3143 return I;
3144}
3145
3146/// Determine whether the given subobject designators refer to elements of the
3147/// same array object.
3148static bool AreElementsOfSameArray(QualType ObjType,
3149 const SubobjectDesignator &A,
3150 const SubobjectDesignator &B) {
3151 if (A.Entries.size() != B.Entries.size())
3152 return false;
3153
George Burgess IVa51c4072015-10-16 01:49:01 +00003154 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003155 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3156 // A is a subobject of the array element.
3157 return false;
3158
3159 // If A (and B) designates an array element, the last entry will be the array
3160 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3161 // of length 1' case, and the entire path must match.
3162 bool WasArrayIndex;
3163 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3164 return CommonLength >= A.Entries.size() - IsArray;
3165}
3166
Richard Smith3229b742013-05-05 21:17:10 +00003167/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003168static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3169 AccessKinds AK, const LValue &LVal,
3170 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003171 if (LVal.InvalidBase) {
3172 Info.FFDiag(E);
3173 return CompleteObject();
3174 }
3175
Richard Smith3229b742013-05-05 21:17:10 +00003176 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003177 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003178 return CompleteObject();
3179 }
3180
Craig Topper36250ad2014-05-12 05:36:57 +00003181 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003182 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003183 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003184 std::tie(Frame, Depth) =
3185 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003186 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003187 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003188 << AK << LVal.Base.is<const ValueDecl*>();
3189 NoteLValueLocation(Info, LVal.Base);
3190 return CompleteObject();
3191 }
Richard Smith3229b742013-05-05 21:17:10 +00003192 }
3193
Richard Smith7bd54ab2019-05-15 20:22:21 +00003194 bool IsAccess = isFormalAccess(AK);
3195
Richard Smith3229b742013-05-05 21:17:10 +00003196 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3197 // is not a constant expression (even if the object is non-volatile). We also
3198 // apply this rule to C++98, in order to conform to the expected 'volatile'
3199 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003200 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003201 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003202 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003203 << AK << LValType;
3204 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003205 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003206 return CompleteObject();
3207 }
3208
3209 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003210 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003211 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003212
3213 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3214 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3215 // In C++11, constexpr, non-volatile variables initialized with constant
3216 // expressions are constant expressions too. Inside constexpr functions,
3217 // parameters are constant expressions even if they're non-const.
3218 // In C++1y, objects local to a constant expression (those with a Frame) are
3219 // both readable and writable inside constant expressions.
3220 // In C, such things can also be folded, although they are not ICEs.
3221 const VarDecl *VD = dyn_cast<VarDecl>(D);
3222 if (VD) {
3223 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3224 VD = VDef;
3225 }
3226 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003228 return CompleteObject();
3229 }
3230
Richard Smith3229b742013-05-05 21:17:10 +00003231 // Unless we're looking at a local variable or argument in a constexpr call,
3232 // the variable we're reading must be const.
3233 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003234 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003235 declaresSameEntity(
3236 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003237 // OK, we can read and modify an object if we're in the process of
3238 // evaluating its initializer, because its lifetime began in this
3239 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003240 } else if (isModification(AK)) {
3241 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003242 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003243 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003244 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003245 // OK, we can read this variable.
3246 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003247 // In OpenCL if a variable is in constant address space it is a const
3248 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003249 if (!(BaseType.isConstQualified() ||
3250 (Info.getLangOpts().OpenCL &&
3251 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003252 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003253 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003254 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003255 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003256 Info.Note(VD->getLocation(), diag::note_declared_at);
3257 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003258 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003259 }
3260 return CompleteObject();
3261 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003262 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003263 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003264 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3265 // We support folding of const floating-point types, in order to make
3266 // static const data members of such types (supported as an extension)
3267 // more useful.
3268 if (Info.getLangOpts().CPlusPlus11) {
3269 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3270 Info.Note(VD->getLocation(), diag::note_declared_at);
3271 } else {
3272 Info.CCEDiag(E);
3273 }
George Burgess IVb5316982016-12-27 05:33:20 +00003274 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3275 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3276 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003277 } else {
3278 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003279 if (Info.checkingPotentialConstantExpression() &&
3280 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3281 // The definition of this variable could be constexpr. We can't
3282 // access it right now, but may be able to in future.
3283 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003284 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003285 Info.Note(VD->getLocation(), diag::note_declared_at);
3286 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003287 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003288 }
3289 return CompleteObject();
3290 }
3291 }
3292
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003293 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003294 return CompleteObject();
3295 } else {
3296 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3297
3298 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003299 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003300 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003301 assert(MTE->getStorageDuration() == SD_Static &&
3302 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003303
Richard Smithe6c01442013-06-05 00:46:14 +00003304 // Per C++1y [expr.const]p2:
3305 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3306 // - a [...] glvalue of integral or enumeration type that refers to
3307 // a non-volatile const object [...]
3308 // [...]
3309 // - a [...] glvalue of literal type that refers to a non-volatile
3310 // object whose lifetime began within the evaluation of e.
3311 //
3312 // C++11 misses the 'began within the evaluation of e' check and
3313 // instead allows all temporaries, including things like:
3314 // int &&r = 1;
3315 // int x = ++r;
3316 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003317 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003318 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3319 const ValueDecl *ED = MTE->getExtendingDecl();
3320 if (!(BaseType.isConstQualified() &&
3321 BaseType->isIntegralOrEnumerationType()) &&
3322 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003323 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003324 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003325 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003326 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3327 return CompleteObject();
3328 }
3329
3330 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3331 assert(BaseVal && "got reference to unevaluated temporary");
3332 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003333 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003334 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003335 APValue Val;
3336 LVal.moveInto(Val);
3337 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3338 << AK
3339 << Val.getAsString(Info.Ctx,
3340 Info.Ctx.getLValueReferenceType(LValType));
3341 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003342 return CompleteObject();
3343 }
3344 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003345 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003346 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003347 }
Richard Smith7525ff62013-05-09 07:14:00 +00003348 }
3349
Richard Smith9defb7d2018-02-21 03:38:30 +00003350 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003351 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003352 //
3353 // FIXME: Not all local state is mutable. Allow local constant subobjects
3354 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003355 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3356 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003357 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003358 return CompleteObject();
3359
Richard Smithdebad642019-05-12 09:39:08 +00003360 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003361}
3362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003363/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003364/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3365/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003366///
3367/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003368/// \param Conv - The expression for which we are performing the conversion.
3369/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003370/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3371/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003372/// \param LVal - The glvalue on which we are attempting to perform this action.
3373/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003374/// \param WantObjectRepresentation - If true, we're looking for the object
3375/// representation rather than the value, and in particular,
3376/// there is no requirement that the result be fully initialized.
3377static bool
3378handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3379 const LValue &LVal, APValue &RVal,
3380 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003381 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003382 return false;
3383
Richard Smith3229b742013-05-05 21:17:10 +00003384 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003385 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003386
Richard Smithc667cdc2019-09-18 17:37:44 +00003387 AccessKinds AK =
3388 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3389
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003390 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003391 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3392 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3393 // initializer until now for such expressions. Such an expression can't be
3394 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003395 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003396 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003397 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003398 }
Richard Smith3229b742013-05-05 21:17:10 +00003399 APValue Lit;
3400 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3401 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003402 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003403 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003404 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003405 // Special-case character extraction so we don't have to construct an
3406 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003407 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003408 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003409 if (LVal.Designator.Entries.empty()) {
3410 // Fail for now for LValue to RValue conversion of an array.
3411 // (This shouldn't show up in C/C++, but it could be triggered by a
3412 // weird EvaluateAsRValue call from a tool.)
3413 Info.FFDiag(Conv);
3414 return false;
3415 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003416 if (LVal.Designator.isOnePastTheEnd()) {
3417 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003418 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003419 else
3420 Info.FFDiag(Conv);
3421 return false;
3422 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003423 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003424 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3425 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003426 }
Richard Smith11562c52011-10-28 17:51:58 +00003427 }
3428
Richard Smithc667cdc2019-09-18 17:37:44 +00003429 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3430 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003431}
3432
3433/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003434static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003435 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003436 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003437 return false;
3438
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003439 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003440 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003441 return false;
3442 }
3443
Richard Smith3229b742013-05-05 21:17:10 +00003444 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003445 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3446}
3447
3448namespace {
3449struct CompoundAssignSubobjectHandler {
3450 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003451 const Expr *E;
3452 QualType PromotedLHSType;
3453 BinaryOperatorKind Opcode;
3454 const APValue &RHS;
3455
3456 static const AccessKinds AccessKind = AK_Assign;
3457
3458 typedef bool result_type;
3459
3460 bool checkConst(QualType QT) {
3461 // Assigning to a const object has undefined behavior.
3462 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003463 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003464 return false;
3465 }
3466 return true;
3467 }
3468
3469 bool failed() { return false; }
3470 bool found(APValue &Subobj, QualType SubobjType) {
3471 switch (Subobj.getKind()) {
3472 case APValue::Int:
3473 return found(Subobj.getInt(), SubobjType);
3474 case APValue::Float:
3475 return found(Subobj.getFloat(), SubobjType);
3476 case APValue::ComplexInt:
3477 case APValue::ComplexFloat:
3478 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003479 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003480 return false;
3481 case APValue::LValue:
3482 return foundPointer(Subobj, SubobjType);
3483 default:
3484 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003485 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003486 return false;
3487 }
3488 }
3489 bool found(APSInt &Value, QualType SubobjType) {
3490 if (!checkConst(SubobjType))
3491 return false;
3492
Tan S. B.9f935e82018-12-18 07:38:06 +00003493 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003494 // We don't support compound assignment on integer-cast-to-pointer
3495 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003496 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003497 return false;
3498 }
3499
Tan S. B.9f935e82018-12-18 07:38:06 +00003500 if (RHS.isInt()) {
3501 APSInt LHS =
3502 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3503 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3504 return false;
3505 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3506 return true;
3507 } else if (RHS.isFloat()) {
3508 APFloat FValue(0.0);
3509 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3510 FValue) &&
3511 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3512 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3513 Value);
3514 }
3515
3516 Info.FFDiag(E);
3517 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003518 }
3519 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003520 return checkConst(SubobjType) &&
3521 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3522 Value) &&
3523 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3524 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003525 }
3526 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3527 if (!checkConst(SubobjType))
3528 return false;
3529
3530 QualType PointeeType;
3531 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3532 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003533
3534 if (PointeeType.isNull() || !RHS.isInt() ||
3535 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003536 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003537 return false;
3538 }
3539
Richard Smithd6cc1982017-01-31 02:23:02 +00003540 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003541 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003542 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003543
3544 LValue LVal;
3545 LVal.setFrom(Info.Ctx, Subobj);
3546 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3547 return false;
3548 LVal.moveInto(Subobj);
3549 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003550 }
Richard Smith43e77732013-05-07 04:50:00 +00003551};
3552} // end anonymous namespace
3553
3554const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3555
3556/// Perform a compound assignment of LVal <op>= RVal.
3557static bool handleCompoundAssignment(
3558 EvalInfo &Info, const Expr *E,
3559 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3560 BinaryOperatorKind Opcode, const APValue &RVal) {
3561 if (LVal.Designator.Invalid)
3562 return false;
3563
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003564 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003565 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003566 return false;
3567 }
3568
3569 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3570 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3571 RVal };
3572 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3573}
3574
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003575namespace {
3576struct IncDecSubobjectHandler {
3577 EvalInfo &Info;
3578 const UnaryOperator *E;
3579 AccessKinds AccessKind;
3580 APValue *Old;
3581
Richard Smith243ef902013-05-05 23:31:59 +00003582 typedef bool result_type;
3583
3584 bool checkConst(QualType QT) {
3585 // Assigning to a const object has undefined behavior.
3586 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003587 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003588 return false;
3589 }
3590 return true;
3591 }
3592
3593 bool failed() { return false; }
3594 bool found(APValue &Subobj, QualType SubobjType) {
3595 // Stash the old value. Also clear Old, so we don't clobber it later
3596 // if we're post-incrementing a complex.
3597 if (Old) {
3598 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003599 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003600 }
3601
3602 switch (Subobj.getKind()) {
3603 case APValue::Int:
3604 return found(Subobj.getInt(), SubobjType);
3605 case APValue::Float:
3606 return found(Subobj.getFloat(), SubobjType);
3607 case APValue::ComplexInt:
3608 return found(Subobj.getComplexIntReal(),
3609 SubobjType->castAs<ComplexType>()->getElementType()
3610 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3611 case APValue::ComplexFloat:
3612 return found(Subobj.getComplexFloatReal(),
3613 SubobjType->castAs<ComplexType>()->getElementType()
3614 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3615 case APValue::LValue:
3616 return foundPointer(Subobj, SubobjType);
3617 default:
3618 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003619 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003620 return false;
3621 }
3622 }
3623 bool found(APSInt &Value, QualType SubobjType) {
3624 if (!checkConst(SubobjType))
3625 return false;
3626
3627 if (!SubobjType->isIntegerType()) {
3628 // We don't support increment / decrement on integer-cast-to-pointer
3629 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003630 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003631 return false;
3632 }
3633
3634 if (Old) *Old = APValue(Value);
3635
3636 // bool arithmetic promotes to int, and the conversion back to bool
3637 // doesn't reduce mod 2^n, so special-case it.
3638 if (SubobjType->isBooleanType()) {
3639 if (AccessKind == AK_Increment)
3640 Value = 1;
3641 else
3642 Value = !Value;
3643 return true;
3644 }
3645
3646 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003647 if (AccessKind == AK_Increment) {
3648 ++Value;
3649
3650 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3651 APSInt ActualValue(Value, /*IsUnsigned*/true);
3652 return HandleOverflow(Info, E, ActualValue, SubobjType);
3653 }
3654 } else {
3655 --Value;
3656
3657 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3658 unsigned BitWidth = Value.getBitWidth();
3659 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3660 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003661 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003662 }
3663 }
3664 return true;
3665 }
3666 bool found(APFloat &Value, QualType SubobjType) {
3667 if (!checkConst(SubobjType))
3668 return false;
3669
3670 if (Old) *Old = APValue(Value);
3671
3672 APFloat One(Value.getSemantics(), 1);
3673 if (AccessKind == AK_Increment)
3674 Value.add(One, APFloat::rmNearestTiesToEven);
3675 else
3676 Value.subtract(One, APFloat::rmNearestTiesToEven);
3677 return true;
3678 }
3679 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3680 if (!checkConst(SubobjType))
3681 return false;
3682
3683 QualType PointeeType;
3684 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3685 PointeeType = PT->getPointeeType();
3686 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003687 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003688 return false;
3689 }
3690
3691 LValue LVal;
3692 LVal.setFrom(Info.Ctx, Subobj);
3693 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3694 AccessKind == AK_Increment ? 1 : -1))
3695 return false;
3696 LVal.moveInto(Subobj);
3697 return true;
3698 }
Richard Smith243ef902013-05-05 23:31:59 +00003699};
3700} // end anonymous namespace
3701
3702/// Perform an increment or decrement on LVal.
3703static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3704 QualType LValType, bool IsIncrement, APValue *Old) {
3705 if (LVal.Designator.Invalid)
3706 return false;
3707
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003708 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003709 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003710 return false;
3711 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003712
3713 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3714 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3715 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3716 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3717}
3718
Richard Smithe97cbd72011-11-11 04:05:33 +00003719/// Build an lvalue for the object argument of a member function call.
3720static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3721 LValue &This) {
3722 if (Object->getType()->isPointerType())
3723 return EvaluatePointer(Object, This, Info);
3724
3725 if (Object->isGLValue())
3726 return EvaluateLValue(Object, This, Info);
3727
Richard Smithd9f663b2013-04-22 15:31:51 +00003728 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003729 return EvaluateTemporary(Object, This, Info);
3730
Faisal Valie690b7a2016-07-02 22:34:24 +00003731 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003732 return false;
3733}
3734
3735/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3736/// lvalue referring to the result.
3737///
3738/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003739/// \param LV - An lvalue referring to the base of the member pointer.
3740/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003741/// \param IncludeMember - Specifies whether the member itself is included in
3742/// the resulting LValue subobject designator. This is not possible when
3743/// creating a bound member function.
3744/// \return The field or method declaration to which the member pointer refers,
3745/// or 0 if evaluation fails.
3746static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003747 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003748 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003749 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003750 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003751 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003752 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003753 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003754
3755 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3756 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003757 if (!MemPtr.getDecl()) {
3758 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003759 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003760 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003761 }
Richard Smith253c2a32012-01-27 01:14:48 +00003762
Richard Smith027bf112011-11-17 22:56:20 +00003763 if (MemPtr.isDerivedMember()) {
3764 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003765 // The end of the derived-to-base path for the base object must match the
3766 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003767 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003768 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003769 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003770 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003771 }
Richard Smith027bf112011-11-17 22:56:20 +00003772 unsigned PathLengthToMember =
3773 LV.Designator.Entries.size() - MemPtr.Path.size();
3774 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3775 const CXXRecordDecl *LVDecl = getAsBaseClass(
3776 LV.Designator.Entries[PathLengthToMember + I]);
3777 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003778 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003779 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003780 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003781 }
Richard Smith027bf112011-11-17 22:56:20 +00003782 }
3783
3784 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003785 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003786 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003787 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003788 } else if (!MemPtr.Path.empty()) {
3789 // Extend the LValue path with the member pointer's path.
3790 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3791 MemPtr.Path.size() + IncludeMember);
3792
3793 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003794 if (const PointerType *PT = LVType->getAs<PointerType>())
3795 LVType = PT->getPointeeType();
3796 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3797 assert(RD && "member pointer access on non-class-type expression");
3798 // The first class in the path is that of the lvalue.
3799 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3800 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003801 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003802 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003803 RD = Base;
3804 }
3805 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003806 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3807 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003808 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003809 }
3810
3811 // Add the member. Note that we cannot build bound member functions here.
3812 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003813 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003814 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003815 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003816 } else if (const IndirectFieldDecl *IFD =
3817 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003818 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003819 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003820 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003821 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003822 }
Richard Smith027bf112011-11-17 22:56:20 +00003823 }
3824
3825 return MemPtr.getDecl();
3826}
3827
Richard Smith84401042013-06-03 05:03:02 +00003828static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3829 const BinaryOperator *BO,
3830 LValue &LV,
3831 bool IncludeMember = true) {
3832 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3833
3834 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003835 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003836 MemberPtr MemPtr;
3837 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3838 }
Craig Topper36250ad2014-05-12 05:36:57 +00003839 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003840 }
3841
3842 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3843 BO->getRHS(), IncludeMember);
3844}
3845
Richard Smith027bf112011-11-17 22:56:20 +00003846/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3847/// the provided lvalue, which currently refers to the base object.
3848static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3849 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003850 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003851 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003852 return false;
3853
Richard Smitha8105bc2012-01-06 16:39:00 +00003854 QualType TargetQT = E->getType();
3855 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3856 TargetQT = PT->getPointeeType();
3857
3858 // Check this cast lands within the final derived-to-base subobject path.
3859 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003860 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003861 << D.MostDerivedType << TargetQT;
3862 return false;
3863 }
3864
Richard Smith027bf112011-11-17 22:56:20 +00003865 // Check the type of the final cast. We don't need to check the path,
3866 // since a cast can only be formed if the path is unique.
3867 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003868 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3869 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003870 if (NewEntriesSize == D.MostDerivedPathLength)
3871 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3872 else
Richard Smith027bf112011-11-17 22:56:20 +00003873 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003874 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003875 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003876 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003877 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003878 }
Richard Smith027bf112011-11-17 22:56:20 +00003879
3880 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003881 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003882}
3883
Richard Smithc667cdc2019-09-18 17:37:44 +00003884/// Get the value to use for a default-initialized object of type T.
3885static APValue getDefaultInitValue(QualType T) {
3886 if (auto *RD = T->getAsCXXRecordDecl()) {
3887 if (RD->isUnion())
3888 return APValue((const FieldDecl*)nullptr);
3889
3890 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
3891 std::distance(RD->field_begin(), RD->field_end()));
3892
3893 unsigned Index = 0;
3894 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
3895 End = RD->bases_end(); I != End; ++I, ++Index)
3896 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
3897
3898 for (const auto *I : RD->fields()) {
3899 if (I->isUnnamedBitfield())
3900 continue;
3901 Struct.getStructField(I->getFieldIndex()) =
3902 getDefaultInitValue(I->getType());
3903 }
3904 return Struct;
3905 }
3906
3907 if (auto *AT =
3908 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
3909 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
3910 if (Array.hasArrayFiller())
3911 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
3912 return Array;
3913 }
3914
3915 return APValue::IndeterminateValue();
3916}
3917
Mike Stump876387b2009-10-27 22:09:17 +00003918namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003919enum EvalStmtResult {
3920 /// Evaluation failed.
3921 ESR_Failed,
3922 /// Hit a 'return' statement.
3923 ESR_Returned,
3924 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003925 ESR_Succeeded,
3926 /// Hit a 'continue' statement.
3927 ESR_Continue,
3928 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003929 ESR_Break,
3930 /// Still scanning for 'case' or 'default' statement.
3931 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003932};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003933}
Richard Smith254a73d2011-10-28 22:34:42 +00003934
Richard Smith97fcf4b2016-08-14 23:15:52 +00003935static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3936 // We don't need to evaluate the initializer for a static local.
3937 if (!VD->hasLocalStorage())
3938 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003939
Richard Smith97fcf4b2016-08-14 23:15:52 +00003940 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003941 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003942
Richard Smith97fcf4b2016-08-14 23:15:52 +00003943 const Expr *InitE = VD->getInit();
3944 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00003945 Val = getDefaultInitValue(VD->getType());
3946 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00003947 }
Richard Smith51f03172013-06-20 03:00:05 +00003948
Richard Smith97fcf4b2016-08-14 23:15:52 +00003949 if (InitE->isValueDependent())
3950 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003951
Richard Smith97fcf4b2016-08-14 23:15:52 +00003952 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3953 // Wipe out any partially-computed value, to allow tracking that this
3954 // evaluation failed.
3955 Val = APValue();
3956 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003957 }
3958
3959 return true;
3960}
3961
Richard Smith97fcf4b2016-08-14 23:15:52 +00003962static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3963 bool OK = true;
3964
3965 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3966 OK &= EvaluateVarDecl(Info, VD);
3967
3968 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3969 for (auto *BD : DD->bindings())
3970 if (auto *VD = BD->getHoldingVar())
3971 OK &= EvaluateDecl(Info, VD);
3972
3973 return OK;
3974}
3975
3976
Richard Smith4e18ca52013-05-06 05:56:11 +00003977/// Evaluate a condition (either a variable declaration or an expression).
3978static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3979 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003980 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003981 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3982 return false;
3983 return EvaluateAsBooleanCondition(Cond, Result, Info);
3984}
3985
Richard Smith89210072016-04-04 23:29:43 +00003986namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003987/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003988/// statement should be stored.
3989struct StmtResult {
3990 /// The APValue that should be filled in with the returned value.
3991 APValue &Value;
3992 /// The location containing the result, if any (used to support RVO).
3993 const LValue *Slot;
3994};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003995
3996struct TempVersionRAII {
3997 CallStackFrame &Frame;
3998
3999 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4000 Frame.pushTempVersion();
4001 }
4002
4003 ~TempVersionRAII() {
4004 Frame.popTempVersion();
4005 }
4006};
4007
Richard Smith89210072016-04-04 23:29:43 +00004008}
Richard Smith52a980a2015-08-28 02:43:42 +00004009
4010static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004011 const Stmt *S,
4012 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004013
4014/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004015static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004016 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004017 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004018 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004019 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004020 case ESR_Break:
4021 return ESR_Succeeded;
4022 case ESR_Succeeded:
4023 case ESR_Continue:
4024 return ESR_Continue;
4025 case ESR_Failed:
4026 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004027 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004028 return ESR;
4029 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004030 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004031}
4032
Richard Smith496ddcf2013-05-12 17:32:42 +00004033/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004034static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004035 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004036 BlockScopeRAII Scope(Info);
4037
Richard Smith496ddcf2013-05-12 17:32:42 +00004038 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004039 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004040 {
4041 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004042 if (const Stmt *Init = SS->getInit()) {
4043 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4044 if (ESR != ESR_Succeeded)
4045 return ESR;
4046 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004047 if (SS->getConditionVariable() &&
4048 !EvaluateDecl(Info, SS->getConditionVariable()))
4049 return ESR_Failed;
4050 if (!EvaluateInteger(SS->getCond(), Value, Info))
4051 return ESR_Failed;
4052 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004053
4054 // Find the switch case corresponding to the value of the condition.
4055 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004056 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004057 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4058 SC = SC->getNextSwitchCase()) {
4059 if (isa<DefaultStmt>(SC)) {
4060 Found = SC;
4061 continue;
4062 }
4063
4064 const CaseStmt *CS = cast<CaseStmt>(SC);
4065 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4066 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4067 : LHS;
4068 if (LHS <= Value && Value <= RHS) {
4069 Found = SC;
4070 break;
4071 }
4072 }
4073
4074 if (!Found)
4075 return ESR_Succeeded;
4076
4077 // Search the switch body for the switch case and evaluate it from there.
4078 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4079 case ESR_Break:
4080 return ESR_Succeeded;
4081 case ESR_Succeeded:
4082 case ESR_Continue:
4083 case ESR_Failed:
4084 case ESR_Returned:
4085 return ESR;
4086 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004087 // This can only happen if the switch case is nested within a statement
4088 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004089 Info.FFDiag(Found->getBeginLoc(),
4090 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004091 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004092 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004093 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004094}
4095
Richard Smith254a73d2011-10-28 22:34:42 +00004096// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004097static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004098 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004099 if (!Info.nextStep(S))
4100 return ESR_Failed;
4101
Richard Smith496ddcf2013-05-12 17:32:42 +00004102 // If we're hunting down a 'case' or 'default' label, recurse through
4103 // substatements until we hit the label.
4104 if (Case) {
4105 // FIXME: We don't start the lifetime of objects whose initialization we
4106 // jump over. However, such objects must be of class type with a trivial
4107 // default constructor that initialize all subobjects, so must be empty,
4108 // so this almost never matters.
4109 switch (S->getStmtClass()) {
4110 case Stmt::CompoundStmtClass:
4111 // FIXME: Precompute which substatement of a compound statement we
4112 // would jump to, and go straight there rather than performing a
4113 // linear scan each time.
4114 case Stmt::LabelStmtClass:
4115 case Stmt::AttributedStmtClass:
4116 case Stmt::DoStmtClass:
4117 break;
4118
4119 case Stmt::CaseStmtClass:
4120 case Stmt::DefaultStmtClass:
4121 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004122 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004123 break;
4124
4125 case Stmt::IfStmtClass: {
4126 // FIXME: Precompute which side of an 'if' we would jump to, and go
4127 // straight there rather than scanning both sides.
4128 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004129
4130 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4131 // preceded by our switch label.
4132 BlockScopeRAII Scope(Info);
4133
Richard Smith496ddcf2013-05-12 17:32:42 +00004134 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4135 if (ESR != ESR_CaseNotFound || !IS->getElse())
4136 return ESR;
4137 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4138 }
4139
4140 case Stmt::WhileStmtClass: {
4141 EvalStmtResult ESR =
4142 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4143 if (ESR != ESR_Continue)
4144 return ESR;
4145 break;
4146 }
4147
4148 case Stmt::ForStmtClass: {
4149 const ForStmt *FS = cast<ForStmt>(S);
4150 EvalStmtResult ESR =
4151 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4152 if (ESR != ESR_Continue)
4153 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004154 if (FS->getInc()) {
4155 FullExpressionRAII IncScope(Info);
4156 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4157 return ESR_Failed;
4158 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004159 break;
4160 }
4161
Richard Smithc667cdc2019-09-18 17:37:44 +00004162 case Stmt::DeclStmtClass: {
4163 // Start the lifetime of any uninitialized variables we encounter. They
4164 // might be used by the selected branch of the switch.
4165 const DeclStmt *DS = cast<DeclStmt>(S);
4166 for (const auto *D : DS->decls()) {
4167 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4168 if (VD->hasLocalStorage() && !VD->getInit())
4169 if (!EvaluateVarDecl(Info, VD))
4170 return ESR_Failed;
4171 // FIXME: If the variable has initialization that can't be jumped
4172 // over, bail out of any immediately-surrounding compound-statement
4173 // too. There can't be any case labels here.
4174 }
4175 }
4176 return ESR_CaseNotFound;
4177 }
4178
Richard Smith496ddcf2013-05-12 17:32:42 +00004179 default:
4180 return ESR_CaseNotFound;
4181 }
4182 }
4183
Richard Smith254a73d2011-10-28 22:34:42 +00004184 switch (S->getStmtClass()) {
4185 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004186 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004187 // Don't bother evaluating beyond an expression-statement which couldn't
4188 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004189 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004190 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004191 return ESR_Failed;
4192 return ESR_Succeeded;
4193 }
4194
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004195 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004196 return ESR_Failed;
4197
4198 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004199 return ESR_Succeeded;
4200
Richard Smithd9f663b2013-04-22 15:31:51 +00004201 case Stmt::DeclStmtClass: {
4202 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004203 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004204 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004205 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004206 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004207 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004208 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004209 return ESR_Succeeded;
4210 }
4211
Richard Smith357362d2011-12-13 06:39:58 +00004212 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004213 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004214 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004215 if (RetExpr &&
4216 !(Result.Slot
4217 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4218 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004219 return ESR_Failed;
4220 return ESR_Returned;
4221 }
Richard Smith254a73d2011-10-28 22:34:42 +00004222
4223 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004224 BlockScopeRAII Scope(Info);
4225
Richard Smith254a73d2011-10-28 22:34:42 +00004226 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004227 for (const auto *BI : CS->body()) {
4228 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004229 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004230 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004231 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004232 return ESR;
4233 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004234 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004235 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004236
4237 case Stmt::IfStmtClass: {
4238 const IfStmt *IS = cast<IfStmt>(S);
4239
4240 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004241 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004242 if (const Stmt *Init = IS->getInit()) {
4243 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4244 if (ESR != ESR_Succeeded)
4245 return ESR;
4246 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004247 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004248 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004249 return ESR_Failed;
4250
4251 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4252 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4253 if (ESR != ESR_Succeeded)
4254 return ESR;
4255 }
4256 return ESR_Succeeded;
4257 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004258
4259 case Stmt::WhileStmtClass: {
4260 const WhileStmt *WS = cast<WhileStmt>(S);
4261 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004262 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004263 bool Continue;
4264 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4265 Continue))
4266 return ESR_Failed;
4267 if (!Continue)
4268 break;
4269
4270 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4271 if (ESR != ESR_Continue)
4272 return ESR;
4273 }
4274 return ESR_Succeeded;
4275 }
4276
4277 case Stmt::DoStmtClass: {
4278 const DoStmt *DS = cast<DoStmt>(S);
4279 bool Continue;
4280 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004281 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004282 if (ESR != ESR_Continue)
4283 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004284 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004285
Richard Smith08d6a2c2013-07-24 07:11:57 +00004286 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004287 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4288 return ESR_Failed;
4289 } while (Continue);
4290 return ESR_Succeeded;
4291 }
4292
4293 case Stmt::ForStmtClass: {
4294 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004295 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004296 if (FS->getInit()) {
4297 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4298 if (ESR != ESR_Succeeded)
4299 return ESR;
4300 }
4301 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004302 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004303 bool Continue = true;
4304 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4305 FS->getCond(), Continue))
4306 return ESR_Failed;
4307 if (!Continue)
4308 break;
4309
4310 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4311 if (ESR != ESR_Continue)
4312 return ESR;
4313
Richard Smith08d6a2c2013-07-24 07:11:57 +00004314 if (FS->getInc()) {
4315 FullExpressionRAII IncScope(Info);
4316 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4317 return ESR_Failed;
4318 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004319 }
4320 return ESR_Succeeded;
4321 }
4322
Richard Smith896e0d72013-05-06 06:51:17 +00004323 case Stmt::CXXForRangeStmtClass: {
4324 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004325 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004326
Richard Smith8baa5002018-09-28 18:44:09 +00004327 // Evaluate the init-statement if present.
4328 if (FS->getInit()) {
4329 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4330 if (ESR != ESR_Succeeded)
4331 return ESR;
4332 }
4333
Richard Smith896e0d72013-05-06 06:51:17 +00004334 // Initialize the __range variable.
4335 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4336 if (ESR != ESR_Succeeded)
4337 return ESR;
4338
4339 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004340 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4341 if (ESR != ESR_Succeeded)
4342 return ESR;
4343 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004344 if (ESR != ESR_Succeeded)
4345 return ESR;
4346
4347 while (true) {
4348 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004349 {
4350 bool Continue = true;
4351 FullExpressionRAII CondExpr(Info);
4352 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4353 return ESR_Failed;
4354 if (!Continue)
4355 break;
4356 }
Richard Smith896e0d72013-05-06 06:51:17 +00004357
4358 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004359 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004360 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4361 if (ESR != ESR_Succeeded)
4362 return ESR;
4363
4364 // Loop body.
4365 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4366 if (ESR != ESR_Continue)
4367 return ESR;
4368
4369 // Increment: ++__begin
4370 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4371 return ESR_Failed;
4372 }
4373
4374 return ESR_Succeeded;
4375 }
4376
Richard Smith496ddcf2013-05-12 17:32:42 +00004377 case Stmt::SwitchStmtClass:
4378 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4379
Richard Smith4e18ca52013-05-06 05:56:11 +00004380 case Stmt::ContinueStmtClass:
4381 return ESR_Continue;
4382
4383 case Stmt::BreakStmtClass:
4384 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004385
4386 case Stmt::LabelStmtClass:
4387 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4388
4389 case Stmt::AttributedStmtClass:
4390 // As a general principle, C++11 attributes can be ignored without
4391 // any semantic impact.
4392 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4393 Case);
4394
4395 case Stmt::CaseStmtClass:
4396 case Stmt::DefaultStmtClass:
4397 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004398 case Stmt::CXXTryStmtClass:
4399 // Evaluate try blocks by evaluating all sub statements.
4400 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004401 }
4402}
4403
Richard Smithcc36f692011-12-22 02:22:31 +00004404/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4405/// default constructor. If so, we'll fold it whether or not it's marked as
4406/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4407/// so we need special handling.
4408static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004409 const CXXConstructorDecl *CD,
4410 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004411 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4412 return false;
4413
Richard Smith66e05fe2012-01-18 05:21:49 +00004414 // Value-initialization does not call a trivial default constructor, so such a
4415 // call is a core constant expression whether or not the constructor is
4416 // constexpr.
4417 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004418 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004419 // FIXME: If DiagDecl is an implicitly-declared special member function,
4420 // we should be much more explicit about why it's not constexpr.
4421 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4422 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4423 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004424 } else {
4425 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4426 }
4427 }
4428 return true;
4429}
4430
Richard Smith357362d2011-12-13 06:39:58 +00004431/// CheckConstexprFunction - Check that a function can be called in a constant
4432/// expression.
4433static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4434 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004435 const FunctionDecl *Definition,
4436 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004437 // Potential constant expressions can contain calls to declared, but not yet
4438 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004439 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004440 Declaration->isConstexpr())
4441 return false;
4442
James Y Knightc7d3e602018-10-05 17:49:48 +00004443 // Bail out if the function declaration itself is invalid. We will
4444 // have produced a relevant diagnostic while parsing it, so just
4445 // note the problematic sub-expression.
4446 if (Declaration->isInvalidDecl()) {
4447 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004448 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004449 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004450
Richard Smithd9c6b032019-05-09 19:45:49 +00004451 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004452 // constant expression (prior to C++20). We can still constant-fold such a
4453 // call.
4454 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4455 cast<CXXMethodDecl>(Declaration)->isVirtual())
4456 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4457
4458 if (Definition && Definition->isInvalidDecl()) {
4459 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004460 return false;
4461 }
4462
Richard Smith357362d2011-12-13 06:39:58 +00004463 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004464 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004465 return true;
4466
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004467 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004468 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004469
Richard Smith5179eb72016-06-28 19:03:57 +00004470 // If this function is not constexpr because it is an inherited
4471 // non-constexpr constructor, diagnose that directly.
4472 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4473 if (CD && CD->isInheritingConstructor()) {
4474 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004475 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004476 DiagDecl = CD = Inherited;
4477 }
4478
4479 // FIXME: If DiagDecl is an implicitly-declared special member function
4480 // or an inheriting constructor, we should be much more explicit about why
4481 // it's not constexpr.
4482 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004483 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004484 << CD->getInheritedConstructor().getConstructor()->getParent();
4485 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004486 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004487 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004488 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4489 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004490 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004491 }
4492 return false;
4493}
4494
Richard Smithdebad642019-05-12 09:39:08 +00004495namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004496struct CheckDynamicTypeHandler {
4497 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004498 typedef bool result_type;
4499 bool failed() { return false; }
4500 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4501 bool found(APSInt &Value, QualType SubobjType) { return true; }
4502 bool found(APFloat &Value, QualType SubobjType) { return true; }
4503};
4504} // end anonymous namespace
4505
Richard Smith7bd54ab2019-05-15 20:22:21 +00004506/// Check that we can access the notional vptr of an object / determine its
4507/// dynamic type.
4508static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4509 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004510 if (This.Designator.Invalid)
4511 return false;
4512
Richard Smith7bd54ab2019-05-15 20:22:21 +00004513 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004514
4515 if (!Obj)
4516 return false;
4517
4518 if (!Obj.Value) {
4519 // The object is not usable in constant expressions, so we can't inspect
4520 // its value to see if it's in-lifetime or what the active union members
4521 // are. We can still check for a one-past-the-end lvalue.
4522 if (This.Designator.isOnePastTheEnd() ||
4523 This.Designator.isMostDerivedAnUnsizedArray()) {
4524 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4525 ? diag::note_constexpr_access_past_end
4526 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004527 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004528 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004529 } else if (Polymorphic) {
4530 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004531 // not be able to read a notional 'vptr' value.
4532 APValue Val;
4533 This.moveInto(Val);
4534 QualType StarThisType =
4535 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004536 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4537 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004538 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004539 }
4540 return true;
4541 }
4542
Richard Smith7bd54ab2019-05-15 20:22:21 +00004543 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004544 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4545}
4546
Richard Smith7bd54ab2019-05-15 20:22:21 +00004547/// Check that the pointee of the 'this' pointer in a member function call is
4548/// either within its lifetime or in its period of construction or destruction.
4549static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4550 const LValue &This) {
4551 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4552}
4553
Richard Smith921f1322019-05-13 23:35:21 +00004554struct DynamicType {
4555 /// The dynamic class type of the object.
4556 const CXXRecordDecl *Type;
4557 /// The corresponding path length in the lvalue.
4558 unsigned PathLength;
4559};
4560
4561static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4562 unsigned PathLength) {
4563 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4564 Designator.Entries.size() && "invalid path length");
4565 return (PathLength == Designator.MostDerivedPathLength)
4566 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4567 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4568}
4569
4570/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004571static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4572 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004573 // If we don't have an lvalue denoting an object of class type, there is no
4574 // meaningful dynamic type. (We consider objects of non-class type to have no
4575 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004576 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004577 return None;
4578
Richard Smith7bd54ab2019-05-15 20:22:21 +00004579 // Refuse to compute a dynamic type in the presence of virtual bases. This
4580 // shouldn't happen other than in constant-folding situations, since literal
4581 // types can't have virtual bases.
4582 //
4583 // Note that consumers of DynamicType assume that the type has no virtual
4584 // bases, and will need modifications if this restriction is relaxed.
4585 const CXXRecordDecl *Class =
4586 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4587 if (!Class || Class->getNumVBases()) {
4588 Info.FFDiag(E);
4589 return None;
4590 }
4591
Richard Smith921f1322019-05-13 23:35:21 +00004592 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4593 // binary search here instead. But the overwhelmingly common case is that
4594 // we're not in the middle of a constructor, so it probably doesn't matter
4595 // in practice.
4596 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4597 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4598 PathLength <= Path.size(); ++PathLength) {
4599 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4600 Path.slice(0, PathLength))) {
4601 case ConstructionPhase::Bases:
4602 // We're constructing a base class. This is not the dynamic type.
4603 break;
4604
4605 case ConstructionPhase::None:
4606 case ConstructionPhase::AfterBases:
4607 // We've finished constructing the base classes, so this is the dynamic
4608 // type.
4609 return DynamicType{getBaseClassType(This.Designator, PathLength),
4610 PathLength};
4611 }
4612 }
4613
4614 // CWG issue 1517: we're constructing a base class of the object described by
4615 // 'This', so that object has not yet begun its period of construction and
4616 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004617 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004618 return None;
4619}
4620
4621/// Perform virtual dispatch.
4622static const CXXMethodDecl *HandleVirtualDispatch(
4623 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4624 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004625 Optional<DynamicType> DynType =
4626 ComputeDynamicType(Info, E, This, AK_MemberCall);
4627 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004628 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004629
4630 // Find the final overrider. It must be declared in one of the classes on the
4631 // path from the dynamic type to the static type.
4632 // FIXME: If we ever allow literal types to have virtual base classes, that
4633 // won't be true.
4634 const CXXMethodDecl *Callee = Found;
4635 unsigned PathLength = DynType->PathLength;
4636 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4637 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004638 const CXXMethodDecl *Overrider =
4639 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4640 if (Overrider) {
4641 Callee = Overrider;
4642 break;
4643 }
4644 }
4645
4646 // C++2a [class.abstract]p6:
4647 // the effect of making a virtual call to a pure virtual function [...] is
4648 // undefined
4649 if (Callee->isPure()) {
4650 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4651 Info.Note(Callee->getLocation(), diag::note_declared_at);
4652 return nullptr;
4653 }
4654
4655 // If necessary, walk the rest of the path to determine the sequence of
4656 // covariant adjustment steps to apply.
4657 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4658 Found->getReturnType())) {
4659 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4660 for (unsigned CovariantPathLength = PathLength + 1;
4661 CovariantPathLength != This.Designator.Entries.size();
4662 ++CovariantPathLength) {
4663 const CXXRecordDecl *NextClass =
4664 getBaseClassType(This.Designator, CovariantPathLength);
4665 const CXXMethodDecl *Next =
4666 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4667 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4668 Next->getReturnType(), CovariantAdjustmentPath.back()))
4669 CovariantAdjustmentPath.push_back(Next->getReturnType());
4670 }
4671 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4672 CovariantAdjustmentPath.back()))
4673 CovariantAdjustmentPath.push_back(Found->getReturnType());
4674 }
4675
4676 // Perform 'this' adjustment.
4677 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4678 return nullptr;
4679
4680 return Callee;
4681}
4682
4683/// Perform the adjustment from a value returned by a virtual function to
4684/// a value of the statically expected type, which may be a pointer or
4685/// reference to a base class of the returned type.
4686static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4687 APValue &Result,
4688 ArrayRef<QualType> Path) {
4689 assert(Result.isLValue() &&
4690 "unexpected kind of APValue for covariant return");
4691 if (Result.isNullPointer())
4692 return true;
4693
4694 LValue LVal;
4695 LVal.setFrom(Info.Ctx, Result);
4696
4697 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4698 for (unsigned I = 1; I != Path.size(); ++I) {
4699 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4700 assert(OldClass && NewClass && "unexpected kind of covariant return");
4701 if (OldClass != NewClass &&
4702 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4703 return false;
4704 OldClass = NewClass;
4705 }
4706
4707 LVal.moveInto(Result);
4708 return true;
4709}
4710
Richard Smith7bd54ab2019-05-15 20:22:21 +00004711/// Determine whether \p Base, which is known to be a direct base class of
4712/// \p Derived, is a public base class.
4713static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4714 const CXXRecordDecl *Base) {
4715 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4716 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4717 if (BaseClass && declaresSameEntity(BaseClass, Base))
4718 return BaseSpec.getAccessSpecifier() == AS_public;
4719 }
4720 llvm_unreachable("Base is not a direct base of Derived");
4721}
4722
4723/// Apply the given dynamic cast operation on the provided lvalue.
4724///
4725/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4726/// to find a suitable target subobject.
4727static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4728 LValue &Ptr) {
4729 // We can't do anything with a non-symbolic pointer value.
4730 SubobjectDesignator &D = Ptr.Designator;
4731 if (D.Invalid)
4732 return false;
4733
4734 // C++ [expr.dynamic.cast]p6:
4735 // If v is a null pointer value, the result is a null pointer value.
4736 if (Ptr.isNullPointer() && !E->isGLValue())
4737 return true;
4738
4739 // For all the other cases, we need the pointer to point to an object within
4740 // its lifetime / period of construction / destruction, and we need to know
4741 // its dynamic type.
4742 Optional<DynamicType> DynType =
4743 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4744 if (!DynType)
4745 return false;
4746
4747 // C++ [expr.dynamic.cast]p7:
4748 // If T is "pointer to cv void", then the result is a pointer to the most
4749 // derived object
4750 if (E->getType()->isVoidPointerType())
4751 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4752
4753 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4754 assert(C && "dynamic_cast target is not void pointer nor class");
4755 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4756
4757 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4758 // C++ [expr.dynamic.cast]p9:
4759 if (!E->isGLValue()) {
4760 // The value of a failed cast to pointer type is the null pointer value
4761 // of the required result type.
4762 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4763 Ptr.setNull(E->getType(), TargetVal);
4764 return true;
4765 }
4766
4767 // A failed cast to reference type throws [...] std::bad_cast.
4768 unsigned DiagKind;
4769 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4770 DynType->Type->isDerivedFrom(C)))
4771 DiagKind = 0;
4772 else if (!Paths || Paths->begin() == Paths->end())
4773 DiagKind = 1;
4774 else if (Paths->isAmbiguous(CQT))
4775 DiagKind = 2;
4776 else {
4777 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4778 DiagKind = 3;
4779 }
4780 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4781 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4782 << Info.Ctx.getRecordType(DynType->Type)
4783 << E->getType().getUnqualifiedType();
4784 return false;
4785 };
4786
4787 // Runtime check, phase 1:
4788 // Walk from the base subobject towards the derived object looking for the
4789 // target type.
4790 for (int PathLength = Ptr.Designator.Entries.size();
4791 PathLength >= (int)DynType->PathLength; --PathLength) {
4792 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4793 if (declaresSameEntity(Class, C))
4794 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4795 // We can only walk across public inheritance edges.
4796 if (PathLength > (int)DynType->PathLength &&
4797 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4798 Class))
4799 return RuntimeCheckFailed(nullptr);
4800 }
4801
4802 // Runtime check, phase 2:
4803 // Search the dynamic type for an unambiguous public base of type C.
4804 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4805 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4806 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4807 Paths.front().Access == AS_public) {
4808 // Downcast to the dynamic type...
4809 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4810 return false;
4811 // ... then upcast to the chosen base class subobject.
4812 for (CXXBasePathElement &Elem : Paths.front())
4813 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4814 return false;
4815 return true;
4816 }
4817
4818 // Otherwise, the runtime check fails.
4819 return RuntimeCheckFailed(&Paths);
4820}
4821
Richard Smith31c69a32019-05-21 23:15:20 +00004822namespace {
4823struct StartLifetimeOfUnionMemberHandler {
4824 const FieldDecl *Field;
4825
4826 static const AccessKinds AccessKind = AK_Assign;
4827
Richard Smith31c69a32019-05-21 23:15:20 +00004828 typedef bool result_type;
4829 bool failed() { return false; }
4830 bool found(APValue &Subobj, QualType SubobjType) {
4831 // We are supposed to perform no initialization but begin the lifetime of
4832 // the object. We interpret that as meaning to do what default
4833 // initialization of the object would do if all constructors involved were
4834 // trivial:
4835 // * All base, non-variant member, and array element subobjects' lifetimes
4836 // begin
4837 // * No variant members' lifetimes begin
4838 // * All scalar subobjects whose lifetimes begin have indeterminate values
4839 assert(SubobjType->isUnionType());
4840 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4841 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4842 return true;
4843 }
4844 bool found(APSInt &Value, QualType SubobjType) {
4845 llvm_unreachable("wrong value kind for union object");
4846 }
4847 bool found(APFloat &Value, QualType SubobjType) {
4848 llvm_unreachable("wrong value kind for union object");
4849 }
4850};
4851} // end anonymous namespace
4852
4853const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4854
4855/// Handle a builtin simple-assignment or a call to a trivial assignment
4856/// operator whose left-hand side might involve a union member access. If it
4857/// does, implicitly start the lifetime of any accessed union elements per
4858/// C++20 [class.union]5.
4859static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4860 const LValue &LHS) {
4861 if (LHS.InvalidBase || LHS.Designator.Invalid)
4862 return false;
4863
4864 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4865 // C++ [class.union]p5:
4866 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00004867 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00004868 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00004869 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
4870 if (auto *ME = dyn_cast<MemberExpr>(E)) {
4871 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
4872 if (!FD)
4873 break;
4874
4875 // ... and also contains A.B if B names a union member
4876 if (FD->getParent()->isUnion())
4877 UnionPathLengths.push_back({PathLength - 1, FD});
4878
4879 E = ME->getBase();
4880 --PathLength;
4881 assert(declaresSameEntity(FD,
4882 LHS.Designator.Entries[PathLength]
4883 .getAsBaseOrMember().getPointer()));
4884
4885 // -- If E is of the form A[B] and is interpreted as a built-in array
4886 // subscripting operator, S(E) is [S(the array operand, if any)].
4887 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
4888 // Step over an ArrayToPointerDecay implicit cast.
4889 auto *Base = ASE->getBase()->IgnoreImplicit();
4890 if (!Base->getType()->isArrayType())
4891 break;
4892
4893 E = Base;
4894 --PathLength;
4895
4896 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4897 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00004898 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00004899 if (ICE->getCastKind() == CK_NoOp)
4900 continue;
4901 if (ICE->getCastKind() != CK_DerivedToBase &&
4902 ICE->getCastKind() != CK_UncheckedDerivedToBase)
4903 break;
Richard Smitha481b012019-05-30 20:45:12 +00004904 // Walk path backwards as we walk up from the base to the derived class.
4905 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00004906 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00004907 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00004908 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
4909 LHS.Designator.Entries[PathLength]
4910 .getAsBaseOrMember().getPointer()));
4911 }
Richard Smith31c69a32019-05-21 23:15:20 +00004912
4913 // -- Otherwise, S(E) is empty.
4914 } else {
4915 break;
4916 }
4917 }
4918
4919 // Common case: no unions' lifetimes are started.
4920 if (UnionPathLengths.empty())
4921 return true;
4922
4923 // if modification of X [would access an inactive union member], an object
4924 // of the type of X is implicitly created
4925 CompleteObject Obj =
4926 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
4927 if (!Obj)
4928 return false;
4929 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
4930 llvm::reverse(UnionPathLengths)) {
4931 // Form a designator for the union object.
4932 SubobjectDesignator D = LHS.Designator;
4933 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
4934
4935 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
4936 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
4937 return false;
4938 }
4939
4940 return true;
4941}
4942
Richard Smithbe6dd812014-11-19 21:27:17 +00004943/// Determine if a class has any fields that might need to be copied by a
4944/// trivial copy or move operation.
4945static bool hasFields(const CXXRecordDecl *RD) {
4946 if (!RD || RD->isEmpty())
4947 return false;
4948 for (auto *FD : RD->fields()) {
4949 if (FD->isUnnamedBitfield())
4950 continue;
4951 return true;
4952 }
4953 for (auto &Base : RD->bases())
4954 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4955 return true;
4956 return false;
4957}
4958
Richard Smithd62306a2011-11-10 06:34:14 +00004959namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004960typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004961}
4962
4963/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004964static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
4965 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00004966 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004967 llvm::SmallBitVector ForbiddenNullArgs;
4968 if (Callee->hasAttr<NonNullAttr>()) {
4969 ForbiddenNullArgs.resize(Args.size());
4970 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
4971 if (!Attr->args_size()) {
4972 ForbiddenNullArgs.set();
4973 break;
4974 } else
4975 for (auto Idx : Attr->args()) {
4976 unsigned ASTIdx = Idx.getASTIndex();
4977 if (ASTIdx >= Args.size())
4978 continue;
4979 ForbiddenNullArgs[ASTIdx] = 1;
4980 }
4981 }
4982 }
Richard Smithd62306a2011-11-10 06:34:14 +00004983 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004984 I != E; ++I) {
4985 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4986 // If we're checking for a potential constant expression, evaluate all
4987 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004988 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004989 return false;
4990 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004991 } else if (!ForbiddenNullArgs.empty() &&
4992 ForbiddenNullArgs[I - Args.begin()] &&
4993 ArgValues[I - Args.begin()].isNullPointer()) {
4994 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
4995 if (!Info.noteFailure())
4996 return false;
4997 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00004998 }
4999 }
5000 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005001}
5002
Richard Smith254a73d2011-10-28 22:34:42 +00005003/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005004static bool HandleFunctionCall(SourceLocation CallLoc,
5005 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005006 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005007 EvalInfo &Info, APValue &Result,
5008 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005009 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005010 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005011 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005012
Richard Smith253c2a32012-01-27 01:14:48 +00005013 if (!Info.CheckCallLimit(CallLoc))
5014 return false;
5015
5016 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005017
5018 // For a trivial copy or move assignment, perform an APValue copy. This is
5019 // essential for unions, where the operations performed by the assignment
5020 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005021 //
5022 // Skip this for non-union classes with no fields; in that case, the defaulted
5023 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005024 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005025 if (MD && MD->isDefaulted() &&
5026 (MD->getParent()->isUnion() ||
5027 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005028 assert(This &&
5029 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5030 LValue RHS;
5031 RHS.setFrom(Info.Ctx, ArgValues[0]);
5032 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005033 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5034 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005035 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005036 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5037 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5038 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005039 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005040 RHSValue))
5041 return false;
5042 This->moveInto(Result);
5043 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005044 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005045 // We're in a lambda; determine the lambda capture field maps unless we're
5046 // just constexpr checking a lambda's call operator. constexpr checking is
5047 // done before the captures have been added to the closure object (unless
5048 // we're inferring constexpr-ness), so we don't have access to them in this
5049 // case. But since we don't need the captures to constexpr check, we can
5050 // just ignore them.
5051 if (!Info.checkingPotentialConstantExpression())
5052 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5053 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005054 }
5055
Richard Smith52a980a2015-08-28 02:43:42 +00005056 StmtResult Ret = {Result, ResultSlot};
5057 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005058 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005059 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005060 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005061 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005062 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005063 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005064}
5065
Richard Smithd62306a2011-11-10 06:34:14 +00005066/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005067static bool HandleConstructorCall(const Expr *E, const LValue &This,
5068 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005069 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005070 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005071 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005072 if (!Info.CheckCallLimit(CallLoc))
5073 return false;
5074
Richard Smith3607ffe2012-02-13 03:54:03 +00005075 const CXXRecordDecl *RD = Definition->getParent();
5076 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005077 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005078 return false;
5079 }
5080
Erik Pilkington42925492017-10-04 00:18:55 +00005081 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005082 Info,
5083 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5084 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005085 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005086
Richard Smith52a980a2015-08-28 02:43:42 +00005087 // FIXME: Creating an APValue just to hold a nonexistent return value is
5088 // wasteful.
5089 APValue RetVal;
5090 StmtResult Ret = {RetVal, nullptr};
5091
Richard Smith5179eb72016-06-28 19:03:57 +00005092 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005093 if (Definition->isDelegatingConstructor()) {
5094 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005095 {
5096 FullExpressionRAII InitScope(Info);
5097 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5098 return false;
5099 }
Richard Smith52a980a2015-08-28 02:43:42 +00005100 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005101 }
5102
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005103 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005104 // essential for unions (or classes with anonymous union members), where the
5105 // operations performed by the constructor cannot be represented by
5106 // ctor-initializers.
5107 //
5108 // Skip this for empty non-union classes; we should not perform an
5109 // lvalue-to-rvalue conversion on them because their copy constructor does not
5110 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005111 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005112 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005113 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005114 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005115 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005116 return handleLValueToRValueConversion(
5117 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005118 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005119 }
5120
5121 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005122 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005123 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005124 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005125
John McCalld7bca762012-05-01 00:38:49 +00005126 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005127 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5128
Richard Smith08d6a2c2013-07-24 07:11:57 +00005129 // A scope for temporaries lifetime-extended by reference members.
5130 BlockScopeRAII LifetimeExtendedScope(Info);
5131
Richard Smith253c2a32012-01-27 01:14:48 +00005132 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005133 unsigned BasesSeen = 0;
5134#ifndef NDEBUG
5135 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5136#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005137 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5138 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5139 // We might be initializing the same field again if this is an indirect
5140 // field initialization.
5141 if (FieldIt == RD->field_end() ||
5142 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5143 assert(Indirect && "fields out of order?");
5144 return;
5145 }
5146
5147 // Default-initialize any fields with no explicit initializer.
5148 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5149 assert(FieldIt != RD->field_end() && "missing field?");
5150 if (!FieldIt->isUnnamedBitfield())
5151 Result.getStructField(FieldIt->getFieldIndex()) =
5152 getDefaultInitValue(FieldIt->getType());
5153 }
5154 ++FieldIt;
5155 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005156 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005157 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005158 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005159 APValue *Value = &Result;
5160
5161 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005162 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005163 if (I->isBaseInitializer()) {
5164 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005165#ifndef NDEBUG
5166 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005167 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005168 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5169 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5170 "base class initializers not in expected order");
5171 ++BaseIt;
5172#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005173 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005174 BaseType->getAsCXXRecordDecl(), &Layout))
5175 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005176 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005177 } else if ((FD = I->getMember())) {
5178 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005179 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005180 if (RD->isUnion()) {
5181 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005182 Value = &Result.getUnionValue();
5183 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005184 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005185 Value = &Result.getStructField(FD->getFieldIndex());
5186 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005187 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005188 // Walk the indirect field decl's chain to find the object to initialize,
5189 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005190 auto IndirectFieldChain = IFD->chain();
5191 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005192 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005193 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5194 // Switch the union field if it differs. This happens if we had
5195 // preceding zero-initialization, and we're now initializing a union
5196 // subobject other than the first.
5197 // FIXME: In this case, the values of the other subobjects are
5198 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005199 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005200 (Value->isUnion() && Value->getUnionField() != FD)) {
5201 if (CD->isUnion())
5202 *Value = APValue(FD);
5203 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005204 // FIXME: This immediately starts the lifetime of all members of an
5205 // anonymous struct. It would be preferable to strictly start member
5206 // lifetime in initialization order.
5207 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005208 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005209 // Store Subobject as its parent before updating it for the last element
5210 // in the chain.
5211 if (C == IndirectFieldChain.back())
5212 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005213 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005214 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005215 if (CD->isUnion())
5216 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005217 else {
5218 if (C == IndirectFieldChain.front() && !RD->isUnion())
5219 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005220 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005221 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005222 }
Richard Smithd62306a2011-11-10 06:34:14 +00005223 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005224 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005225 }
Richard Smith253c2a32012-01-27 01:14:48 +00005226
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005227 // Need to override This for implicit field initializers as in this case
5228 // This refers to innermost anonymous struct/union containing initializer,
5229 // not to currently constructed class.
5230 const Expr *Init = I->getInit();
5231 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5232 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005233 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005234 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5235 (FD && FD->isBitField() &&
5236 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005237 // If we're checking for a potential constant expression, evaluate all
5238 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005239 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005240 return false;
5241 Success = false;
5242 }
Richard Smith921f1322019-05-13 23:35:21 +00005243
5244 // This is the point at which the dynamic type of the object becomes this
5245 // class type.
5246 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5247 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005248 }
5249
Richard Smithc667cdc2019-09-18 17:37:44 +00005250 // Default-initialize any remaining fields.
5251 if (!RD->isUnion()) {
5252 for (; FieldIt != RD->field_end(); ++FieldIt) {
5253 if (!FieldIt->isUnnamedBitfield())
5254 Result.getStructField(FieldIt->getFieldIndex()) =
5255 getDefaultInitValue(FieldIt->getType());
5256 }
5257 }
5258
Richard Smithd9f663b2013-04-22 15:31:51 +00005259 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005260 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005261}
5262
Richard Smith5179eb72016-06-28 19:03:57 +00005263static bool HandleConstructorCall(const Expr *E, const LValue &This,
5264 ArrayRef<const Expr*> Args,
5265 const CXXConstructorDecl *Definition,
5266 EvalInfo &Info, APValue &Result) {
5267 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005268 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005269 return false;
5270
5271 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5272 Info, Result);
5273}
5274
Eli Friedman9a156e52008-11-12 09:44:48 +00005275//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005276// Generic Evaluation
5277//===----------------------------------------------------------------------===//
5278namespace {
5279
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005280class BitCastBuffer {
5281 // FIXME: We're going to need bit-level granularity when we support
5282 // bit-fields.
5283 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5284 // we don't support a host or target where that is the case. Still, we should
5285 // use a more generic type in case we ever do.
5286 SmallVector<Optional<unsigned char>, 32> Bytes;
5287
5288 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5289 "Need at least 8 bit unsigned char");
5290
5291 bool TargetIsLittleEndian;
5292
5293public:
5294 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5295 : Bytes(Width.getQuantity()),
5296 TargetIsLittleEndian(TargetIsLittleEndian) {}
5297
5298 LLVM_NODISCARD
5299 bool readObject(CharUnits Offset, CharUnits Width,
5300 SmallVectorImpl<unsigned char> &Output) const {
5301 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5302 // If a byte of an integer is uninitialized, then the whole integer is
5303 // uninitalized.
5304 if (!Bytes[I.getQuantity()])
5305 return false;
5306 Output.push_back(*Bytes[I.getQuantity()]);
5307 }
5308 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5309 std::reverse(Output.begin(), Output.end());
5310 return true;
5311 }
5312
5313 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5314 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5315 std::reverse(Input.begin(), Input.end());
5316
5317 size_t Index = 0;
5318 for (unsigned char Byte : Input) {
5319 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5320 Bytes[Offset.getQuantity() + Index] = Byte;
5321 ++Index;
5322 }
5323 }
5324
5325 size_t size() { return Bytes.size(); }
5326};
5327
5328/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5329/// target would represent the value at runtime.
5330class APValueToBufferConverter {
5331 EvalInfo &Info;
5332 BitCastBuffer Buffer;
5333 const CastExpr *BCE;
5334
5335 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5336 const CastExpr *BCE)
5337 : Info(Info),
5338 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5339 BCE(BCE) {}
5340
5341 bool visit(const APValue &Val, QualType Ty) {
5342 return visit(Val, Ty, CharUnits::fromQuantity(0));
5343 }
5344
5345 // Write out Val with type Ty into Buffer starting at Offset.
5346 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5347 assert((size_t)Offset.getQuantity() <= Buffer.size());
5348
5349 // As a special case, nullptr_t has an indeterminate value.
5350 if (Ty->isNullPtrType())
5351 return true;
5352
5353 // Dig through Src to find the byte at SrcOffset.
5354 switch (Val.getKind()) {
5355 case APValue::Indeterminate:
5356 case APValue::None:
5357 return true;
5358
5359 case APValue::Int:
5360 return visitInt(Val.getInt(), Ty, Offset);
5361 case APValue::Float:
5362 return visitFloat(Val.getFloat(), Ty, Offset);
5363 case APValue::Array:
5364 return visitArray(Val, Ty, Offset);
5365 case APValue::Struct:
5366 return visitRecord(Val, Ty, Offset);
5367
5368 case APValue::ComplexInt:
5369 case APValue::ComplexFloat:
5370 case APValue::Vector:
5371 case APValue::FixedPoint:
5372 // FIXME: We should support these.
5373
5374 case APValue::Union:
5375 case APValue::MemberPointer:
5376 case APValue::AddrLabelDiff: {
5377 Info.FFDiag(BCE->getBeginLoc(),
5378 diag::note_constexpr_bit_cast_unsupported_type)
5379 << Ty;
5380 return false;
5381 }
5382
5383 case APValue::LValue:
5384 llvm_unreachable("LValue subobject in bit_cast?");
5385 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005386 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005387 }
5388
5389 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5390 const RecordDecl *RD = Ty->getAsRecordDecl();
5391 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5392
5393 // Visit the base classes.
5394 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5395 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5396 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5397 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5398
5399 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5400 Layout.getBaseClassOffset(BaseDecl) + Offset))
5401 return false;
5402 }
5403 }
5404
5405 // Visit the fields.
5406 unsigned FieldIdx = 0;
5407 for (FieldDecl *FD : RD->fields()) {
5408 if (FD->isBitField()) {
5409 Info.FFDiag(BCE->getBeginLoc(),
5410 diag::note_constexpr_bit_cast_unsupported_bitfield);
5411 return false;
5412 }
5413
5414 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5415
5416 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5417 "only bit-fields can have sub-char alignment");
5418 CharUnits FieldOffset =
5419 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5420 QualType FieldTy = FD->getType();
5421 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5422 return false;
5423 ++FieldIdx;
5424 }
5425
5426 return true;
5427 }
5428
5429 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5430 const auto *CAT =
5431 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5432 if (!CAT)
5433 return false;
5434
5435 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5436 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5437 unsigned ArraySize = Val.getArraySize();
5438 // First, initialize the initialized elements.
5439 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5440 const APValue &SubObj = Val.getArrayInitializedElt(I);
5441 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5442 return false;
5443 }
5444
5445 // Next, initialize the rest of the array using the filler.
5446 if (Val.hasArrayFiller()) {
5447 const APValue &Filler = Val.getArrayFiller();
5448 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5449 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5450 return false;
5451 }
5452 }
5453
5454 return true;
5455 }
5456
5457 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5458 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5459 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5460 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5461 Buffer.writeObject(Offset, Bytes);
5462 return true;
5463 }
5464
5465 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5466 APSInt AsInt(Val.bitcastToAPInt());
5467 return visitInt(AsInt, Ty, Offset);
5468 }
5469
5470public:
5471 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5472 const CastExpr *BCE) {
5473 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5474 APValueToBufferConverter Converter(Info, DstSize, BCE);
5475 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5476 return None;
5477 return Converter.Buffer;
5478 }
5479};
5480
5481/// Write an BitCastBuffer into an APValue.
5482class BufferToAPValueConverter {
5483 EvalInfo &Info;
5484 const BitCastBuffer &Buffer;
5485 const CastExpr *BCE;
5486
5487 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5488 const CastExpr *BCE)
5489 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5490
5491 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5492 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5493 // Ideally this will be unreachable.
5494 llvm::NoneType unsupportedType(QualType Ty) {
5495 Info.FFDiag(BCE->getBeginLoc(),
5496 diag::note_constexpr_bit_cast_unsupported_type)
5497 << Ty;
5498 return None;
5499 }
5500
5501 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5502 const EnumType *EnumSugar = nullptr) {
5503 if (T->isNullPtrType()) {
5504 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5505 return APValue((Expr *)nullptr,
5506 /*Offset=*/CharUnits::fromQuantity(NullValue),
5507 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5508 }
5509
5510 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5511 SmallVector<uint8_t, 8> Bytes;
5512 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5513 // If this is std::byte or unsigned char, then its okay to store an
5514 // indeterminate value.
5515 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5516 bool IsUChar =
5517 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5518 T->isSpecificBuiltinType(BuiltinType::Char_U));
5519 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00005520 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005521 Info.FFDiag(BCE->getExprLoc(),
5522 diag::note_constexpr_bit_cast_indet_dest)
5523 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5524 return None;
5525 }
5526
5527 return APValue::IndeterminateValue();
5528 }
5529
5530 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5531 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5532
5533 if (T->isIntegralOrEnumerationType()) {
5534 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5535 return APValue(Val);
5536 }
5537
5538 if (T->isRealFloatingType()) {
5539 const llvm::fltSemantics &Semantics =
5540 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5541 return APValue(APFloat(Semantics, Val));
5542 }
5543
5544 return unsupportedType(QualType(T, 0));
5545 }
5546
5547 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5548 const RecordDecl *RD = RTy->getAsRecordDecl();
5549 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5550
5551 unsigned NumBases = 0;
5552 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5553 NumBases = CXXRD->getNumBases();
5554
5555 APValue ResultVal(APValue::UninitStruct(), NumBases,
5556 std::distance(RD->field_begin(), RD->field_end()));
5557
5558 // Visit the base classes.
5559 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5560 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5561 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5562 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5563 if (BaseDecl->isEmpty() ||
5564 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5565 continue;
5566
5567 Optional<APValue> SubObj = visitType(
5568 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5569 if (!SubObj)
5570 return None;
5571 ResultVal.getStructBase(I) = *SubObj;
5572 }
5573 }
5574
5575 // Visit the fields.
5576 unsigned FieldIdx = 0;
5577 for (FieldDecl *FD : RD->fields()) {
5578 // FIXME: We don't currently support bit-fields. A lot of the logic for
5579 // this is in CodeGen, so we need to factor it around.
5580 if (FD->isBitField()) {
5581 Info.FFDiag(BCE->getBeginLoc(),
5582 diag::note_constexpr_bit_cast_unsupported_bitfield);
5583 return None;
5584 }
5585
5586 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5587 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5588
5589 CharUnits FieldOffset =
5590 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5591 Offset;
5592 QualType FieldTy = FD->getType();
5593 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5594 if (!SubObj)
5595 return None;
5596 ResultVal.getStructField(FieldIdx) = *SubObj;
5597 ++FieldIdx;
5598 }
5599
5600 return ResultVal;
5601 }
5602
5603 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5604 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5605 assert(!RepresentationType.isNull() &&
5606 "enum forward decl should be caught by Sema");
5607 const BuiltinType *AsBuiltin =
5608 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5609 assert(AsBuiltin && "non-integral enum underlying type?");
5610 // Recurse into the underlying type. Treat std::byte transparently as
5611 // unsigned char.
5612 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5613 }
5614
5615 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5616 size_t Size = Ty->getSize().getLimitedValue();
5617 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5618
5619 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5620 for (size_t I = 0; I != Size; ++I) {
5621 Optional<APValue> ElementValue =
5622 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5623 if (!ElementValue)
5624 return None;
5625 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5626 }
5627
5628 return ArrayValue;
5629 }
5630
5631 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5632 return unsupportedType(QualType(Ty, 0));
5633 }
5634
5635 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5636 QualType Can = Ty.getCanonicalType();
5637
5638 switch (Can->getTypeClass()) {
5639#define TYPE(Class, Base) \
5640 case Type::Class: \
5641 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5642#define ABSTRACT_TYPE(Class, Base)
5643#define NON_CANONICAL_TYPE(Class, Base) \
5644 case Type::Class: \
5645 llvm_unreachable("non-canonical type should be impossible!");
5646#define DEPENDENT_TYPE(Class, Base) \
5647 case Type::Class: \
5648 llvm_unreachable( \
5649 "dependent types aren't supported in the constant evaluator!");
5650#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5651 case Type::Class: \
5652 llvm_unreachable("either dependent or not canonical!");
5653#include "clang/AST/TypeNodes.def"
5654 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005655 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005656 }
5657
5658public:
5659 // Pull out a full value of type DstType.
5660 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5661 const CastExpr *BCE) {
5662 BufferToAPValueConverter Converter(Info, Buffer, BCE);
5663 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5664 }
5665};
5666
5667static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5668 QualType Ty, EvalInfo *Info,
5669 const ASTContext &Ctx,
5670 bool CheckingDest) {
5671 Ty = Ty.getCanonicalType();
5672
5673 auto diag = [&](int Reason) {
5674 if (Info)
5675 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5676 << CheckingDest << (Reason == 4) << Reason;
5677 return false;
5678 };
5679 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5680 if (Info)
5681 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5682 << NoteTy << Construct << Ty;
5683 return false;
5684 };
5685
5686 if (Ty->isUnionType())
5687 return diag(0);
5688 if (Ty->isPointerType())
5689 return diag(1);
5690 if (Ty->isMemberPointerType())
5691 return diag(2);
5692 if (Ty.isVolatileQualified())
5693 return diag(3);
5694
5695 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5696 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5697 for (CXXBaseSpecifier &BS : CXXRD->bases())
5698 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5699 CheckingDest))
5700 return note(1, BS.getType(), BS.getBeginLoc());
5701 }
5702 for (FieldDecl *FD : Record->fields()) {
5703 if (FD->getType()->isReferenceType())
5704 return diag(4);
5705 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5706 CheckingDest))
5707 return note(0, FD->getType(), FD->getBeginLoc());
5708 }
5709 }
5710
5711 if (Ty->isArrayType() &&
5712 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5713 Info, Ctx, CheckingDest))
5714 return false;
5715
5716 return true;
5717}
5718
5719static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5720 const ASTContext &Ctx,
5721 const CastExpr *BCE) {
5722 bool DestOK = checkBitCastConstexprEligibilityType(
5723 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5724 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5725 BCE->getBeginLoc(),
5726 BCE->getSubExpr()->getType(), Info, Ctx, false);
5727 return SourceOK;
5728}
5729
5730static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5731 APValue &SourceValue,
5732 const CastExpr *BCE) {
5733 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5734 "no host or target supports non 8-bit chars");
5735 assert(SourceValue.isLValue() &&
5736 "LValueToRValueBitcast requires an lvalue operand!");
5737
5738 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5739 return false;
5740
5741 LValue SourceLValue;
5742 APValue SourceRValue;
5743 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00005744 if (!handleLValueToRValueConversion(
5745 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
5746 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005747 return false;
5748
5749 // Read out SourceValue into a char buffer.
5750 Optional<BitCastBuffer> Buffer =
5751 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5752 if (!Buffer)
5753 return false;
5754
5755 // Write out the buffer into a new APValue.
5756 Optional<APValue> MaybeDestValue =
5757 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5758 if (!MaybeDestValue)
5759 return false;
5760
5761 DestValue = std::move(*MaybeDestValue);
5762 return true;
5763}
5764
Aaron Ballman68af21c2014-01-03 19:26:43 +00005765template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005766class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005767 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005768private:
Richard Smith52a980a2015-08-28 02:43:42 +00005769 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005770 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005771 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005772 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005773 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005774 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005775 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005776
Richard Smith17100ba2012-02-16 02:46:34 +00005777 // Check whether a conditional operator with a non-constant condition is a
5778 // potential constant expression. If neither arm is a potential constant
5779 // expression, then the conditional operator is not either.
5780 template<typename ConditionalOperator>
5781 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005782 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005783
5784 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005785 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005786 {
Richard Smith17100ba2012-02-16 02:46:34 +00005787 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005788 StmtVisitorTy::Visit(E->getFalseExpr());
5789 if (Diag.empty())
5790 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005791 }
Richard Smith17100ba2012-02-16 02:46:34 +00005792
George Burgess IV8c892b52016-05-25 22:31:54 +00005793 {
5794 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005795 Diag.clear();
5796 StmtVisitorTy::Visit(E->getTrueExpr());
5797 if (Diag.empty())
5798 return;
5799 }
5800
5801 Error(E, diag::note_constexpr_conditional_never_const);
5802 }
5803
5804
5805 template<typename ConditionalOperator>
5806 bool HandleConditionalOperator(const ConditionalOperator *E) {
5807 bool BoolResult;
5808 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005809 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005810 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005811 return false;
5812 }
5813 if (Info.noteFailure()) {
5814 StmtVisitorTy::Visit(E->getTrueExpr());
5815 StmtVisitorTy::Visit(E->getFalseExpr());
5816 }
Richard Smith17100ba2012-02-16 02:46:34 +00005817 return false;
5818 }
5819
5820 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5821 return StmtVisitorTy::Visit(EvalExpr);
5822 }
5823
Peter Collingbournee9200682011-05-13 03:29:01 +00005824protected:
5825 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005826 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005827 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5828
Richard Smith92b1ce02011-12-12 09:28:41 +00005829 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005830 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005831 }
5832
Aaron Ballman68af21c2014-01-03 19:26:43 +00005833 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005834
5835public:
5836 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5837
5838 EvalInfo &getEvalInfo() { return Info; }
5839
Richard Smithf57d8cb2011-12-09 22:58:01 +00005840 /// Report an evaluation error. This should only be called when an error is
5841 /// first discovered. When propagating an error, just return false.
5842 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005843 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005844 return false;
5845 }
5846 bool Error(const Expr *E) {
5847 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5848 }
5849
Aaron Ballman68af21c2014-01-03 19:26:43 +00005850 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005851 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005852 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005853 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005854 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005855 }
5856
Bill Wendling8003edc2018-11-09 00:41:36 +00005857 bool VisitConstantExpr(const ConstantExpr *E)
5858 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005859 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005860 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005861 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005862 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005863 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005864 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005865 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005866 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005867 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005868 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005869 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005870 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005871 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5872 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005873 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005874 return StmtVisitorTy::Visit(E->getExpr());
5875 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005876 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005877 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005878 // The initializer may not have been parsed yet, or might be erroneous.
5879 if (!E->getExpr())
5880 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005881 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005882 return StmtVisitorTy::Visit(E->getExpr());
5883 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005884
Richard Smith5894a912011-12-19 22:12:41 +00005885 // We cannot create any objects for which cleanups are required, so there is
5886 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005887 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005888 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005889
Aaron Ballman68af21c2014-01-03 19:26:43 +00005890 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005891 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5892 return static_cast<Derived*>(this)->VisitCastExpr(E);
5893 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005894 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005895 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5896 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005897 return static_cast<Derived*>(this)->VisitCastExpr(E);
5898 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005899 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
5900 return static_cast<Derived*>(this)->VisitCastExpr(E);
5901 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00005902
Aaron Ballman68af21c2014-01-03 19:26:43 +00005903 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005904 switch (E->getOpcode()) {
5905 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005906 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005907
5908 case BO_Comma:
5909 VisitIgnoredValue(E->getLHS());
5910 return StmtVisitorTy::Visit(E->getRHS());
5911
5912 case BO_PtrMemD:
5913 case BO_PtrMemI: {
5914 LValue Obj;
5915 if (!HandleMemberPointerAccess(Info, E, Obj))
5916 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005917 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00005918 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005919 return false;
5920 return DerivedSuccess(Result, E);
5921 }
5922 }
5923 }
5924
Aaron Ballman68af21c2014-01-03 19:26:43 +00005925 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00005926 // Evaluate and cache the common expression. We treat it as a temporary,
5927 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00005928 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00005929 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005930 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00005931
Richard Smith17100ba2012-02-16 02:46:34 +00005932 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005933 }
5934
Aaron Ballman68af21c2014-01-03 19:26:43 +00005935 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005936 bool IsBcpCall = false;
5937 // If the condition (ignoring parens) is a __builtin_constant_p call,
5938 // the result is a constant expression if it can be folded without
5939 // side-effects. This is an important GNU extension. See GCC PR38377
5940 // for discussion.
5941 if (const CallExpr *CallCE =
5942 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00005943 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005944 IsBcpCall = true;
5945
5946 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5947 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00005948 // FIXME: We should instead treat __builtin_constant_p as non-constant if
5949 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00005950 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005951 return false;
5952
Richard Smith6d4c6582013-11-05 22:18:15 +00005953 FoldConstant Fold(Info, IsBcpCall);
5954 if (!HandleConditionalOperator(E)) {
5955 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00005956 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00005957 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00005958
5959 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00005960 }
5961
Aaron Ballman68af21c2014-01-03 19:26:43 +00005962 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005963 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00005964 return DerivedSuccess(*Value, E);
5965
5966 const Expr *Source = E->getSourceExpr();
5967 if (!Source)
5968 return Error(E);
5969 if (Source == E) { // sanity checking.
5970 assert(0 && "OpaqueValueExpr recursively refers to itself");
5971 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00005972 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00005973 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00005974 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005975
Aaron Ballman68af21c2014-01-03 19:26:43 +00005976 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005977 APValue Result;
5978 if (!handleCallExpr(E, Result, nullptr))
5979 return false;
5980 return DerivedSuccess(Result, E);
5981 }
5982
5983 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00005984 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00005985 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00005986 QualType CalleeType = Callee->getType();
5987
Craig Topper36250ad2014-05-12 05:36:57 +00005988 const FunctionDecl *FD = nullptr;
5989 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00005990 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00005991 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00005992
Richard Smithe97cbd72011-11-11 04:05:33 +00005993 // Extract function decl and 'this' pointer from the callee.
5994 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00005995 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005996 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5997 // Explicit bound member calls, such as x.f() or p->g();
5998 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005999 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006000 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6001 if (!Member)
6002 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006003 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006004 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006005 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6006 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006007 Member = dyn_cast_or_null<CXXMethodDecl>(
6008 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6009 if (!Member)
6010 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006011 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00006012 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006013 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006014 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006015 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006016 LValue Call;
6017 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006018 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006019
Richard Smitha8105bc2012-01-06 16:39:00 +00006020 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006021 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006022 FD = dyn_cast_or_null<FunctionDecl>(
6023 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006024 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006025 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006026 // Don't call function pointers which have been cast to some other type.
6027 // Per DR (no number yet), the caller and callee can differ in noexcept.
6028 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6029 CalleeType->getPointeeType(), FD->getType())) {
6030 return Error(E);
6031 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006032
6033 // Overloaded operator calls to member functions are represented as normal
6034 // calls with '*this' as the first argument.
6035 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6036 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006037 // FIXME: When selecting an implicit conversion for an overloaded
6038 // operator delete, we sometimes try to evaluate calls to conversion
6039 // operators without a 'this' parameter!
6040 if (Args.empty())
6041 return Error(E);
6042
Nick Lewycky13073a62017-06-12 21:15:44 +00006043 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006044 return false;
6045 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006046 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006047 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006048 // Map the static invoker for the lambda back to the call operator.
6049 // Conveniently, we don't have to slice out the 'this' argument (as is
6050 // being done for the non-static case), since a static member function
6051 // doesn't have an implicit argument passed in.
6052 const CXXRecordDecl *ClosureClass = MD->getParent();
6053 assert(
6054 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6055 "Number of captures must be zero for conversion to function-ptr");
6056
6057 const CXXMethodDecl *LambdaCallOp =
6058 ClosureClass->getLambdaCallOperator();
6059
6060 // Set 'FD', the function that will be called below, to the call
6061 // operator. If the closure object represents a generic lambda, find
6062 // the corresponding specialization of the call operator.
6063
6064 if (ClosureClass->isGenericLambda()) {
6065 assert(MD->isFunctionTemplateSpecialization() &&
6066 "A generic lambda's static-invoker function must be a "
6067 "template specialization");
6068 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6069 FunctionTemplateDecl *CallOpTemplate =
6070 LambdaCallOp->getDescribedFunctionTemplate();
6071 void *InsertPos = nullptr;
6072 FunctionDecl *CorrespondingCallOpSpecialization =
6073 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6074 assert(CorrespondingCallOpSpecialization &&
6075 "We must always have a function call operator specialization "
6076 "that corresponds to our static invoker specialization");
6077 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6078 } else
6079 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00006080 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006081 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006082 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006083
Richard Smith921f1322019-05-13 23:35:21 +00006084 SmallVector<QualType, 4> CovariantAdjustmentPath;
6085 if (This) {
6086 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006087 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6088 // Perform virtual dispatch, if necessary.
6089 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6090 CovariantAdjustmentPath);
6091 if (!FD)
6092 return false;
6093 } else {
6094 // Check that the 'this' pointer points to an object of the right type.
6095 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6096 return false;
6097 }
Richard Smith921f1322019-05-13 23:35:21 +00006098 }
Richard Smith47b34932012-02-01 02:39:43 +00006099
Craig Topper36250ad2014-05-12 05:36:57 +00006100 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006101 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006102
Nick Lewycky13073a62017-06-12 21:15:44 +00006103 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6104 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006105 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006106 return false;
6107
Richard Smith921f1322019-05-13 23:35:21 +00006108 if (!CovariantAdjustmentPath.empty() &&
6109 !HandleCovariantReturnAdjustment(Info, E, Result,
6110 CovariantAdjustmentPath))
6111 return false;
6112
Richard Smith52a980a2015-08-28 02:43:42 +00006113 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006114 }
6115
Aaron Ballman68af21c2014-01-03 19:26:43 +00006116 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006117 return StmtVisitorTy::Visit(E->getInitializer());
6118 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006119 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006120 if (E->getNumInits() == 0)
6121 return DerivedZeroInitialization(E);
6122 if (E->getNumInits() == 1)
6123 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006124 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006125 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006126 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006127 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006128 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006129 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006130 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006131 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006132 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006133 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006134 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006135
Richard Smithd62306a2011-11-10 06:34:14 +00006136 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006137 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006138 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6139 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006140 assert(!E->isArrow() && "missing call to bound member function?");
6141
Richard Smith2e312c82012-03-03 22:46:17 +00006142 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006143 if (!Evaluate(Val, Info, E->getBase()))
6144 return false;
6145
6146 QualType BaseTy = E->getBase()->getType();
6147
6148 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00006149 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006150 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00006151 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00006152 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6153
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006154 // Note: there is no lvalue base here. But this case should only ever
6155 // happen in C or in C++98, where we cannot be evaluating a constexpr
6156 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00006157 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00006158 SubobjectDesignator Designator(BaseTy);
6159 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00006160
Richard Smith3229b742013-05-05 21:17:10 +00006161 APValue Result;
6162 return extractSubobject(Info, E, Obj, Designator, Result) &&
6163 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00006164 }
6165
Aaron Ballman68af21c2014-01-03 19:26:43 +00006166 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006167 switch (E->getCastKind()) {
6168 default:
6169 break;
6170
Richard Smitha23ab512013-05-23 00:30:41 +00006171 case CK_AtomicToNonAtomic: {
6172 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00006173 // This does not need to be done in place even for class/array types:
6174 // atomic-to-non-atomic conversion implies copying the object
6175 // representation.
6176 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00006177 return false;
6178 return DerivedSuccess(AtomicVal, E);
6179 }
6180
Richard Smith11562c52011-10-28 17:51:58 +00006181 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00006182 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00006183 return StmtVisitorTy::Visit(E->getSubExpr());
6184
6185 case CK_LValueToRValue: {
6186 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006187 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6188 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006189 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00006190 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00006191 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00006192 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006193 return false;
6194 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00006195 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006196 case CK_LValueToRValueBitCast: {
6197 APValue DestValue, SourceValue;
6198 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6199 return false;
6200 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6201 return false;
6202 return DerivedSuccess(DestValue, E);
6203 }
Richard Smith11562c52011-10-28 17:51:58 +00006204 }
6205
Richard Smithf57d8cb2011-12-09 22:58:01 +00006206 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006207 }
6208
Aaron Ballman68af21c2014-01-03 19:26:43 +00006209 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006210 return VisitUnaryPostIncDec(UO);
6211 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006212 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006213 return VisitUnaryPostIncDec(UO);
6214 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006215 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006216 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006217 return Error(UO);
6218
6219 LValue LVal;
6220 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6221 return false;
6222 APValue RVal;
6223 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6224 UO->isIncrementOp(), &RVal))
6225 return false;
6226 return DerivedSuccess(RVal, UO);
6227 }
6228
Aaron Ballman68af21c2014-01-03 19:26:43 +00006229 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00006230 // We will have checked the full-expressions inside the statement expression
6231 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00006232 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00006233 return Error(E);
6234
Richard Smith08d6a2c2013-07-24 07:11:57 +00006235 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00006236 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006237 if (CS->body_empty())
6238 return true;
6239
Richard Smith51f03172013-06-20 03:00:05 +00006240 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6241 BE = CS->body_end();
6242 /**/; ++BI) {
6243 if (BI + 1 == BE) {
6244 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6245 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006246 Info.FFDiag((*BI)->getBeginLoc(),
6247 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006248 return false;
6249 }
6250 return this->Visit(FinalExpr);
6251 }
6252
6253 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00006254 StmtResult Result = { ReturnValue, nullptr };
6255 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00006256 if (ESR != ESR_Succeeded) {
6257 // FIXME: If the statement-expression terminated due to 'return',
6258 // 'break', or 'continue', it would be nice to propagate that to
6259 // the outer statement evaluation rather than bailing out.
6260 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006261 Info.FFDiag((*BI)->getBeginLoc(),
6262 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006263 return false;
6264 }
6265 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006266
6267 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00006268 }
6269
Richard Smith4a678122011-10-24 18:44:57 +00006270 /// Visit a value which is evaluated, but whose value is ignored.
6271 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00006272 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00006273 }
David Majnemere9807b22016-02-26 04:23:19 +00006274
6275 /// Potentially visit a MemberExpr's base expression.
6276 void VisitIgnoredBaseExpression(const Expr *E) {
6277 // While MSVC doesn't evaluate the base expression, it does diagnose the
6278 // presence of side-effecting behavior.
6279 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6280 return;
6281 VisitIgnoredValue(E);
6282 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006283};
6284
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006285} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00006286
6287//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006288// Common base class for lvalue and temporary evaluation.
6289//===----------------------------------------------------------------------===//
6290namespace {
6291template<class Derived>
6292class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006293 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00006294protected:
6295 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006296 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00006297 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006298 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00006299
6300 bool Success(APValue::LValueBase B) {
6301 Result.set(B);
6302 return true;
6303 }
6304
George Burgess IVf9013bf2017-02-10 22:52:29 +00006305 bool evaluatePointer(const Expr *E, LValue &Result) {
6306 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6307 }
6308
Richard Smith027bf112011-11-17 22:56:20 +00006309public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006310 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6311 : ExprEvaluatorBaseTy(Info), Result(Result),
6312 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00006313
Richard Smith2e312c82012-03-03 22:46:17 +00006314 bool Success(const APValue &V, const Expr *E) {
6315 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00006316 return true;
6317 }
Richard Smith027bf112011-11-17 22:56:20 +00006318
Richard Smith027bf112011-11-17 22:56:20 +00006319 bool VisitMemberExpr(const MemberExpr *E) {
6320 // Handle non-static data members.
6321 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006322 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00006323 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006324 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00006325 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00006326 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006327 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00006328 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00006329 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00006330 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00006331 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00006332 BaseTy = E->getBase()->getType();
6333 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00006334 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006335 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006336 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006337 Result.setInvalid(E);
6338 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006339 }
Richard Smith027bf112011-11-17 22:56:20 +00006340
Richard Smith1b78b3d2012-01-25 22:15:11 +00006341 const ValueDecl *MD = E->getMemberDecl();
6342 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6343 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6344 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6345 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00006346 if (!HandleLValueMember(this->Info, E, Result, FD))
6347 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006348 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00006349 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6350 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006351 } else
6352 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006353
Richard Smith1b78b3d2012-01-25 22:15:11 +00006354 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00006355 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00006356 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00006357 RefValue))
6358 return false;
6359 return Success(RefValue, E);
6360 }
6361 return true;
6362 }
6363
6364 bool VisitBinaryOperator(const BinaryOperator *E) {
6365 switch (E->getOpcode()) {
6366 default:
6367 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6368
6369 case BO_PtrMemD:
6370 case BO_PtrMemI:
6371 return HandleMemberPointerAccess(this->Info, E, Result);
6372 }
6373 }
6374
6375 bool VisitCastExpr(const CastExpr *E) {
6376 switch (E->getCastKind()) {
6377 default:
6378 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6379
6380 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006381 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00006382 if (!this->Visit(E->getSubExpr()))
6383 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006384
6385 // Now figure out the necessary offset to add to the base LV to get from
6386 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006387 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6388 Result);
Richard Smith027bf112011-11-17 22:56:20 +00006389 }
6390 }
6391};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006392}
Richard Smith027bf112011-11-17 22:56:20 +00006393
6394//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00006395// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006396//
6397// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6398// function designators (in C), decl references to void objects (in C), and
6399// temporaries (if building with -Wno-address-of-temporary).
6400//
6401// LValue evaluation produces values comprising a base expression of one of the
6402// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006403// - Declarations
6404// * VarDecl
6405// * FunctionDecl
6406// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006407// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006408// * StringLiteral
6409// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006410// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006411// * ObjCEncodeExpr
6412// * AddrLabelExpr
6413// * BlockExpr
6414// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006415// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006416// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006417// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006418// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006419// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6420// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006421// * A MaterializeTemporaryExpr that has static storage duration, with no
6422// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006423// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006424//===----------------------------------------------------------------------===//
6425namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006426class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006427 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006428public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006429 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6430 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006431
Richard Smith11562c52011-10-28 17:51:58 +00006432 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006433 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006434
Peter Collingbournee9200682011-05-13 03:29:01 +00006435 bool VisitDeclRefExpr(const DeclRefExpr *E);
6436 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006437 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006438 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6439 bool VisitMemberExpr(const MemberExpr *E);
6440 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6441 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006442 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006443 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006444 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6445 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006446 bool VisitUnaryReal(const UnaryOperator *E);
6447 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006448 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6449 return VisitUnaryPreIncDec(UO);
6450 }
6451 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6452 return VisitUnaryPreIncDec(UO);
6453 }
Richard Smith3229b742013-05-05 21:17:10 +00006454 bool VisitBinAssign(const BinaryOperator *BO);
6455 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006456
Peter Collingbournee9200682011-05-13 03:29:01 +00006457 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006458 switch (E->getCastKind()) {
6459 default:
Richard Smith027bf112011-11-17 22:56:20 +00006460 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006461
Eli Friedmance3e02a2011-10-11 00:13:24 +00006462 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006463 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006464 if (!Visit(E->getSubExpr()))
6465 return false;
6466 Result.Designator.setInvalid();
6467 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006468
Richard Smith027bf112011-11-17 22:56:20 +00006469 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006470 if (!Visit(E->getSubExpr()))
6471 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006472 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006473
6474 case CK_Dynamic:
6475 if (!Visit(E->getSubExpr()))
6476 return false;
6477 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006478 }
6479 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006480};
6481} // end anonymous namespace
6482
Richard Smith11562c52011-10-28 17:51:58 +00006483/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006484/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006485/// * function designators in C, and
6486/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006487/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006488static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6489 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006490 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006491 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006492 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006493}
6494
Peter Collingbournee9200682011-05-13 03:29:01 +00006495bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006496 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006497 return Success(FD);
6498 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006499 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006500 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006501 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006502 return Error(E);
6503}
Richard Smith733237d2011-10-24 23:14:33 +00006504
Faisal Vali0528a312016-11-13 06:09:16 +00006505
Richard Smith11562c52011-10-28 17:51:58 +00006506bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006507
6508 // If we are within a lambda's call operator, check whether the 'VD' referred
6509 // to within 'E' actually represents a lambda-capture that maps to a
6510 // data-member/field within the closure object, and if so, evaluate to the
6511 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006512 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6513 isa<DeclRefExpr>(E) &&
6514 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6515 // We don't always have a complete capture-map when checking or inferring if
6516 // the function call operator meets the requirements of a constexpr function
6517 // - but we don't need to evaluate the captures to determine constexprness
6518 // (dcl.constexpr C++17).
6519 if (Info.checkingPotentialConstantExpression())
6520 return false;
6521
Faisal Vali051e3a22017-02-16 04:12:21 +00006522 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006523 // Start with 'Result' referring to the complete closure object...
6524 Result = *Info.CurrentCall->This;
6525 // ... then update it to refer to the field of the closure object
6526 // that represents the capture.
6527 if (!HandleLValueMember(Info, E, Result, FD))
6528 return false;
6529 // And if the field is of reference type, update 'Result' to refer to what
6530 // the field refers to.
6531 if (FD->getType()->isReferenceType()) {
6532 APValue RVal;
6533 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6534 RVal))
6535 return false;
6536 Result.setFrom(Info.Ctx, RVal);
6537 }
6538 return true;
6539 }
6540 }
Craig Topper36250ad2014-05-12 05:36:57 +00006541 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006542 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6543 // Only if a local variable was declared in the function currently being
6544 // evaluated, do we expect to be able to find its value in the current
6545 // frame. (Otherwise it was likely declared in an enclosing context and
6546 // could either have a valid evaluatable value (for e.g. a constexpr
6547 // variable) or be ill-formed (and trigger an appropriate evaluation
6548 // diagnostic)).
6549 if (Info.CurrentCall->Callee &&
6550 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6551 Frame = Info.CurrentCall;
6552 }
6553 }
Richard Smith3229b742013-05-05 21:17:10 +00006554
Richard Smithfec09922011-11-01 16:57:24 +00006555 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006556 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006557 Result.set({VD, Frame->Index,
6558 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006559 return true;
6560 }
Richard Smithce40ad62011-11-12 22:28:03 +00006561 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006562 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006563
Richard Smith3229b742013-05-05 21:17:10 +00006564 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006565 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006566 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006567 if (!V->hasValue()) {
6568 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6569 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006570 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006571 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006572 return false;
6573 }
Richard Smith3229b742013-05-05 21:17:10 +00006574 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006575}
6576
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006577bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6578 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006579 // Walk through the expression to find the materialized temporary itself.
6580 SmallVector<const Expr *, 2> CommaLHSs;
6581 SmallVector<SubobjectAdjustment, 2> Adjustments;
6582 const Expr *Inner = E->GetTemporaryExpr()->
6583 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006584
Richard Smith84401042013-06-03 05:03:02 +00006585 // If we passed any comma operators, evaluate their LHSs.
6586 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6587 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6588 return false;
6589
Richard Smithe6c01442013-06-05 00:46:14 +00006590 // A materialized temporary with static storage duration can appear within the
6591 // result of a constant expression evaluation, so we need to preserve its
6592 // value for use outside this evaluation.
6593 APValue *Value;
6594 if (E->getStorageDuration() == SD_Static) {
6595 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006596 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006597 Result.set(E);
6598 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006599 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6600 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00006601 }
6602
Richard Smithea4ad5d2013-06-06 08:19:16 +00006603 QualType Type = Inner->getType();
6604
Richard Smith84401042013-06-03 05:03:02 +00006605 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006606 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6607 (E->getStorageDuration() == SD_Static &&
6608 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6609 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006610 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006611 }
Richard Smith84401042013-06-03 05:03:02 +00006612
6613 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006614 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6615 --I;
6616 switch (Adjustments[I].Kind) {
6617 case SubobjectAdjustment::DerivedToBaseAdjustment:
6618 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6619 Type, Result))
6620 return false;
6621 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6622 break;
6623
6624 case SubobjectAdjustment::FieldAdjustment:
6625 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6626 return false;
6627 Type = Adjustments[I].Field->getType();
6628 break;
6629
6630 case SubobjectAdjustment::MemberPointerAdjustment:
6631 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6632 Adjustments[I].Ptr.RHS))
6633 return false;
6634 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6635 break;
6636 }
6637 }
6638
6639 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006640}
6641
Peter Collingbournee9200682011-05-13 03:29:01 +00006642bool
6643LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006644 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6645 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006646 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6647 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006648 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006649}
6650
Richard Smith6e525142011-12-27 12:18:28 +00006651bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006652 TypeInfoLValue TypeInfo;
6653
Richard Smithee0ce3022019-05-17 07:06:46 +00006654 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006655 if (E->isTypeOperand())
6656 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6657 else
6658 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006659 } else {
6660 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6661 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6662 << E->getExprOperand()->getType()
6663 << E->getExprOperand()->getSourceRange();
6664 }
6665
6666 if (!Visit(E->getExprOperand()))
6667 return false;
6668
6669 Optional<DynamicType> DynType =
6670 ComputeDynamicType(Info, E, Result, AK_TypeId);
6671 if (!DynType)
6672 return false;
6673
6674 TypeInfo =
6675 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006676 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006677
Richard Smitha9330302019-05-17 19:19:28 +00006678 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006679}
6680
Francois Pichet0066db92012-04-16 04:08:35 +00006681bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6682 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006683}
Francois Pichet0066db92012-04-16 04:08:35 +00006684
Peter Collingbournee9200682011-05-13 03:29:01 +00006685bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006686 // Handle static data members.
6687 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006688 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006689 return VisitVarDecl(E, VD);
6690 }
6691
Richard Smith254a73d2011-10-28 22:34:42 +00006692 // Handle static member functions.
6693 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6694 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006695 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006696 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006697 }
6698 }
6699
Richard Smithd62306a2011-11-10 06:34:14 +00006700 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006701 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006702}
6703
Peter Collingbournee9200682011-05-13 03:29:01 +00006704bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006705 // FIXME: Deal with vectors as array subscript bases.
6706 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006707 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006708
Nick Lewyckyad888682017-04-27 07:27:36 +00006709 bool Success = true;
6710 if (!evaluatePointer(E->getBase(), Result)) {
6711 if (!Info.noteFailure())
6712 return false;
6713 Success = false;
6714 }
Mike Stump11289f42009-09-09 15:08:12 +00006715
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006716 APSInt Index;
6717 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006718 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006719
Nick Lewyckyad888682017-04-27 07:27:36 +00006720 return Success &&
6721 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006722}
Eli Friedman9a156e52008-11-12 09:44:48 +00006723
Peter Collingbournee9200682011-05-13 03:29:01 +00006724bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006725 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006726}
6727
Richard Smith66c96992012-02-18 22:04:06 +00006728bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6729 if (!Visit(E->getSubExpr()))
6730 return false;
6731 // __real is a no-op on scalar lvalues.
6732 if (E->getSubExpr()->getType()->isAnyComplexType())
6733 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6734 return true;
6735}
6736
6737bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6738 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6739 "lvalue __imag__ on scalar?");
6740 if (!Visit(E->getSubExpr()))
6741 return false;
6742 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6743 return true;
6744}
6745
Richard Smith243ef902013-05-05 23:31:59 +00006746bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006747 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006748 return Error(UO);
6749
6750 if (!this->Visit(UO->getSubExpr()))
6751 return false;
6752
Richard Smith243ef902013-05-05 23:31:59 +00006753 return handleIncDec(
6754 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006755 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006756}
6757
6758bool LValueExprEvaluator::VisitCompoundAssignOperator(
6759 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006760 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006761 return Error(CAO);
6762
Richard Smith3229b742013-05-05 21:17:10 +00006763 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006764
6765 // The overall lvalue result is the result of evaluating the LHS.
6766 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006767 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006768 Evaluate(RHS, this->Info, CAO->getRHS());
6769 return false;
6770 }
6771
Richard Smith3229b742013-05-05 21:17:10 +00006772 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6773 return false;
6774
Richard Smith43e77732013-05-07 04:50:00 +00006775 return handleCompoundAssignment(
6776 this->Info, CAO,
6777 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6778 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006779}
6780
6781bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006782 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006783 return Error(E);
6784
Richard Smith3229b742013-05-05 21:17:10 +00006785 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006786
6787 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006788 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006789 Evaluate(NewVal, this->Info, E->getRHS());
6790 return false;
6791 }
6792
Richard Smith3229b742013-05-05 21:17:10 +00006793 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6794 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006795
Richard Smith31c69a32019-05-21 23:15:20 +00006796 if (Info.getLangOpts().CPlusPlus2a &&
6797 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6798 return false;
6799
Richard Smith243ef902013-05-05 23:31:59 +00006800 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006801 NewVal);
6802}
6803
Eli Friedman9a156e52008-11-12 09:44:48 +00006804//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006805// Pointer Evaluation
6806//===----------------------------------------------------------------------===//
6807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006808/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006809/// returned by a function with the alloc_size attribute. Returns true if we
6810/// were successful. Places an unsigned number into `Result`.
6811///
6812/// This expects the given CallExpr to be a call to a function with an
6813/// alloc_size attribute.
6814static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6815 const CallExpr *Call,
6816 llvm::APInt &Result) {
6817 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6818
Joel E. Denny81508102018-03-13 14:51:22 +00006819 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6820 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006821 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6822 if (Call->getNumArgs() <= SizeArgNo)
6823 return false;
6824
6825 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006826 Expr::EvalResult ExprResult;
6827 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006828 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006829 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006830 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6831 return false;
6832 Into = Into.zextOrSelf(BitsInSizeT);
6833 return true;
6834 };
6835
6836 APSInt SizeOfElem;
6837 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6838 return false;
6839
Joel E. Denny81508102018-03-13 14:51:22 +00006840 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006841 Result = std::move(SizeOfElem);
6842 return true;
6843 }
6844
6845 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006846 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006847 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6848 return false;
6849
6850 bool Overflow;
6851 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6852 if (Overflow)
6853 return false;
6854
6855 Result = std::move(BytesAvailable);
6856 return true;
6857}
6858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006859/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006860/// function.
6861static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6862 const LValue &LVal,
6863 llvm::APInt &Result) {
6864 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6865 "Can't get the size of a non alloc_size function");
6866 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6867 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6868 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6869}
6870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006871/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006872/// a function with the alloc_size attribute. If it was possible to do so, this
6873/// function will return true, make Result's Base point to said function call,
6874/// and mark Result's Base as invalid.
6875static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6876 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006877 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006878 return false;
6879
6880 // Because we do no form of static analysis, we only support const variables.
6881 //
6882 // Additionally, we can't support parameters, nor can we support static
6883 // variables (in the latter case, use-before-assign isn't UB; in the former,
6884 // we have no clue what they'll be assigned to).
6885 const auto *VD =
6886 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6887 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6888 return false;
6889
6890 const Expr *Init = VD->getAnyInitializer();
6891 if (!Init)
6892 return false;
6893
6894 const Expr *E = Init->IgnoreParens();
6895 if (!tryUnwrapAllocSizeCall(E))
6896 return false;
6897
6898 // Store E instead of E unwrapped so that the type of the LValue's base is
6899 // what the user wanted.
6900 Result.setInvalid(E);
6901
6902 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006903 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00006904 return true;
6905}
6906
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006907namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006908class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006909 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00006910 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006911 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00006912
Peter Collingbournee9200682011-05-13 03:29:01 +00006913 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00006914 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00006915 return true;
6916 }
George Burgess IVe3763372016-12-22 02:50:20 +00006917
George Burgess IVf9013bf2017-02-10 22:52:29 +00006918 bool evaluateLValue(const Expr *E, LValue &Result) {
6919 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6920 }
6921
6922 bool evaluatePointer(const Expr *E, LValue &Result) {
6923 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6924 }
6925
George Burgess IVe3763372016-12-22 02:50:20 +00006926 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006927public:
Mike Stump11289f42009-09-09 15:08:12 +00006928
George Burgess IVf9013bf2017-02-10 22:52:29 +00006929 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6930 : ExprEvaluatorBaseTy(info), Result(Result),
6931 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006932
Richard Smith2e312c82012-03-03 22:46:17 +00006933 bool Success(const APValue &V, const Expr *E) {
6934 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00006935 return true;
6936 }
Richard Smithfddd3842011-12-30 21:15:51 +00006937 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00006938 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6939 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00006940 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00006941 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006942
John McCall45d55e42010-05-07 21:00:08 +00006943 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006944 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00006945 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006946 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00006947 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006948 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00006949 if (E->isExpressibleAsConstantInitializer())
6950 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006951 if (Info.noteFailure())
6952 EvaluateIgnoredValue(Info, E->getSubExpr());
6953 return Error(E);
6954 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006955 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00006956 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00006957 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006958 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00006959 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00006960 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00006961 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006962 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00006963 }
Richard Smithd62306a2011-11-10 06:34:14 +00006964 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006965 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00006966 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00006967 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00006968 if (!Info.CurrentCall->This) {
6969 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00006970 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00006971 else
Faisal Valie690b7a2016-07-02 22:34:24 +00006972 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00006973 return false;
6974 }
Richard Smithd62306a2011-11-10 06:34:14 +00006975 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00006976 // If we are inside a lambda's call operator, the 'this' expression refers
6977 // to the enclosing '*this' object (either by value or reference) which is
6978 // either copied into the closure object's field that represents the '*this'
6979 // or refers to '*this'.
6980 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6981 // Update 'Result' to refer to the data member/field of the closure object
6982 // that represents the '*this' capture.
6983 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00006984 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00006985 return false;
6986 // If we captured '*this' by reference, replace the field with its referent.
6987 if (Info.CurrentCall->LambdaThisCaptureField->getType()
6988 ->isPointerType()) {
6989 APValue RVal;
6990 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6991 RVal))
6992 return false;
6993
6994 Result.setFrom(Info.Ctx, RVal);
6995 }
6996 }
Richard Smithd62306a2011-11-10 06:34:14 +00006997 return true;
6998 }
John McCallc07a0c72011-02-17 10:25:35 +00006999
Eric Fiselier708afb52019-05-16 21:04:15 +00007000 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7001 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7002 APValue LValResult = E->EvaluateInContext(
7003 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7004 Result.setFrom(Info.Ctx, LValResult);
7005 return true;
7006 }
7007
Eli Friedman449fe542009-03-23 04:56:01 +00007008 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007009};
Chris Lattner05706e882008-07-11 18:11:29 +00007010} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007011
George Burgess IVf9013bf2017-02-10 22:52:29 +00007012static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7013 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007014 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007015 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007016}
7017
John McCall45d55e42010-05-07 21:00:08 +00007018bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007019 if (E->getOpcode() != BO_Add &&
7020 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007021 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007022
Chris Lattner05706e882008-07-11 18:11:29 +00007023 const Expr *PExp = E->getLHS();
7024 const Expr *IExp = E->getRHS();
7025 if (IExp->getType()->isPointerType())
7026 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007027
George Burgess IVf9013bf2017-02-10 22:52:29 +00007028 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007029 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007030 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007031
John McCall45d55e42010-05-07 21:00:08 +00007032 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007033 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007034 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007035
Richard Smith96e0c102011-11-04 02:25:55 +00007036 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007037 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007038
Ted Kremenek28831752012-08-23 20:46:57 +00007039 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007040 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007041}
Eli Friedman9a156e52008-11-12 09:44:48 +00007042
John McCall45d55e42010-05-07 21:00:08 +00007043bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007044 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007045}
Mike Stump11289f42009-09-09 15:08:12 +00007046
Richard Smith81dfef92018-07-11 00:29:05 +00007047bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7048 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007049
Eli Friedman847a2bc2009-12-27 05:43:15 +00007050 switch (E->getCastKind()) {
7051 default:
7052 break;
John McCalle3027922010-08-25 11:45:40 +00007053 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007054 case CK_CPointerToObjCPointerCast:
7055 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007056 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007057 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007058 if (!Visit(SubExpr))
7059 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007060 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7061 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7062 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007063 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00007064 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00007065 if (SubExpr->getType()->isVoidPointerType())
7066 CCEDiag(E, diag::note_constexpr_invalid_cast)
7067 << 3 << SubExpr->getType();
7068 else
7069 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7070 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007071 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7072 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007073 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007074
Anders Carlsson18275092010-10-31 20:41:46 +00007075 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007076 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007077 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007078 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007079 if (!Result.Base && Result.Offset.isZero())
7080 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007081
Richard Smithd62306a2011-11-10 06:34:14 +00007082 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007083 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007084 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7085 castAs<PointerType>()->getPointeeType(),
7086 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007087
Richard Smith027bf112011-11-17 22:56:20 +00007088 case CK_BaseToDerived:
7089 if (!Visit(E->getSubExpr()))
7090 return false;
7091 if (!Result.Base && Result.Offset.isZero())
7092 return true;
7093 return HandleBaseToDerivedCast(Info, E, Result);
7094
Richard Smith7bd54ab2019-05-15 20:22:21 +00007095 case CK_Dynamic:
7096 if (!Visit(E->getSubExpr()))
7097 return false;
7098 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7099
Richard Smith0b0a0b62011-10-29 20:57:55 +00007100 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007101 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007102 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007103
John McCalle3027922010-08-25 11:45:40 +00007104 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007105 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7106
Richard Smith2e312c82012-03-03 22:46:17 +00007107 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007108 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007109 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007110
John McCall45d55e42010-05-07 21:00:08 +00007111 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007112 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7113 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007114 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007115 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007116 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007117 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007118 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007119 return true;
7120 } else {
7121 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007122 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007123 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007124 }
7125 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007126
7127 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007128 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007129 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007130 return false;
7131 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007132 APValue &Value = createTemporary(SubExpr, false, Result,
7133 *Info.CurrentCall);
7134 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007135 return false;
7136 }
Richard Smith96e0c102011-11-04 02:25:55 +00007137 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00007138 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7139 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00007140 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00007141 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00007142 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00007143 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00007144 }
Richard Smithdd785442011-10-31 20:57:44 +00007145
John McCalle3027922010-08-25 11:45:40 +00007146 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007147 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007148
7149 case CK_LValueToRValue: {
7150 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007151 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00007152 return false;
7153
7154 APValue RVal;
7155 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7156 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7157 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00007158 return InvalidBaseOK &&
7159 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007160 return Success(RVal, E);
7161 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007162 }
7163
Richard Smith11562c52011-10-28 17:51:58 +00007164 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00007165}
Chris Lattner05706e882008-07-11 18:11:29 +00007166
Richard Smith6822bd72018-10-26 19:26:45 +00007167static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7168 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007169 // C++ [expr.alignof]p3:
7170 // When alignof is applied to a reference type, the result is the
7171 // alignment of the referenced type.
7172 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7173 T = Ref->getPointeeType();
7174
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00007175 if (T.getQualifiers().hasUnaligned())
7176 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00007177
7178 const bool AlignOfReturnsPreferred =
7179 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7180
7181 // __alignof is defined to return the preferred alignment.
7182 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7183 // as well.
7184 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7185 return Info.Ctx.toCharUnitsFromBits(
7186 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7187 // alignof and _Alignof are defined to return the ABI alignment.
7188 else if (ExprKind == UETT_AlignOf)
7189 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7190 else
7191 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00007192}
7193
Richard Smith6822bd72018-10-26 19:26:45 +00007194static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7195 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007196 E = E->IgnoreParens();
7197
7198 // The kinds of expressions that we have special-case logic here for
7199 // should be kept up to date with the special checks for those
7200 // expressions in Sema.
7201
7202 // alignof decl is always accepted, even if it doesn't make sense: we default
7203 // to 1 in those cases.
7204 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7205 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7206 /*RefAsPointee*/true);
7207
7208 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7209 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7210 /*RefAsPointee*/true);
7211
Richard Smith6822bd72018-10-26 19:26:45 +00007212 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007213}
7214
George Burgess IVe3763372016-12-22 02:50:20 +00007215// To be clear: this happily visits unsupported builtins. Better name welcomed.
7216bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7217 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7218 return true;
7219
George Burgess IVf9013bf2017-02-10 22:52:29 +00007220 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00007221 return false;
7222
7223 Result.setInvalid(E);
7224 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007225 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00007226 return true;
7227}
7228
Peter Collingbournee9200682011-05-13 03:29:01 +00007229bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007230 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00007231 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00007232
Richard Smith6328cbd2016-11-16 00:57:23 +00007233 if (unsigned BuiltinOp = E->getBuiltinCallee())
7234 return VisitBuiltinCallExpr(E, BuiltinOp);
7235
George Burgess IVe3763372016-12-22 02:50:20 +00007236 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007237}
7238
7239bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7240 unsigned BuiltinOp) {
7241 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00007242 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007243 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007244 case Builtin::BI__builtin_assume_aligned: {
7245 // We need to be very careful here because: if the pointer does not have the
7246 // asserted alignment, then the behavior is undefined, and undefined
7247 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00007248 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00007249 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00007250
Hal Finkel0dd05d42014-10-03 17:18:37 +00007251 LValue OffsetResult(Result);
7252 APSInt Alignment;
7253 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7254 return false;
Richard Smith642a2362017-01-30 23:30:26 +00007255 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00007256
7257 if (E->getNumArgs() > 2) {
7258 APSInt Offset;
7259 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7260 return false;
7261
Richard Smith642a2362017-01-30 23:30:26 +00007262 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007263 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7264 }
7265
7266 // If there is a base object, then it must have the correct alignment.
7267 if (OffsetResult.Base) {
7268 CharUnits BaseAlignment;
7269 if (const ValueDecl *VD =
7270 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7271 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00007272 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7273 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007274 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00007275 BaseAlignment = GetAlignOfType(
7276 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007277 }
7278
7279 if (BaseAlignment < Align) {
7280 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00007281 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00007282 CCEDiag(E->getArg(0),
7283 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00007284 << (unsigned)BaseAlignment.getQuantity()
7285 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007286 return false;
7287 }
7288 }
7289
7290 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007291 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007292 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007293
Richard Smith642a2362017-01-30 23:30:26 +00007294 (OffsetResult.Base
7295 ? CCEDiag(E->getArg(0),
7296 diag::note_constexpr_baa_insufficient_alignment) << 1
7297 : CCEDiag(E->getArg(0),
7298 diag::note_constexpr_baa_value_insufficient_alignment))
7299 << (int)OffsetResult.Offset.getQuantity()
7300 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007301 return false;
7302 }
7303
7304 return true;
7305 }
Eric Fiselier26187502018-12-14 21:11:28 +00007306 case Builtin::BI__builtin_launder:
7307 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00007308 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007309 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00007310 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007311 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00007312 if (Info.getLangOpts().CPlusPlus11)
7313 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7314 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007315 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00007316 else
7317 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007318 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00007319 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007320 case Builtin::BI__builtin_wcschr:
7321 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007322 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007323 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00007324 if (!Visit(E->getArg(0)))
7325 return false;
7326 APSInt Desired;
7327 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7328 return false;
7329 uint64_t MaxLength = uint64_t(-1);
7330 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007331 BuiltinOp != Builtin::BIwcschr &&
7332 BuiltinOp != Builtin::BI__builtin_strchr &&
7333 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00007334 APSInt N;
7335 if (!EvaluateInteger(E->getArg(2), N, Info))
7336 return false;
7337 MaxLength = N.getExtValue();
7338 }
Hubert Tong147b7432018-12-12 16:53:43 +00007339 // We cannot find the value if there are no candidates to match against.
7340 if (MaxLength == 0u)
7341 return ZeroInitialization(E);
7342 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7343 Result.Designator.Invalid)
7344 return false;
7345 QualType CharTy = Result.Designator.getType(Info.Ctx);
7346 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7347 BuiltinOp == Builtin::BI__builtin_memchr;
7348 assert(IsRawByte ||
7349 Info.Ctx.hasSameUnqualifiedType(
7350 CharTy, E->getArg(0)->getType()->getPointeeType()));
7351 // Pointers to const void may point to objects of incomplete type.
7352 if (IsRawByte && CharTy->isIncompleteType()) {
7353 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7354 return false;
7355 }
7356 // Give up on byte-oriented matching against multibyte elements.
7357 // FIXME: We can compare the bytes in the correct order.
7358 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7359 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007360 // Figure out what value we're actually looking for (after converting to
7361 // the corresponding unsigned type if necessary).
7362 uint64_t DesiredVal;
7363 bool StopAtNull = false;
7364 switch (BuiltinOp) {
7365 case Builtin::BIstrchr:
7366 case Builtin::BI__builtin_strchr:
7367 // strchr compares directly to the passed integer, and therefore
7368 // always fails if given an int that is not a char.
7369 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7370 E->getArg(1)->getType(),
7371 Desired),
7372 Desired))
7373 return ZeroInitialization(E);
7374 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007375 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007376 case Builtin::BImemchr:
7377 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007378 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007379 // memchr compares by converting both sides to unsigned char. That's also
7380 // correct for strchr if we get this far (to cope with plain char being
7381 // unsigned in the strchr case).
7382 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7383 break;
Richard Smithe9507952016-11-12 01:39:56 +00007384
Richard Smith8110c9d2016-11-29 19:45:17 +00007385 case Builtin::BIwcschr:
7386 case Builtin::BI__builtin_wcschr:
7387 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007388 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007389 case Builtin::BIwmemchr:
7390 case Builtin::BI__builtin_wmemchr:
7391 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7392 DesiredVal = Desired.getZExtValue();
7393 break;
7394 }
Richard Smithe9507952016-11-12 01:39:56 +00007395
7396 for (; MaxLength; --MaxLength) {
7397 APValue Char;
7398 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7399 !Char.isInt())
7400 return false;
7401 if (Char.getInt().getZExtValue() == DesiredVal)
7402 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007403 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007404 break;
7405 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7406 return false;
7407 }
7408 // Not found: return nullptr.
7409 return ZeroInitialization(E);
7410 }
7411
Richard Smith06f71b52018-08-04 00:57:17 +00007412 case Builtin::BImemcpy:
7413 case Builtin::BImemmove:
7414 case Builtin::BIwmemcpy:
7415 case Builtin::BIwmemmove:
7416 if (Info.getLangOpts().CPlusPlus11)
7417 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7418 << /*isConstexpr*/0 << /*isConstructor*/0
7419 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7420 else
7421 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7422 LLVM_FALLTHROUGH;
7423 case Builtin::BI__builtin_memcpy:
7424 case Builtin::BI__builtin_memmove:
7425 case Builtin::BI__builtin_wmemcpy:
7426 case Builtin::BI__builtin_wmemmove: {
7427 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7428 BuiltinOp == Builtin::BIwmemmove ||
7429 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7430 BuiltinOp == Builtin::BI__builtin_wmemmove;
7431 bool Move = BuiltinOp == Builtin::BImemmove ||
7432 BuiltinOp == Builtin::BIwmemmove ||
7433 BuiltinOp == Builtin::BI__builtin_memmove ||
7434 BuiltinOp == Builtin::BI__builtin_wmemmove;
7435
7436 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007437 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007438 return false;
7439 LValue Dest = Result;
7440
7441 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007442 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007443 return false;
7444
7445 APSInt N;
7446 if (!EvaluateInteger(E->getArg(2), N, Info))
7447 return false;
7448 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7449
7450 // If the size is zero, we treat this as always being a valid no-op.
7451 // (Even if one of the src and dest pointers is null.)
7452 if (!N)
7453 return true;
7454
Richard Smith128719c2018-09-13 22:47:33 +00007455 // Otherwise, if either of the operands is null, we can't proceed. Don't
7456 // try to determine the type of the copied objects, because there aren't
7457 // any.
7458 if (!Src.Base || !Dest.Base) {
7459 APValue Val;
7460 (!Src.Base ? Src : Dest).moveInto(Val);
7461 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7462 << Move << WChar << !!Src.Base
7463 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7464 return false;
7465 }
7466 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7467 return false;
7468
Richard Smith06f71b52018-08-04 00:57:17 +00007469 // We require that Src and Dest are both pointers to arrays of
7470 // trivially-copyable type. (For the wide version, the designator will be
7471 // invalid if the designated object is not a wchar_t.)
7472 QualType T = Dest.Designator.getType(Info.Ctx);
7473 QualType SrcT = Src.Designator.getType(Info.Ctx);
7474 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7475 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7476 return false;
7477 }
Petr Pavlued083f22018-10-04 09:25:44 +00007478 if (T->isIncompleteType()) {
7479 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7480 return false;
7481 }
Richard Smith06f71b52018-08-04 00:57:17 +00007482 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7483 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7484 return false;
7485 }
7486
7487 // Figure out how many T's we're copying.
7488 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7489 if (!WChar) {
7490 uint64_t Remainder;
7491 llvm::APInt OrigN = N;
7492 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7493 if (Remainder) {
7494 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7495 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7496 << (unsigned)TSize;
7497 return false;
7498 }
7499 }
7500
7501 // Check that the copying will remain within the arrays, just so that we
7502 // can give a more meaningful diagnostic. This implicitly also checks that
7503 // N fits into 64 bits.
7504 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7505 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7506 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7507 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7508 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7509 << N.toString(10, /*Signed*/false);
7510 return false;
7511 }
7512 uint64_t NElems = N.getZExtValue();
7513 uint64_t NBytes = NElems * TSize;
7514
7515 // Check for overlap.
7516 int Direction = 1;
7517 if (HasSameBase(Src, Dest)) {
7518 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7519 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7520 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7521 // Dest is inside the source region.
7522 if (!Move) {
7523 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7524 return false;
7525 }
7526 // For memmove and friends, copy backwards.
7527 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7528 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7529 return false;
7530 Direction = -1;
7531 } else if (!Move && SrcOffset >= DestOffset &&
7532 SrcOffset - DestOffset < NBytes) {
7533 // Src is inside the destination region for memcpy: invalid.
7534 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7535 return false;
7536 }
7537 }
7538
7539 while (true) {
7540 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00007541 // FIXME: Set WantObjectRepresentation to true if we're copying a
7542 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00007543 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7544 !handleAssignment(Info, E, Dest, T, Val))
7545 return false;
7546 // Do not iterate past the last element; if we're copying backwards, that
7547 // might take us off the start of the array.
7548 if (--NElems == 0)
7549 return true;
7550 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7551 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7552 return false;
7553 }
7554 }
7555
Richard Smith6cbd65d2013-07-11 02:27:57 +00007556 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007557 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007558 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007559}
Chris Lattner05706e882008-07-11 18:11:29 +00007560
7561//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007562// Member Pointer Evaluation
7563//===----------------------------------------------------------------------===//
7564
7565namespace {
7566class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007567 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007568 MemberPtr &Result;
7569
7570 bool Success(const ValueDecl *D) {
7571 Result = MemberPtr(D);
7572 return true;
7573 }
7574public:
7575
7576 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7577 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7578
Richard Smith2e312c82012-03-03 22:46:17 +00007579 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007580 Result.setFrom(V);
7581 return true;
7582 }
Richard Smithfddd3842011-12-30 21:15:51 +00007583 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007584 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007585 }
7586
7587 bool VisitCastExpr(const CastExpr *E);
7588 bool VisitUnaryAddrOf(const UnaryOperator *E);
7589};
7590} // end anonymous namespace
7591
7592static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7593 EvalInfo &Info) {
7594 assert(E->isRValue() && E->getType()->isMemberPointerType());
7595 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7596}
7597
7598bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7599 switch (E->getCastKind()) {
7600 default:
7601 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7602
7603 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007604 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007605 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007606
7607 case CK_BaseToDerivedMemberPointer: {
7608 if (!Visit(E->getSubExpr()))
7609 return false;
7610 if (E->path_empty())
7611 return true;
7612 // Base-to-derived member pointer casts store the path in derived-to-base
7613 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7614 // the wrong end of the derived->base arc, so stagger the path by one class.
7615 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7616 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7617 PathI != PathE; ++PathI) {
7618 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7619 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7620 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007621 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007622 }
7623 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7624 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007625 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007626 return true;
7627 }
7628
7629 case CK_DerivedToBaseMemberPointer:
7630 if (!Visit(E->getSubExpr()))
7631 return false;
7632 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7633 PathE = E->path_end(); PathI != PathE; ++PathI) {
7634 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7635 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7636 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007637 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007638 }
7639 return true;
7640 }
7641}
7642
7643bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7644 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7645 // member can be formed.
7646 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7647}
7648
7649//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007650// Record Evaluation
7651//===----------------------------------------------------------------------===//
7652
7653namespace {
7654 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007655 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007656 const LValue &This;
7657 APValue &Result;
7658 public:
7659
7660 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7661 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7662
Richard Smith2e312c82012-03-03 22:46:17 +00007663 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007664 Result = V;
7665 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007666 }
Richard Smithb8348f52016-05-12 22:16:28 +00007667 bool ZeroInitialization(const Expr *E) {
7668 return ZeroInitialization(E, E->getType());
7669 }
7670 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007671
Richard Smith52a980a2015-08-28 02:43:42 +00007672 bool VisitCallExpr(const CallExpr *E) {
7673 return handleCallExpr(E, Result, &This);
7674 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007675 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007676 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007677 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7678 return VisitCXXConstructExpr(E, E->getType());
7679 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007680 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007681 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007682 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007683 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007684
7685 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007686 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007687}
Richard Smithd62306a2011-11-10 06:34:14 +00007688
Richard Smithfddd3842011-12-30 21:15:51 +00007689/// Perform zero-initialization on an object of non-union class type.
7690/// C++11 [dcl.init]p5:
7691/// To zero-initialize an object or reference of type T means:
7692/// [...]
7693/// -- if T is a (possibly cv-qualified) non-union class type,
7694/// each non-static data member and each base-class subobject is
7695/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007696static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7697 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007698 const LValue &This, APValue &Result) {
7699 assert(!RD->isUnion() && "Expected non-union class type");
7700 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7701 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007702 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007703
John McCalld7bca762012-05-01 00:38:49 +00007704 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007705 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7706
7707 if (CD) {
7708 unsigned Index = 0;
7709 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007710 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007711 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7712 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007713 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7714 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007715 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007716 Result.getStructBase(Index)))
7717 return false;
7718 }
7719 }
7720
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007721 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007722 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007723 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007724 continue;
7725
7726 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007727 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007728 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007729
David Blaikie2d7c57e2012-04-30 02:36:29 +00007730 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007731 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007732 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007733 return false;
7734 }
7735
7736 return true;
7737}
7738
Richard Smithb8348f52016-05-12 22:16:28 +00007739bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7740 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007741 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007742 if (RD->isUnion()) {
7743 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7744 // object's first non-static named data member is zero-initialized
7745 RecordDecl::field_iterator I = RD->field_begin();
7746 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007747 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007748 return true;
7749 }
7750
7751 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007752 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007753 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007754 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007755 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007756 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007757 }
7758
Richard Smith5d108602012-02-17 00:44:16 +00007759 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007760 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007761 return false;
7762 }
7763
Richard Smitha8105bc2012-01-06 16:39:00 +00007764 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007765}
7766
Richard Smithe97cbd72011-11-11 04:05:33 +00007767bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7768 switch (E->getCastKind()) {
7769 default:
7770 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7771
7772 case CK_ConstructorConversion:
7773 return Visit(E->getSubExpr());
7774
7775 case CK_DerivedToBase:
7776 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007777 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007778 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007779 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007780 if (!DerivedObject.isStruct())
7781 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007782
7783 // Derived-to-base rvalue conversion: just slice off the derived part.
7784 APValue *Value = &DerivedObject;
7785 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7786 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7787 PathE = E->path_end(); PathI != PathE; ++PathI) {
7788 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7789 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7790 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7791 RD = Base;
7792 }
7793 Result = *Value;
7794 return true;
7795 }
7796 }
7797}
7798
Richard Smithd62306a2011-11-10 06:34:14 +00007799bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007800 if (E->isTransparent())
7801 return Visit(E->getInit(0));
7802
Richard Smithd62306a2011-11-10 06:34:14 +00007803 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007804 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007805 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007806 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7807
7808 EvalInfo::EvaluatingConstructorRAII EvalObj(
7809 Info,
7810 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7811 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007812
7813 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007814 const FieldDecl *Field = E->getInitializedFieldInUnion();
7815 Result = APValue(Field);
7816 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007817 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007818
7819 // If the initializer list for a union does not contain any elements, the
7820 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007821 // FIXME: The element should be initialized from an initializer list.
7822 // Is this difference ever observable for initializer lists which
7823 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007824 ImplicitValueInitExpr VIE(Field->getType());
7825 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7826
Richard Smithd62306a2011-11-10 06:34:14 +00007827 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007828 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7829 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007830
7831 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7832 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7833 isa<CXXDefaultInitExpr>(InitExpr));
7834
Richard Smithb228a862012-02-15 02:18:13 +00007835 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007836 }
7837
Richard Smithe637cbe2019-05-21 23:15:18 +00007838 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007839 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7840 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007841 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007842 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007843
7844 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007845 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007846 for (const auto &Base : CXXRD->bases()) {
7847 assert(ElementNo < E->getNumInits() && "missing init for base class");
7848 const Expr *Init = E->getInit(ElementNo);
7849
7850 LValue Subobject = This;
7851 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7852 return false;
7853
7854 APValue &FieldVal = Result.getStructBase(ElementNo);
7855 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007856 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007857 return false;
7858 Success = false;
7859 }
7860 ++ElementNo;
7861 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007862
7863 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007864 }
7865
7866 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007867 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007868 // Anonymous bit-fields are not considered members of the class for
7869 // purposes of aggregate initialization.
7870 if (Field->isUnnamedBitfield())
7871 continue;
7872
7873 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007874
Richard Smith253c2a32012-01-27 01:14:48 +00007875 bool HaveInit = ElementNo < E->getNumInits();
7876
7877 // FIXME: Diagnostics here should point to the end of the initializer
7878 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007879 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007880 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007881 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007882
7883 // Perform an implicit value-initialization for members beyond the end of
7884 // the initializer list.
7885 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007886 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007887
Richard Smith852c9db2013-04-20 22:23:05 +00007888 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7889 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7890 isa<CXXDefaultInitExpr>(Init));
7891
Richard Smith49ca8aa2013-08-06 07:09:20 +00007892 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7893 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7894 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007895 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007896 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007897 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007898 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007899 }
7900 }
7901
Richard Smith253c2a32012-01-27 01:14:48 +00007902 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00007903}
7904
Richard Smithb8348f52016-05-12 22:16:28 +00007905bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7906 QualType T) {
7907 // Note that E's type is not necessarily the type of our class here; we might
7908 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00007909 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00007910 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7911
Richard Smithfddd3842011-12-30 21:15:51 +00007912 bool ZeroInit = E->requiresZeroInitialization();
7913 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00007914 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00007915 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00007916 return true;
7917
Richard Smithc667cdc2019-09-18 17:37:44 +00007918 if (ZeroInit)
7919 return ZeroInitialization(E, T);
7920
7921 Result = getDefaultInitValue(T);
7922 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00007923 }
7924
Craig Topper36250ad2014-05-12 05:36:57 +00007925 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007926 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00007927
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007928 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00007929 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007930
Richard Smith1bc5c2c2012-01-10 04:32:03 +00007931 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00007932 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00007933 if (const MaterializeTemporaryExpr *ME
7934 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7935 return Visit(ME->GetTemporaryExpr());
7936
Richard Smithb8348f52016-05-12 22:16:28 +00007937 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00007938 return false;
7939
Craig Topper5fc8fc22014-08-27 06:28:36 +00007940 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00007941 return HandleConstructorCall(E, This, Args,
7942 cast<CXXConstructorDecl>(Definition), Info,
7943 Result);
7944}
7945
7946bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7947 const CXXInheritedCtorInitExpr *E) {
7948 if (!Info.CurrentCall) {
7949 assert(Info.checkingPotentialConstantExpression());
7950 return false;
7951 }
7952
7953 const CXXConstructorDecl *FD = E->getConstructor();
7954 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7955 return false;
7956
7957 const FunctionDecl *Definition = nullptr;
7958 auto Body = FD->getBody(Definition);
7959
7960 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7961 return false;
7962
7963 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00007964 cast<CXXConstructorDecl>(Definition), Info,
7965 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00007966}
7967
Richard Smithcc1b96d2013-06-12 22:31:48 +00007968bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7969 const CXXStdInitializerListExpr *E) {
7970 const ConstantArrayType *ArrayType =
7971 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7972
7973 LValue Array;
7974 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7975 return false;
7976
7977 // Get a pointer to the first element of the array.
7978 Array.addArray(Info, E, ArrayType);
7979
7980 // FIXME: Perform the checks on the field types in SemaInit.
7981 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7982 RecordDecl::field_iterator Field = Record->field_begin();
7983 if (Field == Record->field_end())
7984 return Error(E);
7985
7986 // Start pointer.
7987 if (!Field->getType()->isPointerType() ||
7988 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7989 ArrayType->getElementType()))
7990 return Error(E);
7991
7992 // FIXME: What if the initializer_list type has base classes, etc?
7993 Result = APValue(APValue::UninitStruct(), 0, 2);
7994 Array.moveInto(Result.getStructField(0));
7995
7996 if (++Field == Record->field_end())
7997 return Error(E);
7998
7999 if (Field->getType()->isPointerType() &&
8000 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8001 ArrayType->getElementType())) {
8002 // End pointer.
8003 if (!HandleLValueArrayAdjustment(Info, E, Array,
8004 ArrayType->getElementType(),
8005 ArrayType->getSize().getZExtValue()))
8006 return false;
8007 Array.moveInto(Result.getStructField(1));
8008 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8009 // Length.
8010 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8011 else
8012 return Error(E);
8013
8014 if (++Field != Record->field_end())
8015 return Error(E);
8016
8017 return true;
8018}
8019
Faisal Valic72a08c2017-01-09 03:02:53 +00008020bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8021 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8022 if (ClosureClass->isInvalidDecl()) return false;
8023
8024 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008025
Faisal Vali051e3a22017-02-16 04:12:21 +00008026 const size_t NumFields =
8027 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00008028
8029 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8030 E->capture_init_end()) &&
8031 "The number of lambda capture initializers should equal the number of "
8032 "fields within the closure type");
8033
Faisal Vali051e3a22017-02-16 04:12:21 +00008034 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8035 // Iterate through all the lambda's closure object's fields and initialize
8036 // them.
8037 auto *CaptureInitIt = E->capture_init_begin();
8038 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8039 bool Success = true;
8040 for (const auto *Field : ClosureClass->fields()) {
8041 assert(CaptureInitIt != E->capture_init_end());
8042 // Get the initializer for this field
8043 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00008044
Faisal Vali051e3a22017-02-16 04:12:21 +00008045 // If there is no initializer, either this is a VLA or an error has
8046 // occurred.
8047 if (!CurFieldInit)
8048 return Error(E);
8049
8050 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8051 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8052 if (!Info.keepEvaluatingAfterFailure())
8053 return false;
8054 Success = false;
8055 }
8056 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00008057 }
Faisal Vali051e3a22017-02-16 04:12:21 +00008058 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00008059}
8060
Richard Smithd62306a2011-11-10 06:34:14 +00008061static bool EvaluateRecord(const Expr *E, const LValue &This,
8062 APValue &Result, EvalInfo &Info) {
8063 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00008064 "can't evaluate expression as a record rvalue");
8065 return RecordExprEvaluator(Info, This, Result).Visit(E);
8066}
8067
8068//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008069// Temporary Evaluation
8070//
8071// Temporaries are represented in the AST as rvalues, but generally behave like
8072// lvalues. The full-object of which the temporary is a subobject is implicitly
8073// materialized so that a reference can bind to it.
8074//===----------------------------------------------------------------------===//
8075namespace {
8076class TemporaryExprEvaluator
8077 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8078public:
8079 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00008080 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00008081
8082 /// Visit an expression which constructs the value of this temporary.
8083 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008084 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8085 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00008086 }
8087
8088 bool VisitCastExpr(const CastExpr *E) {
8089 switch (E->getCastKind()) {
8090 default:
8091 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8092
8093 case CK_ConstructorConversion:
8094 return VisitConstructExpr(E->getSubExpr());
8095 }
8096 }
8097 bool VisitInitListExpr(const InitListExpr *E) {
8098 return VisitConstructExpr(E);
8099 }
8100 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8101 return VisitConstructExpr(E);
8102 }
8103 bool VisitCallExpr(const CallExpr *E) {
8104 return VisitConstructExpr(E);
8105 }
Richard Smith513955c2014-12-17 19:24:30 +00008106 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8107 return VisitConstructExpr(E);
8108 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008109 bool VisitLambdaExpr(const LambdaExpr *E) {
8110 return VisitConstructExpr(E);
8111 }
Richard Smith027bf112011-11-17 22:56:20 +00008112};
8113} // end anonymous namespace
8114
8115/// Evaluate an expression of record type as a temporary.
8116static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00008117 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00008118 return TemporaryExprEvaluator(Info, Result).Visit(E);
8119}
8120
8121//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008122// Vector Evaluation
8123//===----------------------------------------------------------------------===//
8124
8125namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008126 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008127 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00008128 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008129 public:
Mike Stump11289f42009-09-09 15:08:12 +00008130
Richard Smith2d406342011-10-22 21:10:00 +00008131 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8132 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00008133
Craig Topper9798b932015-09-29 04:30:05 +00008134 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008135 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8136 // FIXME: remove this APValue copy.
8137 Result = APValue(V.data(), V.size());
8138 return true;
8139 }
Richard Smith2e312c82012-03-03 22:46:17 +00008140 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00008141 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00008142 Result = V;
8143 return true;
8144 }
Richard Smithfddd3842011-12-30 21:15:51 +00008145 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00008146
Richard Smith2d406342011-10-22 21:10:00 +00008147 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00008148 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00008149 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00008150 bool VisitInitListExpr(const InitListExpr *E);
8151 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008152 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00008153 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00008154 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008155 };
8156} // end anonymous namespace
8157
8158static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008159 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00008160 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008161}
8162
George Burgess IV533ff002015-12-11 00:23:35 +00008163bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008164 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008165 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008166
Richard Smith161f09a2011-12-06 22:44:34 +00008167 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00008168 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008169
Eli Friedmanc757de22011-03-25 00:43:55 +00008170 switch (E->getCastKind()) {
8171 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00008172 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00008173 if (SETy->isIntegerType()) {
8174 APSInt IntResult;
8175 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00008176 return false;
8177 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008178 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00008179 APFloat FloatResult(0.0);
8180 if (!EvaluateFloat(SE, FloatResult, Info))
8181 return false;
8182 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008183 } else {
Richard Smith2d406342011-10-22 21:10:00 +00008184 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008185 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008186
8187 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00008188 SmallVector<APValue, 4> Elts(NElts, Val);
8189 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00008190 }
Eli Friedman803acb32011-12-22 03:51:45 +00008191 case CK_BitCast: {
8192 // Evaluate the operand into an APInt we can extract from.
8193 llvm::APInt SValInt;
8194 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8195 return false;
8196 // Extract the elements
8197 QualType EltTy = VTy->getElementType();
8198 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8199 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8200 SmallVector<APValue, 4> Elts;
8201 if (EltTy->isRealFloatingType()) {
8202 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00008203 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00008204 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00008205 FloatEltSize = 80;
8206 for (unsigned i = 0; i < NElts; i++) {
8207 llvm::APInt Elt;
8208 if (BigEndian)
8209 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8210 else
8211 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00008212 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00008213 }
8214 } else if (EltTy->isIntegerType()) {
8215 for (unsigned i = 0; i < NElts; i++) {
8216 llvm::APInt Elt;
8217 if (BigEndian)
8218 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8219 else
8220 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8221 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8222 }
8223 } else {
8224 return Error(E);
8225 }
8226 return Success(Elts, E);
8227 }
Eli Friedmanc757de22011-03-25 00:43:55 +00008228 default:
Richard Smith11562c52011-10-28 17:51:58 +00008229 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008230 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008231}
8232
Richard Smith2d406342011-10-22 21:10:00 +00008233bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008234VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008235 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008236 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00008237 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008238
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008239 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008240 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008241
Eli Friedmanb9c71292012-01-03 23:24:20 +00008242 // The number of initializers can be less than the number of
8243 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00008244 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00008245 // should be initialized with zeroes.
8246 unsigned CountInits = 0, CountElts = 0;
8247 while (CountElts < NumElements) {
8248 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00008249 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00008250 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00008251 APValue v;
8252 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8253 return Error(E);
8254 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00008255 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00008256 Elements.push_back(v.getVectorElt(j));
8257 CountElts += vlen;
8258 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008259 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008260 if (CountInits < NumInits) {
8261 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008262 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008263 } else // trailing integer zero.
8264 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8265 Elements.push_back(APValue(sInt));
8266 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008267 } else {
8268 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008269 if (CountInits < NumInits) {
8270 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008271 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008272 } else // trailing float zero.
8273 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8274 Elements.push_back(APValue(f));
8275 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00008276 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00008277 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008278 }
Richard Smith2d406342011-10-22 21:10:00 +00008279 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008280}
8281
Richard Smith2d406342011-10-22 21:10:00 +00008282bool
Richard Smithfddd3842011-12-30 21:15:51 +00008283VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008284 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00008285 QualType EltTy = VT->getElementType();
8286 APValue ZeroElement;
8287 if (EltTy->isIntegerType())
8288 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8289 else
8290 ZeroElement =
8291 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8292
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008293 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00008294 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008295}
8296
Richard Smith2d406342011-10-22 21:10:00 +00008297bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00008298 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008299 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008300}
8301
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008302//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00008303// Array Evaluation
8304//===----------------------------------------------------------------------===//
8305
8306namespace {
8307 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008308 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008309 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00008310 APValue &Result;
8311 public:
8312
Richard Smithd62306a2011-11-10 06:34:14 +00008313 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8314 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00008315
8316 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00008317 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00008318 Result = V;
8319 return true;
8320 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008321
Richard Smithfddd3842011-12-30 21:15:51 +00008322 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008323 const ConstantArrayType *CAT =
8324 Info.Ctx.getAsConstantArrayType(E->getType());
8325 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008326 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008327
8328 Result = APValue(APValue::UninitArray(), 0,
8329 CAT->getSize().getZExtValue());
8330 if (!Result.hasArrayFiller()) return true;
8331
Richard Smithfddd3842011-12-30 21:15:51 +00008332 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00008333 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008334 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00008335 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00008336 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00008337 }
8338
Richard Smith52a980a2015-08-28 02:43:42 +00008339 bool VisitCallExpr(const CallExpr *E) {
8340 return handleCallExpr(E, Result, &This);
8341 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008342 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00008343 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00008344 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00008345 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8346 const LValue &Subobject,
8347 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00008348 bool VisitStringLiteral(const StringLiteral *E) {
8349 expandStringLiteral(Info, E, Result);
8350 return true;
8351 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008352 };
8353} // end anonymous namespace
8354
Richard Smithd62306a2011-11-10 06:34:14 +00008355static bool EvaluateArray(const Expr *E, const LValue &This,
8356 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00008357 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00008358 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008359}
8360
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008361// Return true iff the given array filler may depend on the element index.
8362static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8363 // For now, just whitelist non-class value-initialization and initialization
8364 // lists comprised of them.
8365 if (isa<ImplicitValueInitExpr>(FillerExpr))
8366 return false;
8367 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8368 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8369 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8370 return true;
8371 }
8372 return false;
8373 }
8374 return true;
8375}
8376
Richard Smithf3e9e432011-11-07 09:22:26 +00008377bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8378 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8379 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008380 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008381
Richard Smithca2cfbf2011-12-22 01:07:19 +00008382 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8383 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00008384 if (E->isStringLiteralInit())
8385 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00008386
Richard Smith253c2a32012-01-27 01:14:48 +00008387 bool Success = true;
8388
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008389 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8390 "zero-initialized array shouldn't have any initialized elts");
8391 APValue Filler;
8392 if (Result.isArray() && Result.hasArrayFiller())
8393 Filler = Result.getArrayFiller();
8394
Richard Smith9543c5e2013-04-22 14:44:29 +00008395 unsigned NumEltsToInit = E->getNumInits();
8396 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00008397 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008398
8399 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008400 // array element.
8401 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008402 NumEltsToInit = NumElts;
8403
Nicola Zaghen3538b392018-05-15 13:30:56 +00008404 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8405 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008406
Richard Smith9543c5e2013-04-22 14:44:29 +00008407 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008408
8409 // If the array was previously zero-initialized, preserve the
8410 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008411 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008412 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8413 Result.getArrayInitializedElt(I) = Filler;
8414 if (Result.hasArrayFiller())
8415 Result.getArrayFiller() = Filler;
8416 }
8417
Richard Smithd62306a2011-11-10 06:34:14 +00008418 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008419 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008420 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8421 const Expr *Init =
8422 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008423 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008424 Info, Subobject, Init) ||
8425 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008426 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008427 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008428 return false;
8429 Success = false;
8430 }
Richard Smithd62306a2011-11-10 06:34:14 +00008431 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008432
Richard Smith9543c5e2013-04-22 14:44:29 +00008433 if (!Result.hasArrayFiller())
8434 return Success;
8435
8436 // If we get here, we have a trivial filler, which we can just evaluate
8437 // once and splat over the rest of the array elements.
8438 assert(FillerExpr && "no array filler for incomplete init list");
8439 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8440 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008441}
8442
Richard Smith410306b2016-12-12 02:53:20 +00008443bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8444 if (E->getCommonExpr() &&
8445 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8446 Info, E->getCommonExpr()->getSourceExpr()))
8447 return false;
8448
8449 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8450
8451 uint64_t Elements = CAT->getSize().getZExtValue();
8452 Result = APValue(APValue::UninitArray(), Elements, Elements);
8453
8454 LValue Subobject = This;
8455 Subobject.addArray(Info, E, CAT);
8456
8457 bool Success = true;
8458 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8459 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8460 Info, Subobject, E->getSubExpr()) ||
8461 !HandleLValueArrayAdjustment(Info, E, Subobject,
8462 CAT->getElementType(), 1)) {
8463 if (!Info.noteFailure())
8464 return false;
8465 Success = false;
8466 }
8467 }
8468
8469 return Success;
8470}
8471
Richard Smith027bf112011-11-17 22:56:20 +00008472bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008473 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8474}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008475
Richard Smith9543c5e2013-04-22 14:44:29 +00008476bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8477 const LValue &Subobject,
8478 APValue *Value,
8479 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008480 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008481
8482 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8483 unsigned N = CAT->getSize().getZExtValue();
8484
8485 // Preserve the array filler if we had prior zero-initialization.
8486 APValue Filler =
8487 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8488 : APValue();
8489
8490 *Value = APValue(APValue::UninitArray(), N, N);
8491
8492 if (HadZeroInit)
8493 for (unsigned I = 0; I != N; ++I)
8494 Value->getArrayInitializedElt(I) = Filler;
8495
8496 // Initialize the elements.
8497 LValue ArrayElt = Subobject;
8498 ArrayElt.addArray(Info, E, CAT);
8499 for (unsigned I = 0; I != N; ++I)
8500 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8501 CAT->getElementType()) ||
8502 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8503 CAT->getElementType(), 1))
8504 return false;
8505
8506 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008507 }
Richard Smith027bf112011-11-17 22:56:20 +00008508
Richard Smith9543c5e2013-04-22 14:44:29 +00008509 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008510 return Error(E);
8511
Richard Smithb8348f52016-05-12 22:16:28 +00008512 return RecordExprEvaluator(Info, Subobject, *Value)
8513 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008514}
8515
Richard Smithf3e9e432011-11-07 09:22:26 +00008516//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008517// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008518//
8519// As a GNU extension, we support casting pointers to sufficiently-wide integer
8520// types and back in constant folding. Integer values are thus represented
8521// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008522//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008523
8524namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008525class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008526 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008527 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008528public:
Richard Smith2e312c82012-03-03 22:46:17 +00008529 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008530 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008531
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008532 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008533 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008534 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008535 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008536 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008537 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008538 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008539 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008540 return true;
8541 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008542 bool Success(const llvm::APSInt &SI, const Expr *E) {
8543 return Success(SI, E, Result);
8544 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008545
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008546 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008547 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008548 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008549 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008550 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008551 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008552 Result.getInt().setIsUnsigned(
8553 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008554 return true;
8555 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008556 bool Success(const llvm::APInt &I, const Expr *E) {
8557 return Success(I, E, Result);
8558 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008559
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008560 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008561 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008562 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008563 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008564 return true;
8565 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008566 bool Success(uint64_t Value, const Expr *E) {
8567 return Success(Value, E, Result);
8568 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008569
Ken Dyckdbc01912011-03-11 02:13:43 +00008570 bool Success(CharUnits Size, const Expr *E) {
8571 return Success(Size.getQuantity(), E);
8572 }
8573
Richard Smith2e312c82012-03-03 22:46:17 +00008574 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00008575 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008576 Result = V;
8577 return true;
8578 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008579 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008580 }
Mike Stump11289f42009-09-09 15:08:12 +00008581
Richard Smithfddd3842011-12-30 21:15:51 +00008582 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008583
Peter Collingbournee9200682011-05-13 03:29:01 +00008584 //===--------------------------------------------------------------------===//
8585 // Visitor Methods
8586 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008587
Fangrui Song407659a2018-11-30 23:41:18 +00008588 bool VisitConstantExpr(const ConstantExpr *E);
8589
Chris Lattner7174bf32008-07-12 00:38:25 +00008590 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008591 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008592 }
8593 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008594 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008595 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008596
8597 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8598 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008599 if (CheckReferencedDecl(E, E->getDecl()))
8600 return true;
8601
8602 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008603 }
8604 bool VisitMemberExpr(const MemberExpr *E) {
8605 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008606 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008607 return true;
8608 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008609
8610 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008611 }
8612
Peter Collingbournee9200682011-05-13 03:29:01 +00008613 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008614 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008615 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008616 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008617 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008618
Peter Collingbournee9200682011-05-13 03:29:01 +00008619 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008620 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008621
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008622 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008623 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008624 }
Mike Stump11289f42009-09-09 15:08:12 +00008625
Ted Kremeneke65b0862012-03-06 20:05:56 +00008626 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8627 return Success(E->getValue(), E);
8628 }
Richard Smith410306b2016-12-12 02:53:20 +00008629
8630 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8631 if (Info.ArrayInitIndex == uint64_t(-1)) {
8632 // We were asked to evaluate this subexpression independent of the
8633 // enclosing ArrayInitLoopExpr. We can't do that.
8634 Info.FFDiag(E);
8635 return false;
8636 }
8637 return Success(Info.ArrayInitIndex, E);
8638 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008639
Richard Smith4ce706a2011-10-11 21:43:33 +00008640 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008641 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008642 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008643 }
8644
Douglas Gregor29c42f22012-02-24 07:38:34 +00008645 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8646 return Success(E->getValue(), E);
8647 }
8648
John Wiegley6242b6a2011-04-28 00:16:57 +00008649 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8650 return Success(E->getValue(), E);
8651 }
8652
John Wiegleyf9f65842011-04-25 06:54:41 +00008653 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8654 return Success(E->getValue(), E);
8655 }
8656
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008657 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008658 bool VisitUnaryImag(const UnaryOperator *E);
8659
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008660 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008661 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008662 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008663 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008664};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008665
8666class FixedPointExprEvaluator
8667 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8668 APValue &Result;
8669
8670 public:
8671 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8672 : ExprEvaluatorBaseTy(info), Result(result) {}
8673
Leonard Chandb01c3a2018-06-20 17:19:40 +00008674 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008675 return Success(
8676 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008677 }
8678
Leonard Chandb01c3a2018-06-20 17:19:40 +00008679 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008680 return Success(
8681 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008682 }
8683
8684 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008685 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008686 }
8687
Leonard Chand3f3e162019-01-18 21:04:25 +00008688 bool Success(const APFixedPoint &V, const Expr *E) {
8689 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8690 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8691 "Invalid evaluation result.");
8692 Result = APValue(V);
8693 return true;
8694 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008695
8696 //===--------------------------------------------------------------------===//
8697 // Visitor Methods
8698 //===--------------------------------------------------------------------===//
8699
8700 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8701 return Success(E->getValue(), E);
8702 }
8703
Leonard Chand3f3e162019-01-18 21:04:25 +00008704 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008705 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008706 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008707};
Chris Lattner05706e882008-07-11 18:11:29 +00008708} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008709
Richard Smith11562c52011-10-28 17:51:58 +00008710/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8711/// produce either the integer value or a pointer.
8712///
8713/// GCC has a heinous extension which folds casts between pointer types and
8714/// pointer-sized integral types. We support this by allowing the evaluation of
8715/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8716/// Some simple arithmetic on such values is supported (they are treated much
8717/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008718static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008719 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008720 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008721 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008722}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008723
Richard Smithf57d8cb2011-12-09 22:58:01 +00008724static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008725 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008726 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008727 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008728 if (!Val.isInt()) {
8729 // FIXME: It would be better to produce the diagnostic for casting
8730 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008731 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008732 return false;
8733 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008734 Result = Val.getInt();
8735 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008736}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008737
Eric Fiselier708afb52019-05-16 21:04:15 +00008738bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8739 APValue Evaluated = E->EvaluateInContext(
8740 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8741 return Success(Evaluated, E);
8742}
8743
Leonard Chand3f3e162019-01-18 21:04:25 +00008744static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8745 EvalInfo &Info) {
8746 if (E->getType()->isFixedPointType()) {
8747 APValue Val;
8748 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8749 return false;
8750 if (!Val.isFixedPoint())
8751 return false;
8752
8753 Result = Val.getFixedPoint();
8754 return true;
8755 }
8756 return false;
8757}
8758
8759static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8760 EvalInfo &Info) {
8761 if (E->getType()->isIntegerType()) {
8762 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8763 APSInt Val;
8764 if (!EvaluateInteger(E, Val, Info))
8765 return false;
8766 Result = APFixedPoint(Val, FXSema);
8767 return true;
8768 } else if (E->getType()->isFixedPointType()) {
8769 return EvaluateFixedPoint(E, Result, Info);
8770 }
8771 return false;
8772}
8773
Richard Smithf57d8cb2011-12-09 22:58:01 +00008774/// Check whether the given declaration can be directly converted to an integral
8775/// rvalue. If not, no diagnostic is produced; there are other things we can
8776/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008777bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008778 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008779 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008780 // Check for signedness/width mismatches between E type and ECD value.
8781 bool SameSign = (ECD->getInitVal().isSigned()
8782 == E->getType()->isSignedIntegerOrEnumerationType());
8783 bool SameWidth = (ECD->getInitVal().getBitWidth()
8784 == Info.Ctx.getIntWidth(E->getType()));
8785 if (SameSign && SameWidth)
8786 return Success(ECD->getInitVal(), E);
8787 else {
8788 // Get rid of mismatch (otherwise Success assertions will fail)
8789 // by computing a new value matching the type of E.
8790 llvm::APSInt Val = ECD->getInitVal();
8791 if (!SameSign)
8792 Val.setIsSigned(!ECD->getInitVal().isSigned());
8793 if (!SameWidth)
8794 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8795 return Success(Val, E);
8796 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008797 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008798 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008799}
8800
Richard Smith08b682b2018-05-23 21:18:00 +00008801/// Values returned by __builtin_classify_type, chosen to match the values
8802/// produced by GCC's builtin.
8803enum class GCCTypeClass {
8804 None = -1,
8805 Void = 0,
8806 Integer = 1,
8807 // GCC reserves 2 for character types, but instead classifies them as
8808 // integers.
8809 Enum = 3,
8810 Bool = 4,
8811 Pointer = 5,
8812 // GCC reserves 6 for references, but appears to never use it (because
8813 // expressions never have reference type, presumably).
8814 PointerToDataMember = 7,
8815 RealFloat = 8,
8816 Complex = 9,
8817 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8818 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8819 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8820 // uses 12 for that purpose, same as for a class or struct. Maybe it
8821 // internally implements a pointer to member as a struct? Who knows.
8822 PointerToMemberFunction = 12, // Not a bug, see above.
8823 ClassOrStruct = 12,
8824 Union = 13,
8825 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8826 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8827 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8828 // literals.
8829};
8830
Chris Lattner86ee2862008-10-06 06:40:35 +00008831/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8832/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008833static GCCTypeClass
8834EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8835 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008836
Richard Smith08b682b2018-05-23 21:18:00 +00008837 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008838 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8839
8840 switch (CanTy->getTypeClass()) {
8841#define TYPE(ID, BASE)
8842#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8843#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8844#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8845#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008846 case Type::Auto:
8847 case Type::DeducedTemplateSpecialization:
8848 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008849
8850 case Type::Builtin:
8851 switch (BT->getKind()) {
8852#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008853#define SIGNED_TYPE(ID, SINGLETON_ID) \
8854 case BuiltinType::ID: return GCCTypeClass::Integer;
8855#define FLOATING_TYPE(ID, SINGLETON_ID) \
8856 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8857#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8858 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008859#include "clang/AST/BuiltinTypes.def"
8860 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008861 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008862
8863 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008864 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008865
Richard Smith08b682b2018-05-23 21:18:00 +00008866 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008867 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008868 case BuiltinType::WChar_U:
8869 case BuiltinType::Char8:
8870 case BuiltinType::Char16:
8871 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008872 case BuiltinType::UShort:
8873 case BuiltinType::UInt:
8874 case BuiltinType::ULong:
8875 case BuiltinType::ULongLong:
8876 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008877 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008878
Leonard Chanf921d852018-06-04 16:07:52 +00008879 case BuiltinType::UShortAccum:
8880 case BuiltinType::UAccum:
8881 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008882 case BuiltinType::UShortFract:
8883 case BuiltinType::UFract:
8884 case BuiltinType::ULongFract:
8885 case BuiltinType::SatUShortAccum:
8886 case BuiltinType::SatUAccum:
8887 case BuiltinType::SatULongAccum:
8888 case BuiltinType::SatUShortFract:
8889 case BuiltinType::SatUFract:
8890 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008891 return GCCTypeClass::None;
8892
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008893 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008894
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008895 case BuiltinType::ObjCId:
8896 case BuiltinType::ObjCClass:
8897 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00008898#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8899 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00008900#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008901#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8902 case BuiltinType::Id:
8903#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008904 case BuiltinType::OCLSampler:
8905 case BuiltinType::OCLEvent:
8906 case BuiltinType::OCLClkEvent:
8907 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008908 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00008909#define SVE_TYPE(Name, Id, SingletonId) \
8910 case BuiltinType::Id:
8911#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008912 return GCCTypeClass::None;
8913
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008914 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00008915 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008916 };
Richard Smith08b682b2018-05-23 21:18:00 +00008917 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008918
8919 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00008920 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008921
8922 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008923 case Type::ConstantArray:
8924 case Type::VariableArray:
8925 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00008926 case Type::FunctionNoProto:
8927 case Type::FunctionProto:
8928 return GCCTypeClass::Pointer;
8929
8930 case Type::MemberPointer:
8931 return CanTy->isMemberDataPointerType()
8932 ? GCCTypeClass::PointerToDataMember
8933 : GCCTypeClass::PointerToMemberFunction;
8934
8935 case Type::Complex:
8936 return GCCTypeClass::Complex;
8937
8938 case Type::Record:
8939 return CanTy->isUnionType() ? GCCTypeClass::Union
8940 : GCCTypeClass::ClassOrStruct;
8941
8942 case Type::Atomic:
8943 // GCC classifies _Atomic T the same as T.
8944 return EvaluateBuiltinClassifyType(
8945 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008946
8947 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008948 case Type::Vector:
8949 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008950 case Type::ObjCObject:
8951 case Type::ObjCInterface:
8952 case Type::ObjCObjectPointer:
8953 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00008954 // GCC classifies vectors as None. We follow its lead and classify all
8955 // other types that don't fit into the regular classification the same way.
8956 return GCCTypeClass::None;
8957
8958 case Type::LValueReference:
8959 case Type::RValueReference:
8960 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008961 }
8962
Richard Smith08b682b2018-05-23 21:18:00 +00008963 llvm_unreachable("unexpected type class");
8964}
8965
8966/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8967/// as GCC.
8968static GCCTypeClass
8969EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8970 // If no argument was supplied, default to None. This isn't
8971 // ideal, however it is what gcc does.
8972 if (E->getNumArgs() == 0)
8973 return GCCTypeClass::None;
8974
8975 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8976 // being an ICE, but still folds it to a constant using the type of the first
8977 // argument.
8978 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00008979}
8980
Richard Smith5fab0c92011-12-28 19:48:30 +00008981/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00008982/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00008983///
Richard Smith31cfb312019-04-27 02:58:17 +00008984/// A pointer is only "constant" if it is null (or a pointer cast to integer)
8985/// or it points to the first character of a string literal.
8986static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8987 APValue::LValueBase Base = LV.getLValueBase();
8988 if (Base.isNull()) {
8989 // A null base is acceptable.
8990 return true;
8991 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8992 if (!isa<StringLiteral>(E))
8993 return false;
8994 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00008995 } else if (Base.is<TypeInfoLValue>()) {
8996 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8997 // evaluate to true.
8998 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00008999 } else {
9000 // Any other base is not constant enough for GCC.
9001 return false;
9002 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009003}
9004
9005/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9006/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00009007static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00009008 // This evaluation is not permitted to have side-effects, so evaluate it in
9009 // a speculative evaluation context.
9010 SpeculativeEvaluationRAII SpeculativeEval(Info);
9011
Richard Smith31cfb312019-04-27 02:58:17 +00009012 // Constant-folding is always enabled for the operand of __builtin_constant_p
9013 // (even when the enclosing evaluation context otherwise requires a strict
9014 // language-specific constant expression).
9015 FoldConstant Fold(Info, true);
9016
Richard Smith5fab0c92011-12-28 19:48:30 +00009017 QualType ArgType = Arg->getType();
9018
9019 // __builtin_constant_p always has one operand. The rules which gcc follows
9020 // are not precisely documented, but are as follows:
9021 //
9022 // - If the operand is of integral, floating, complex or enumeration type,
9023 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00009024 // - If the operand can be folded to a pointer to the first character
9025 // of a string literal (or such a pointer cast to an integral type)
9026 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00009027 //
9028 // Otherwise, it returns 0.
9029 //
9030 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00009031 // its support for this did not work prior to GCC 9 and is not yet well
9032 // understood.
9033 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9034 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9035 ArgType->isNullPtrType()) {
9036 APValue V;
9037 if (!::EvaluateAsRValue(Info, Arg, V)) {
9038 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00009039 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00009040 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009041
Richard Smith31cfb312019-04-27 02:58:17 +00009042 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00009043 if (V.getKind() == APValue::LValue)
9044 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00009045
9046 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00009047 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00009048 }
9049
9050 // Anything else isn't considered to be sufficiently constant.
9051 return false;
9052}
9053
John McCall95007602010-05-10 23:27:23 +00009054/// Retrieves the "underlying object type" of the given expression,
9055/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00009056static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00009057 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9058 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00009059 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00009060 } else if (const Expr *E = B.get<const Expr*>()) {
9061 if (isa<CompoundLiteralExpr>(E))
9062 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00009063 } else if (B.is<TypeInfoLValue>()) {
9064 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00009065 }
9066
9067 return QualType();
9068}
9069
George Burgess IV3a03fab2015-09-04 21:28:13 +00009070/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00009071/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00009072/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00009073/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9074///
9075/// Always returns an RValue with a pointer representation.
9076static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9077 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9078
9079 auto *NoParens = E->IgnoreParens();
9080 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00009081 if (Cast == nullptr)
9082 return NoParens;
9083
9084 // We only conservatively allow a few kinds of casts, because this code is
9085 // inherently a simple solution that seeks to support the common case.
9086 auto CastKind = Cast->getCastKind();
9087 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9088 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00009089 return NoParens;
9090
9091 auto *SubExpr = Cast->getSubExpr();
9092 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9093 return NoParens;
9094 return ignorePointerCastsAndParens(SubExpr);
9095}
9096
George Burgess IVa51c4072015-10-16 01:49:01 +00009097/// Checks to see if the given LValue's Designator is at the end of the LValue's
9098/// record layout. e.g.
9099/// struct { struct { int a, b; } fst, snd; } obj;
9100/// obj.fst // no
9101/// obj.snd // yes
9102/// obj.fst.a // no
9103/// obj.fst.b // no
9104/// obj.snd.a // no
9105/// obj.snd.b // yes
9106///
9107/// Please note: this function is specialized for how __builtin_object_size
9108/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00009109///
Richard Smith6f4f0f12017-10-20 22:56:25 +00009110/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9111/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00009112static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9113 assert(!LVal.Designator.Invalid);
9114
George Burgess IV4168d752016-06-27 19:40:41 +00009115 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9116 const RecordDecl *Parent = FD->getParent();
9117 Invalid = Parent->isInvalidDecl();
9118 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00009119 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00009120 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00009121 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9122 };
9123
9124 auto &Base = LVal.getLValueBase();
9125 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9126 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009127 bool Invalid;
9128 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9129 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009130 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009131 for (auto *FD : IFD->chain()) {
9132 bool Invalid;
9133 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9134 return Invalid;
9135 }
George Burgess IVa51c4072015-10-16 01:49:01 +00009136 }
9137 }
9138
George Burgess IVe3763372016-12-22 02:50:20 +00009139 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00009140 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00009141 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00009142 // If we don't know the array bound, conservatively assume we're looking at
9143 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00009144 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00009145 if (BaseType->isIncompleteArrayType())
9146 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9147 else
9148 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00009149 }
9150
9151 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9152 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00009153 if (BaseType->isArrayType()) {
9154 // Because __builtin_object_size treats arrays as objects, we can ignore
9155 // the index iff this is the last array in the Designator.
9156 if (I + 1 == E)
9157 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00009158 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00009159 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009160 if (Index + 1 != CAT->getSize())
9161 return false;
9162 BaseType = CAT->getElementType();
9163 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00009164 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009165 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009166 if (Index != 1)
9167 return false;
9168 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00009169 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00009170 bool Invalid;
9171 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9172 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009173 BaseType = FD->getType();
9174 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00009175 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00009176 return false;
9177 }
9178 }
9179 return true;
9180}
9181
George Burgess IVe3763372016-12-22 02:50:20 +00009182/// Tests to see if the LValue has a user-specified designator (that isn't
9183/// necessarily valid). Note that this always returns 'true' if the LValue has
9184/// an unsized array as its first designator entry, because there's currently no
9185/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00009186static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00009187 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00009188 return false;
9189
George Burgess IVe3763372016-12-22 02:50:20 +00009190 if (!LVal.Designator.Entries.empty())
9191 return LVal.Designator.isMostDerivedAnUnsizedArray();
9192
George Burgess IVa51c4072015-10-16 01:49:01 +00009193 if (!LVal.InvalidBase)
9194 return true;
9195
George Burgess IVe3763372016-12-22 02:50:20 +00009196 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9197 // the LValueBase.
9198 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9199 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00009200}
9201
George Burgess IVe3763372016-12-22 02:50:20 +00009202/// Attempts to detect a user writing into a piece of memory that's impossible
9203/// to figure out the size of by just using types.
9204static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9205 const SubobjectDesignator &Designator = LVal.Designator;
9206 // Notes:
9207 // - Users can only write off of the end when we have an invalid base. Invalid
9208 // bases imply we don't know where the memory came from.
9209 // - We used to be a bit more aggressive here; we'd only be conservative if
9210 // the array at the end was flexible, or if it had 0 or 1 elements. This
9211 // broke some common standard library extensions (PR30346), but was
9212 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9213 // with some sort of whitelist. OTOH, it seems that GCC is always
9214 // conservative with the last element in structs (if it's an array), so our
9215 // current behavior is more compatible than a whitelisting approach would
9216 // be.
9217 return LVal.InvalidBase &&
9218 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9219 Designator.MostDerivedIsArrayElement &&
9220 isDesignatorAtObjectEnd(Ctx, LVal);
9221}
9222
9223/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9224/// Fails if the conversion would cause loss of precision.
9225static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9226 CharUnits &Result) {
9227 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9228 if (Int.ugt(CharUnitsMax))
9229 return false;
9230 Result = CharUnits::fromQuantity(Int.getZExtValue());
9231 return true;
9232}
9233
9234/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9235/// determine how many bytes exist from the beginning of the object to either
9236/// the end of the current subobject, or the end of the object itself, depending
9237/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00009238///
George Burgess IVe3763372016-12-22 02:50:20 +00009239/// If this returns false, the value of Result is undefined.
9240static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9241 unsigned Type, const LValue &LVal,
9242 CharUnits &EndOffset) {
9243 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009244
George Burgess IV7fb7e362017-01-03 23:35:19 +00009245 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9246 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9247 return false;
9248 return HandleSizeof(Info, ExprLoc, Ty, Result);
9249 };
9250
George Burgess IVe3763372016-12-22 02:50:20 +00009251 // We want to evaluate the size of the entire object. This is a valid fallback
9252 // for when Type=1 and the designator is invalid, because we're asked for an
9253 // upper-bound.
9254 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9255 // Type=3 wants a lower bound, so we can't fall back to this.
9256 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00009257 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00009258
9259 llvm::APInt APEndOffset;
9260 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9261 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9262 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9263
9264 if (LVal.InvalidBase)
9265 return false;
9266
9267 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00009268 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00009269 }
9270
George Burgess IVe3763372016-12-22 02:50:20 +00009271 // We want to evaluate the size of a subobject.
9272 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009273
9274 // The following is a moderately common idiom in C:
9275 //
9276 // struct Foo { int a; char c[1]; };
9277 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9278 // strcpy(&F->c[0], Bar);
9279 //
George Burgess IVe3763372016-12-22 02:50:20 +00009280 // In order to not break too much legacy code, we need to support it.
9281 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9282 // If we can resolve this to an alloc_size call, we can hand that back,
9283 // because we know for certain how many bytes there are to write to.
9284 llvm::APInt APEndOffset;
9285 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9286 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9287 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9288
9289 // If we cannot determine the size of the initial allocation, then we can't
9290 // given an accurate upper-bound. However, we are still able to give
9291 // conservative lower-bounds for Type=3.
9292 if (Type == 1)
9293 return false;
9294 }
9295
9296 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00009297 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009298 return false;
9299
George Burgess IVe3763372016-12-22 02:50:20 +00009300 // According to the GCC documentation, we want the size of the subobject
9301 // denoted by the pointer. But that's not quite right -- what we actually
9302 // want is the size of the immediately-enclosing array, if there is one.
9303 int64_t ElemsRemaining;
9304 if (Designator.MostDerivedIsArrayElement &&
9305 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9306 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009307 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00009308 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9309 } else {
9310 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9311 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009312
George Burgess IVe3763372016-12-22 02:50:20 +00009313 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9314 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009315}
9316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009317/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00009318/// returns true and stores the result in @p Size.
9319///
9320/// If @p WasError is non-null, this will report whether the failure to evaluate
9321/// is to be treated as an Error in IntExprEvaluator.
9322static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9323 EvalInfo &Info, uint64_t &Size) {
9324 // Determine the denoted object.
9325 LValue LVal;
9326 {
9327 // The operand of __builtin_object_size is never evaluated for side-effects.
9328 // If there are any, but we can determine the pointed-to object anyway, then
9329 // ignore the side-effects.
9330 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00009331 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00009332
9333 if (E->isGLValue()) {
9334 // It's possible for us to be given GLValues if we're called via
9335 // Expr::tryEvaluateObjectSize.
9336 APValue RVal;
9337 if (!EvaluateAsRValue(Info, E, RVal))
9338 return false;
9339 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00009340 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9341 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00009342 return false;
9343 }
9344
9345 // If we point to before the start of the object, there are no accessible
9346 // bytes.
9347 if (LVal.getLValueOffset().isNegative()) {
9348 Size = 0;
9349 return true;
9350 }
9351
9352 CharUnits EndOffset;
9353 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9354 return false;
9355
9356 // If we've fallen outside of the end offset, just pretend there's nothing to
9357 // write to/read from.
9358 if (EndOffset <= LVal.getLValueOffset())
9359 Size = 0;
9360 else
9361 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9362 return true;
John McCall95007602010-05-10 23:27:23 +00009363}
9364
Fangrui Song407659a2018-11-30 23:41:18 +00009365bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9366 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +00009367 if (E->getResultAPValueKind() != APValue::None)
9368 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +00009369 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9370}
9371
Peter Collingbournee9200682011-05-13 03:29:01 +00009372bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00009373 if (unsigned BuiltinOp = E->getBuiltinCallee())
9374 return VisitBuiltinCallExpr(E, BuiltinOp);
9375
9376 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9377}
9378
9379bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9380 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00009381 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009382 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00009383 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00009384
Erik Pilkington9c3b5882019-01-30 20:34:53 +00009385 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00009386 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00009387 // The type was checked when we built the expression.
9388 unsigned Type =
9389 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9390 assert(Type <= 3 && "unexpected type");
9391
George Burgess IVe3763372016-12-22 02:50:20 +00009392 uint64_t Size;
9393 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9394 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00009395
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009396 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00009397 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00009398
Richard Smith01ade172012-05-23 04:13:20 +00009399 // Expression had no side effects, but we couldn't statically determine the
9400 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009401 switch (Info.EvalMode) {
9402 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009403 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009404 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009405 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009406 return Error(E);
9407 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009408 // Reduce it to a constant now.
9409 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009410 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009411
9412 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009413 }
9414
Tim Northover314fbfa2018-11-02 13:14:11 +00009415 case Builtin::BI__builtin_os_log_format_buffer_size: {
9416 analyze_os_log::OSLogBufferLayout Layout;
9417 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9418 return Success(Layout.size().getQuantity(), E);
9419 }
9420
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009421 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009422 case Builtin::BI__builtin_bswap32:
9423 case Builtin::BI__builtin_bswap64: {
9424 APSInt Val;
9425 if (!EvaluateInteger(E->getArg(0), Val, Info))
9426 return false;
9427
9428 return Success(Val.byteSwap(), E);
9429 }
9430
Richard Smith8889a3d2013-06-13 06:26:32 +00009431 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009432 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009433
Craig Topperf95a6d92018-08-08 22:31:12 +00009434 case Builtin::BI__builtin_clrsb:
9435 case Builtin::BI__builtin_clrsbl:
9436 case Builtin::BI__builtin_clrsbll: {
9437 APSInt Val;
9438 if (!EvaluateInteger(E->getArg(0), Val, Info))
9439 return false;
9440
9441 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9442 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009443
Richard Smith80b3c8e2013-06-13 05:04:16 +00009444 case Builtin::BI__builtin_clz:
9445 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009446 case Builtin::BI__builtin_clzll:
9447 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009448 APSInt Val;
9449 if (!EvaluateInteger(E->getArg(0), Val, Info))
9450 return false;
9451 if (!Val)
9452 return Error(E);
9453
9454 return Success(Val.countLeadingZeros(), E);
9455 }
9456
Fangrui Song407659a2018-11-30 23:41:18 +00009457 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009458 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009459 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009460 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009461 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009462 // Outside a constant context, eagerly evaluate to false in the presence
9463 // of side-effects in order to avoid -Wunsequenced false-positives in
9464 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009465 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009466 }
David Blaikie639b3d12019-05-03 18:11:31 +00009467 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9468 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009469 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009470
Eric Fiselieradd16a82019-04-24 02:23:30 +00009471 case Builtin::BI__builtin_is_constant_evaluated:
9472 return Success(Info.InConstantContext, E);
9473
Richard Smith80b3c8e2013-06-13 05:04:16 +00009474 case Builtin::BI__builtin_ctz:
9475 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009476 case Builtin::BI__builtin_ctzll:
9477 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009478 APSInt Val;
9479 if (!EvaluateInteger(E->getArg(0), Val, Info))
9480 return false;
9481 if (!Val)
9482 return Error(E);
9483
9484 return Success(Val.countTrailingZeros(), E);
9485 }
9486
Richard Smith8889a3d2013-06-13 06:26:32 +00009487 case Builtin::BI__builtin_eh_return_data_regno: {
9488 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9489 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9490 return Success(Operand, E);
9491 }
9492
9493 case Builtin::BI__builtin_expect:
9494 return Visit(E->getArg(0));
9495
9496 case Builtin::BI__builtin_ffs:
9497 case Builtin::BI__builtin_ffsl:
9498 case Builtin::BI__builtin_ffsll: {
9499 APSInt Val;
9500 if (!EvaluateInteger(E->getArg(0), Val, Info))
9501 return false;
9502
9503 unsigned N = Val.countTrailingZeros();
9504 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9505 }
9506
9507 case Builtin::BI__builtin_fpclassify: {
9508 APFloat Val(0.0);
9509 if (!EvaluateFloat(E->getArg(5), Val, Info))
9510 return false;
9511 unsigned Arg;
9512 switch (Val.getCategory()) {
9513 case APFloat::fcNaN: Arg = 0; break;
9514 case APFloat::fcInfinity: Arg = 1; break;
9515 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9516 case APFloat::fcZero: Arg = 4; break;
9517 }
9518 return Visit(E->getArg(Arg));
9519 }
9520
9521 case Builtin::BI__builtin_isinf_sign: {
9522 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009523 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009524 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9525 }
9526
Richard Smithea3019d2013-10-15 19:07:14 +00009527 case Builtin::BI__builtin_isinf: {
9528 APFloat Val(0.0);
9529 return EvaluateFloat(E->getArg(0), Val, Info) &&
9530 Success(Val.isInfinity() ? 1 : 0, E);
9531 }
9532
9533 case Builtin::BI__builtin_isfinite: {
9534 APFloat Val(0.0);
9535 return EvaluateFloat(E->getArg(0), Val, Info) &&
9536 Success(Val.isFinite() ? 1 : 0, E);
9537 }
9538
9539 case Builtin::BI__builtin_isnan: {
9540 APFloat Val(0.0);
9541 return EvaluateFloat(E->getArg(0), Val, Info) &&
9542 Success(Val.isNaN() ? 1 : 0, E);
9543 }
9544
9545 case Builtin::BI__builtin_isnormal: {
9546 APFloat Val(0.0);
9547 return EvaluateFloat(E->getArg(0), Val, Info) &&
9548 Success(Val.isNormal() ? 1 : 0, E);
9549 }
9550
Richard Smith8889a3d2013-06-13 06:26:32 +00009551 case Builtin::BI__builtin_parity:
9552 case Builtin::BI__builtin_parityl:
9553 case Builtin::BI__builtin_parityll: {
9554 APSInt Val;
9555 if (!EvaluateInteger(E->getArg(0), Val, Info))
9556 return false;
9557
9558 return Success(Val.countPopulation() % 2, E);
9559 }
9560
Richard Smith80b3c8e2013-06-13 05:04:16 +00009561 case Builtin::BI__builtin_popcount:
9562 case Builtin::BI__builtin_popcountl:
9563 case Builtin::BI__builtin_popcountll: {
9564 APSInt Val;
9565 if (!EvaluateInteger(E->getArg(0), Val, Info))
9566 return false;
9567
9568 return Success(Val.countPopulation(), E);
9569 }
9570
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009571 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009572 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009573 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009574 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009575 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009576 << /*isConstexpr*/0 << /*isConstructor*/0
9577 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009578 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009579 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009580 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009581 case Builtin::BI__builtin_strlen:
9582 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009583 // As an extension, we support __builtin_strlen() as a constant expression,
9584 // and support folding strlen() to a constant.
9585 LValue String;
9586 if (!EvaluatePointer(E->getArg(0), String, Info))
9587 return false;
9588
Richard Smith8110c9d2016-11-29 19:45:17 +00009589 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9590
Richard Smithe6c19f22013-11-15 02:10:04 +00009591 // Fast path: if it's a string literal, search the string value.
9592 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9593 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009594 // The string literal may have embedded null characters. Find the first
9595 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009596 StringRef Str = S->getBytes();
9597 int64_t Off = String.Offset.getQuantity();
9598 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009599 S->getCharByteWidth() == 1 &&
9600 // FIXME: Add fast-path for wchar_t too.
9601 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009602 Str = Str.substr(Off);
9603
9604 StringRef::size_type Pos = Str.find(0);
9605 if (Pos != StringRef::npos)
9606 Str = Str.substr(0, Pos);
9607
9608 return Success(Str.size(), E);
9609 }
9610
9611 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009612 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009613
9614 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009615 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9616 APValue Char;
9617 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9618 !Char.isInt())
9619 return false;
9620 if (!Char.getInt())
9621 return Success(Strlen, E);
9622 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9623 return false;
9624 }
9625 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009626
Richard Smithe151bab2016-11-11 23:43:35 +00009627 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009628 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009629 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009630 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009631 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009632 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009633 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009634 // A call to strlen is not a constant expression.
9635 if (Info.getLangOpts().CPlusPlus11)
9636 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9637 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009638 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009639 else
9640 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009641 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009642 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009643 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009644 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009645 case Builtin::BI__builtin_wcsncmp:
9646 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009647 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009648 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009649 LValue String1, String2;
9650 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9651 !EvaluatePointer(E->getArg(1), String2, Info))
9652 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009653
Richard Smithe151bab2016-11-11 23:43:35 +00009654 uint64_t MaxLength = uint64_t(-1);
9655 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009656 BuiltinOp != Builtin::BIwcscmp &&
9657 BuiltinOp != Builtin::BI__builtin_strcmp &&
9658 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009659 APSInt N;
9660 if (!EvaluateInteger(E->getArg(2), N, Info))
9661 return false;
9662 MaxLength = N.getExtValue();
9663 }
Hubert Tong147b7432018-12-12 16:53:43 +00009664
9665 // Empty substrings compare equal by definition.
9666 if (MaxLength == 0u)
9667 return Success(0, E);
9668
9669 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9670 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9671 String1.Designator.Invalid || String2.Designator.Invalid)
9672 return false;
9673
9674 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9675 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9676
9677 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009678 BuiltinOp == Builtin::BIbcmp ||
9679 BuiltinOp == Builtin::BI__builtin_memcmp ||
9680 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009681
9682 assert(IsRawByte ||
9683 (Info.Ctx.hasSameUnqualifiedType(
9684 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9685 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9686
9687 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9688 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9689 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9690 Char1.isInt() && Char2.isInt();
9691 };
9692 const auto &AdvanceElems = [&] {
9693 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9694 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9695 };
9696
9697 if (IsRawByte) {
9698 uint64_t BytesRemaining = MaxLength;
9699 // Pointers to const void may point to objects of incomplete type.
9700 if (CharTy1->isIncompleteType()) {
9701 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9702 return false;
9703 }
9704 if (CharTy2->isIncompleteType()) {
9705 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9706 return false;
9707 }
9708 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9709 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9710 // Give up on comparing between elements with disparate widths.
9711 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9712 return false;
9713 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9714 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9715 "following loop considers at least one element");
9716 while (true) {
9717 APValue Char1, Char2;
9718 if (!ReadCurElems(Char1, Char2))
9719 return false;
9720 // We have compatible in-memory widths, but a possible type and
9721 // (for `bool`) internal representation mismatch.
9722 // Assuming two's complement representation, including 0 for `false` and
9723 // 1 for `true`, we can check an appropriate number of elements for
9724 // equality even if they are not byte-sized.
9725 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9726 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9727 if (Char1InMem.ne(Char2InMem)) {
9728 // If the elements are byte-sized, then we can produce a three-way
9729 // comparison result in a straightforward manner.
9730 if (BytesPerElement == 1u) {
9731 // memcmp always compares unsigned chars.
9732 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9733 }
9734 // The result is byte-order sensitive, and we have multibyte elements.
9735 // FIXME: We can compare the remaining bytes in the correct order.
9736 return false;
9737 }
9738 if (!AdvanceElems())
9739 return false;
9740 if (BytesRemaining <= BytesPerElement)
9741 break;
9742 BytesRemaining -= BytesPerElement;
9743 }
9744 // Enough elements are equal to account for the memcmp limit.
9745 return Success(0, E);
9746 }
9747
Clement Courbet8c3343d2019-02-14 12:00:34 +00009748 bool StopAtNull =
9749 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9750 BuiltinOp != Builtin::BIwmemcmp &&
9751 BuiltinOp != Builtin::BI__builtin_memcmp &&
9752 BuiltinOp != Builtin::BI__builtin_bcmp &&
9753 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009754 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9755 BuiltinOp == Builtin::BIwcsncmp ||
9756 BuiltinOp == Builtin::BIwmemcmp ||
9757 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9758 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9759 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009760
Richard Smithe151bab2016-11-11 23:43:35 +00009761 for (; MaxLength; --MaxLength) {
9762 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009763 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009764 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009765 if (Char1.getInt() != Char2.getInt()) {
9766 if (IsWide) // wmemcmp compares with wchar_t signedness.
9767 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9768 // memcmp always compares unsigned chars.
9769 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9770 }
Richard Smithe151bab2016-11-11 23:43:35 +00009771 if (StopAtNull && !Char1.getInt())
9772 return Success(0, E);
9773 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009774 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009775 return false;
9776 }
9777 // We hit the strncmp / memcmp limit.
9778 return Success(0, E);
9779 }
9780
Richard Smith01ba47d2012-04-13 00:45:38 +00009781 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009782 case Builtin::BI__atomic_is_lock_free:
9783 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009784 APSInt SizeVal;
9785 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9786 return false;
9787
9788 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9789 // of two less than the maximum inline atomic width, we know it is
9790 // lock-free. If the size isn't a power of two, or greater than the
9791 // maximum alignment where we promote atomics, we know it is not lock-free
9792 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9793 // the answer can only be determined at runtime; for example, 16-byte
9794 // atomics have lock-free implementations on some, but not all,
9795 // x86-64 processors.
9796
9797 // Check power-of-two.
9798 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009799 if (Size.isPowerOfTwo()) {
9800 // Check against inlining width.
9801 unsigned InlineWidthBits =
9802 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9803 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9804 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9805 Size == CharUnits::One() ||
9806 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9807 Expr::NPC_NeverValueDependent))
9808 // OK, we will inline appropriately-aligned operations of this size,
9809 // and _Atomic(T) is appropriately-aligned.
9810 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009811
Richard Smith01ba47d2012-04-13 00:45:38 +00009812 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9813 castAs<PointerType>()->getPointeeType();
9814 if (!PointeeType->isIncompleteType() &&
9815 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9816 // OK, we will inline operations on this object.
9817 return Success(1, E);
9818 }
9819 }
9820 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009821
Richard Smith01ba47d2012-04-13 00:45:38 +00009822 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9823 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009824 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009825 case Builtin::BIomp_is_initial_device:
9826 // We can decide statically which value the runtime would return if called.
9827 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009828 case Builtin::BI__builtin_add_overflow:
9829 case Builtin::BI__builtin_sub_overflow:
9830 case Builtin::BI__builtin_mul_overflow:
9831 case Builtin::BI__builtin_sadd_overflow:
9832 case Builtin::BI__builtin_uadd_overflow:
9833 case Builtin::BI__builtin_uaddl_overflow:
9834 case Builtin::BI__builtin_uaddll_overflow:
9835 case Builtin::BI__builtin_usub_overflow:
9836 case Builtin::BI__builtin_usubl_overflow:
9837 case Builtin::BI__builtin_usubll_overflow:
9838 case Builtin::BI__builtin_umul_overflow:
9839 case Builtin::BI__builtin_umull_overflow:
9840 case Builtin::BI__builtin_umulll_overflow:
9841 case Builtin::BI__builtin_saddl_overflow:
9842 case Builtin::BI__builtin_saddll_overflow:
9843 case Builtin::BI__builtin_ssub_overflow:
9844 case Builtin::BI__builtin_ssubl_overflow:
9845 case Builtin::BI__builtin_ssubll_overflow:
9846 case Builtin::BI__builtin_smul_overflow:
9847 case Builtin::BI__builtin_smull_overflow:
9848 case Builtin::BI__builtin_smulll_overflow: {
9849 LValue ResultLValue;
9850 APSInt LHS, RHS;
9851
9852 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9853 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9854 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9855 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9856 return false;
9857
9858 APSInt Result;
9859 bool DidOverflow = false;
9860
9861 // If the types don't have to match, enlarge all 3 to the largest of them.
9862 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9863 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9864 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9865 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9866 ResultType->isSignedIntegerOrEnumerationType();
9867 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9868 ResultType->isSignedIntegerOrEnumerationType();
9869 uint64_t LHSSize = LHS.getBitWidth();
9870 uint64_t RHSSize = RHS.getBitWidth();
9871 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9872 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9873
9874 // Add an additional bit if the signedness isn't uniformly agreed to. We
9875 // could do this ONLY if there is a signed and an unsigned that both have
9876 // MaxBits, but the code to check that is pretty nasty. The issue will be
9877 // caught in the shrink-to-result later anyway.
9878 if (IsSigned && !AllSigned)
9879 ++MaxBits;
9880
Erich Keanefc3dfd32019-05-30 21:35:32 +00009881 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9882 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +00009883 Result = APSInt(MaxBits, !IsSigned);
9884 }
9885
9886 // Find largest int.
9887 switch (BuiltinOp) {
9888 default:
9889 llvm_unreachable("Invalid value for BuiltinOp");
9890 case Builtin::BI__builtin_add_overflow:
9891 case Builtin::BI__builtin_sadd_overflow:
9892 case Builtin::BI__builtin_saddl_overflow:
9893 case Builtin::BI__builtin_saddll_overflow:
9894 case Builtin::BI__builtin_uadd_overflow:
9895 case Builtin::BI__builtin_uaddl_overflow:
9896 case Builtin::BI__builtin_uaddll_overflow:
9897 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9898 : LHS.uadd_ov(RHS, DidOverflow);
9899 break;
9900 case Builtin::BI__builtin_sub_overflow:
9901 case Builtin::BI__builtin_ssub_overflow:
9902 case Builtin::BI__builtin_ssubl_overflow:
9903 case Builtin::BI__builtin_ssubll_overflow:
9904 case Builtin::BI__builtin_usub_overflow:
9905 case Builtin::BI__builtin_usubl_overflow:
9906 case Builtin::BI__builtin_usubll_overflow:
9907 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9908 : LHS.usub_ov(RHS, DidOverflow);
9909 break;
9910 case Builtin::BI__builtin_mul_overflow:
9911 case Builtin::BI__builtin_smul_overflow:
9912 case Builtin::BI__builtin_smull_overflow:
9913 case Builtin::BI__builtin_smulll_overflow:
9914 case Builtin::BI__builtin_umul_overflow:
9915 case Builtin::BI__builtin_umull_overflow:
9916 case Builtin::BI__builtin_umulll_overflow:
9917 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9918 : LHS.umul_ov(RHS, DidOverflow);
9919 break;
9920 }
9921
9922 // In the case where multiple sizes are allowed, truncate and see if
9923 // the values are the same.
9924 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9925 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9926 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9927 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9928 // since it will give us the behavior of a TruncOrSelf in the case where
9929 // its parameter <= its size. We previously set Result to be at least the
9930 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9931 // will work exactly like TruncOrSelf.
9932 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9933 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9934
9935 if (!APSInt::isSameValue(Temp, Result))
9936 DidOverflow = true;
9937 Result = Temp;
9938 }
9939
9940 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00009941 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9942 return false;
Erich Keane00958272018-06-13 20:43:27 +00009943 return Success(DidOverflow, E);
9944 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009945 }
Chris Lattner7174bf32008-07-12 00:38:25 +00009946}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009948/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00009949/// object referred to by the lvalue.
9950static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9951 const LValue &LV) {
9952 // A null pointer can be viewed as being "past the end" but we don't
9953 // choose to look at it that way here.
9954 if (!LV.getLValueBase())
9955 return false;
9956
9957 // If the designator is valid and refers to a subobject, we're not pointing
9958 // past the end.
9959 if (!LV.getLValueDesignator().Invalid &&
9960 !LV.getLValueDesignator().isOnePastTheEnd())
9961 return false;
9962
David Majnemerc378ca52015-08-29 08:32:55 +00009963 // A pointer to an incomplete type might be past-the-end if the type's size is
9964 // zero. We cannot tell because the type is incomplete.
9965 QualType Ty = getType(LV.getLValueBase());
9966 if (Ty->isIncompleteType())
9967 return true;
9968
Richard Smithd20f1e62014-10-21 23:01:04 +00009969 // We're a past-the-end pointer if we point to the byte after the object,
9970 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00009971 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00009972 return LV.getLValueOffset() == Size;
9973}
9974
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009975namespace {
Richard Smith11562c52011-10-28 17:51:58 +00009976
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009977/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009978///
9979/// We use a data recursive algorithm for binary operators so that we are able
9980/// to handle extreme cases of chained binary operators without causing stack
9981/// overflow.
9982class DataRecursiveIntBinOpEvaluator {
9983 struct EvalResult {
9984 APValue Val;
9985 bool Failed;
9986
9987 EvalResult() : Failed(false) { }
9988
9989 void swap(EvalResult &RHS) {
9990 Val.swap(RHS.Val);
9991 Failed = RHS.Failed;
9992 RHS.Failed = false;
9993 }
9994 };
9995
9996 struct Job {
9997 const Expr *E;
9998 EvalResult LHSResult; // meaningful only for binary operator expression.
9999 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000010000
David Blaikie73726062015-08-12 23:09:24 +000010001 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000010002 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000010003
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010004 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000010005 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010006 }
George Burgess IV8c892b52016-05-25 22:31:54 +000010007
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010008 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000010009 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010010 };
10011
10012 SmallVector<Job, 16> Queue;
10013
10014 IntExprEvaluator &IntEval;
10015 EvalInfo &Info;
10016 APValue &FinalResult;
10017
10018public:
10019 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10020 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010022 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010023 /// data recursively.
10024 /// We handle binary operators that are comma, logical, or that have operands
10025 /// with integral or enumeration type.
10026 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010027 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10028 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000010029 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010030 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000010031 }
10032
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010033 bool Traverse(const BinaryOperator *E) {
10034 enqueue(E);
10035 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000010036 while (!Queue.empty())
10037 process(PrevResult);
10038
10039 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010040
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010041 FinalResult.swap(PrevResult.Val);
10042 return true;
10043 }
10044
10045private:
10046 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10047 return IntEval.Success(Value, E, Result);
10048 }
10049 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10050 return IntEval.Success(Value, E, Result);
10051 }
10052 bool Error(const Expr *E) {
10053 return IntEval.Error(E);
10054 }
10055 bool Error(const Expr *E, diag::kind D) {
10056 return IntEval.Error(E, D);
10057 }
10058
10059 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10060 return Info.CCEDiag(E, D);
10061 }
10062
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010063 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010064 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010065 bool &SuppressRHSDiags);
10066
10067 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10068 const BinaryOperator *E, APValue &Result);
10069
10070 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10071 Result.Failed = !Evaluate(Result.Val, Info, E);
10072 if (Result.Failed)
10073 Result.Val = APValue();
10074 }
10075
Richard Trieuba4d0872012-03-21 23:30:30 +000010076 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010077
10078 void enqueue(const Expr *E) {
10079 E = E->IgnoreParens();
10080 Queue.resize(Queue.size()+1);
10081 Queue.back().E = E;
10082 Queue.back().Kind = Job::AnyExprKind;
10083 }
10084};
10085
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010086}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010087
10088bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010089 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010090 bool &SuppressRHSDiags) {
10091 if (E->getOpcode() == BO_Comma) {
10092 // Ignore LHS but note if we could not evaluate it.
10093 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000010094 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010095 return true;
10096 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010097
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010098 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010099 bool LHSAsBool;
10100 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010101 // We were able to evaluate the LHS, see if we can get away with not
10102 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000010103 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10104 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010105 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010106 }
10107 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010108 LHSResult.Failed = true;
10109
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010110 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000010111 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000010112 if (!Info.noteSideEffect())
10113 return false;
10114
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010115 // We can't evaluate the LHS; however, sometimes the result
10116 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10117 // Don't ignore RHS and suppress diagnostics from this arm.
10118 SuppressRHSDiags = true;
10119 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010120
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010121 return true;
10122 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010123
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010124 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10125 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000010126
George Burgess IVa145e252016-05-25 22:38:36 +000010127 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010128 return false; // Ignore RHS;
10129
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010130 return true;
10131}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010132
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000010133static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10134 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000010135 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10136 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10137 // offsets.
10138 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10139 CharUnits &Offset = LVal.getLValueOffset();
10140 uint64_t Offset64 = Offset.getQuantity();
10141 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10142 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10143 : Offset64 + Index64);
10144}
10145
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010146bool DataRecursiveIntBinOpEvaluator::
10147 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10148 const BinaryOperator *E, APValue &Result) {
10149 if (E->getOpcode() == BO_Comma) {
10150 if (RHSResult.Failed)
10151 return false;
10152 Result = RHSResult.Val;
10153 return true;
10154 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010155
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010156 if (E->isLogicalOp()) {
10157 bool lhsResult, rhsResult;
10158 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10159 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000010160
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010161 if (LHSIsOK) {
10162 if (RHSIsOK) {
10163 if (E->getOpcode() == BO_LOr)
10164 return Success(lhsResult || rhsResult, E, Result);
10165 else
10166 return Success(lhsResult && rhsResult, E, Result);
10167 }
10168 } else {
10169 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010170 // We can't evaluate the LHS; however, sometimes the result
10171 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10172 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010173 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010174 }
10175 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010176
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010177 return false;
10178 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010179
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010180 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10181 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000010182
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010183 if (LHSResult.Failed || RHSResult.Failed)
10184 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010185
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010186 const APValue &LHSVal = LHSResult.Val;
10187 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000010188
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010189 // Handle cases like (unsigned long)&a + 4.
10190 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10191 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010192 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010193 return true;
10194 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010195
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010196 // Handle cases like 4 + (unsigned long)&a
10197 if (E->getOpcode() == BO_Add &&
10198 RHSVal.isLValue() && LHSVal.isInt()) {
10199 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010200 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010201 return true;
10202 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010203
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010204 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10205 // Handle (intptr_t)&&A - (intptr_t)&&B.
10206 if (!LHSVal.getLValueOffset().isZero() ||
10207 !RHSVal.getLValueOffset().isZero())
10208 return false;
10209 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10210 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10211 if (!LHSExpr || !RHSExpr)
10212 return false;
10213 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10214 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10215 if (!LHSAddrExpr || !RHSAddrExpr)
10216 return false;
10217 // Make sure both labels come from the same function.
10218 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10219 RHSAddrExpr->getLabel()->getDeclContext())
10220 return false;
10221 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10222 return true;
10223 }
Richard Smith43e77732013-05-07 04:50:00 +000010224
10225 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010226 if (!LHSVal.isInt() || !RHSVal.isInt())
10227 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000010228
10229 // Set up the width and signedness manually, in case it can't be deduced
10230 // from the operation we're performing.
10231 // FIXME: Don't do this in the cases where we can deduce it.
10232 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10233 E->getType()->isUnsignedIntegerOrEnumerationType());
10234 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10235 RHSVal.getInt(), Value))
10236 return false;
10237 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010238}
10239
Richard Trieuba4d0872012-03-21 23:30:30 +000010240void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010241 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000010242
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010243 switch (job.Kind) {
10244 case Job::AnyExprKind: {
10245 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10246 if (shouldEnqueue(Bop)) {
10247 job.Kind = Job::BinOpKind;
10248 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010249 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010250 }
10251 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010252
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010253 EvaluateExpr(job.E, Result);
10254 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010255 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010256 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010257
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010258 case Job::BinOpKind: {
10259 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010260 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010261 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010262 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010263 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010264 }
10265 if (SuppressRHSDiags)
10266 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010267 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010268 job.Kind = Job::BinOpVisitedLHSKind;
10269 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010270 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010271 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010272
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010273 case Job::BinOpVisitedLHSKind: {
10274 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10275 EvalResult RHS;
10276 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000010277 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010278 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010279 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010280 }
10281 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010282
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010283 llvm_unreachable("Invalid Job::Kind!");
10284}
10285
George Burgess IV8c892b52016-05-25 22:31:54 +000010286namespace {
10287/// Used when we determine that we should fail, but can keep evaluating prior to
10288/// noting that we had a failure.
10289class DelayedNoteFailureRAII {
10290 EvalInfo &Info;
10291 bool NoteFailure;
10292
10293public:
10294 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10295 : Info(Info), NoteFailure(NoteFailure) {}
10296 ~DelayedNoteFailureRAII() {
10297 if (NoteFailure) {
10298 bool ContinueAfterFailure = Info.noteFailure();
10299 (void)ContinueAfterFailure;
10300 assert(ContinueAfterFailure &&
10301 "Shouldn't have kept evaluating on failure.");
10302 }
10303 }
10304};
10305}
10306
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010307template <class SuccessCB, class AfterCB>
10308static bool
10309EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10310 SuccessCB &&Success, AfterCB &&DoAfter) {
10311 assert(E->isComparisonOp() && "expected comparison operator");
10312 assert((E->getOpcode() == BO_Cmp ||
10313 E->getType()->isIntegralOrEnumerationType()) &&
10314 "unsupported binary expression evaluation");
10315 auto Error = [&](const Expr *E) {
10316 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10317 return false;
10318 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010319
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010320 using CCR = ComparisonCategoryResult;
10321 bool IsRelational = E->isRelationalOp();
10322 bool IsEquality = E->isEqualityOp();
10323 if (E->getOpcode() == BO_Cmp) {
10324 const ComparisonCategoryInfo &CmpInfo =
10325 Info.Ctx.CompCategories.getInfoForType(E->getType());
10326 IsRelational = CmpInfo.isOrdered();
10327 IsEquality = CmpInfo.isEquality();
10328 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000010329
Anders Carlssonacc79812008-11-16 07:17:21 +000010330 QualType LHSTy = E->getLHS()->getType();
10331 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010332
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010333 if (LHSTy->isIntegralOrEnumerationType() &&
10334 RHSTy->isIntegralOrEnumerationType()) {
10335 APSInt LHS, RHS;
10336 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10337 if (!LHSOK && !Info.noteFailure())
10338 return false;
10339 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10340 return false;
10341 if (LHS < RHS)
10342 return Success(CCR::Less, E);
10343 if (LHS > RHS)
10344 return Success(CCR::Greater, E);
10345 return Success(CCR::Equal, E);
10346 }
10347
Leonard Chance1d4f12019-02-21 20:50:09 +000010348 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10349 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10350 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10351
10352 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10353 if (!LHSOK && !Info.noteFailure())
10354 return false;
10355 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10356 return false;
10357 if (LHSFX < RHSFX)
10358 return Success(CCR::Less, E);
10359 if (LHSFX > RHSFX)
10360 return Success(CCR::Greater, E);
10361 return Success(CCR::Equal, E);
10362 }
10363
Chandler Carruthb29a7432014-10-11 11:03:30 +000010364 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010365 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000010366 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000010367 if (E->isAssignmentOp()) {
10368 LValue LV;
10369 EvaluateLValue(E->getLHS(), LV, Info);
10370 LHSOK = false;
10371 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000010372 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10373 if (LHSOK) {
10374 LHS.makeComplexFloat();
10375 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10376 }
10377 } else {
10378 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10379 }
George Burgess IVa145e252016-05-25 22:38:36 +000010380 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010381 return false;
10382
Chandler Carruthb29a7432014-10-11 11:03:30 +000010383 if (E->getRHS()->getType()->isRealFloatingType()) {
10384 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10385 return false;
10386 RHS.makeComplexFloat();
10387 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10388 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010389 return false;
10390
10391 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000010392 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010393 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000010394 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010395 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010396 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10397 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010398 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010399 assert(IsEquality && "invalid complex comparison");
10400 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10401 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10402 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010403 }
10404 }
Mike Stump11289f42009-09-09 15:08:12 +000010405
Anders Carlssonacc79812008-11-16 07:17:21 +000010406 if (LHSTy->isRealFloatingType() &&
10407 RHSTy->isRealFloatingType()) {
10408 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010409
Richard Smith253c2a32012-01-27 01:14:48 +000010410 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010411 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010412 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010413
Richard Smith253c2a32012-01-27 01:14:48 +000010414 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010415 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010416
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010417 assert(E->isComparisonOp() && "Invalid binary operator!");
10418 auto GetCmpRes = [&]() {
10419 switch (LHS.compare(RHS)) {
10420 case APFloat::cmpEqual:
10421 return CCR::Equal;
10422 case APFloat::cmpLessThan:
10423 return CCR::Less;
10424 case APFloat::cmpGreaterThan:
10425 return CCR::Greater;
10426 case APFloat::cmpUnordered:
10427 return CCR::Unordered;
10428 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010429 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010430 };
10431 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010432 }
Mike Stump11289f42009-09-09 15:08:12 +000010433
Eli Friedmana38da572009-04-28 19:17:36 +000010434 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010435 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010436
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010437 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10438 if (!LHSOK && !Info.noteFailure())
10439 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010440
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010441 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10442 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010443
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010444 // Reject differing bases from the normal codepath; we special-case
10445 // comparisons to null.
10446 if (!HasSameBase(LHSValue, RHSValue)) {
10447 // Inequalities and subtractions between unrelated pointers have
10448 // unspecified or undefined behavior.
10449 if (!IsEquality)
10450 return Error(E);
10451 // A constant address may compare equal to the address of a symbol.
10452 // The one exception is that address of an object cannot compare equal
10453 // to a null pointer constant.
10454 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10455 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10456 return Error(E);
10457 // It's implementation-defined whether distinct literals will have
10458 // distinct addresses. In clang, the result of such a comparison is
10459 // unspecified, so it is not a constant expression. However, we do know
10460 // that the address of a literal will be non-null.
10461 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10462 LHSValue.Base && RHSValue.Base)
10463 return Error(E);
10464 // We can't tell whether weak symbols will end up pointing to the same
10465 // object.
10466 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10467 return Error(E);
10468 // We can't compare the address of the start of one object with the
10469 // past-the-end address of another object, per C++ DR1652.
10470 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10471 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10472 (RHSValue.Base && RHSValue.Offset.isZero() &&
10473 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10474 return Error(E);
10475 // We can't tell whether an object is at the same address as another
10476 // zero sized object.
10477 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10478 (LHSValue.Base && isZeroSized(RHSValue)))
10479 return Error(E);
10480 return Success(CCR::Nonequal, E);
10481 }
Eli Friedman64004332009-03-23 04:38:34 +000010482
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010483 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10484 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010485
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010486 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10487 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010488
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010489 // C++11 [expr.rel]p3:
10490 // Pointers to void (after pointer conversions) can be compared, with a
10491 // result defined as follows: If both pointers represent the same
10492 // address or are both the null pointer value, the result is true if the
10493 // operator is <= or >= and false otherwise; otherwise the result is
10494 // unspecified.
10495 // We interpret this as applying to pointers to *cv* void.
10496 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10497 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010498
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010499 // C++11 [expr.rel]p2:
10500 // - If two pointers point to non-static data members of the same object,
10501 // or to subobjects or array elements fo such members, recursively, the
10502 // pointer to the later declared member compares greater provided the
10503 // two members have the same access control and provided their class is
10504 // not a union.
10505 // [...]
10506 // - Otherwise pointer comparisons are unspecified.
10507 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10508 bool WasArrayIndex;
10509 unsigned Mismatch = FindDesignatorMismatch(
10510 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10511 // At the point where the designators diverge, the comparison has a
10512 // specified value if:
10513 // - we are comparing array indices
10514 // - we are comparing fields of a union, or fields with the same access
10515 // Otherwise, the result is unspecified and thus the comparison is not a
10516 // constant expression.
10517 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10518 Mismatch < RHSDesignator.Entries.size()) {
10519 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10520 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10521 if (!LF && !RF)
10522 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10523 else if (!LF)
10524 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010525 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10526 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010527 else if (!RF)
10528 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010529 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10530 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010531 else if (!LF->getParent()->isUnion() &&
10532 LF->getAccess() != RF->getAccess())
10533 Info.CCEDiag(E,
10534 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010535 << LF << LF->getAccess() << RF << RF->getAccess()
10536 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010537 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010538 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010539
10540 // The comparison here must be unsigned, and performed with the same
10541 // width as the pointer.
10542 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10543 uint64_t CompareLHS = LHSOffset.getQuantity();
10544 uint64_t CompareRHS = RHSOffset.getQuantity();
10545 assert(PtrSize <= 64 && "Unexpected pointer width");
10546 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10547 CompareLHS &= Mask;
10548 CompareRHS &= Mask;
10549
10550 // If there is a base and this is a relational operator, we can only
10551 // compare pointers within the object in question; otherwise, the result
10552 // depends on where the object is located in memory.
10553 if (!LHSValue.Base.isNull() && IsRelational) {
10554 QualType BaseTy = getType(LHSValue.Base);
10555 if (BaseTy->isIncompleteType())
10556 return Error(E);
10557 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10558 uint64_t OffsetLimit = Size.getQuantity();
10559 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10560 return Error(E);
10561 }
10562
10563 if (CompareLHS < CompareRHS)
10564 return Success(CCR::Less, E);
10565 if (CompareLHS > CompareRHS)
10566 return Success(CCR::Greater, E);
10567 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010568 }
Richard Smith7bb00672012-02-01 01:42:44 +000010569
10570 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010571 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010572 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10573
10574 MemberPtr LHSValue, RHSValue;
10575
10576 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010577 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010578 return false;
10579
10580 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10581 return false;
10582
10583 // C++11 [expr.eq]p2:
10584 // If both operands are null, they compare equal. Otherwise if only one is
10585 // null, they compare unequal.
10586 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10587 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010588 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010589 }
10590
10591 // Otherwise if either is a pointer to a virtual member function, the
10592 // result is unspecified.
10593 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10594 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010595 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010596 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10597 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010598 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010599
10600 // Otherwise they compare equal if and only if they would refer to the
10601 // same member of the same most derived object or the same subobject if
10602 // they were dereferenced with a hypothetical object of the associated
10603 // class type.
10604 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010605 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010606 }
10607
Richard Smithab44d9b2012-02-14 22:35:28 +000010608 if (LHSTy->isNullPtrType()) {
10609 assert(E->isComparisonOp() && "unexpected nullptr operation");
10610 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10611 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10612 // are compared, the result is true of the operator is <=, >= or ==, and
10613 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010614 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010615 }
10616
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010617 return DoAfter();
10618}
10619
10620bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10621 if (!CheckLiteralType(Info, E))
10622 return false;
10623
10624 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10625 const BinaryOperator *E) {
10626 // Evaluation succeeded. Lookup the information for the comparison category
10627 // type and fetch the VarDecl for the result.
10628 const ComparisonCategoryInfo &CmpInfo =
10629 Info.Ctx.CompCategories.getInfoForType(E->getType());
10630 const VarDecl *VD =
10631 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10632 // Check and evaluate the result as a constant expression.
10633 LValue LV;
10634 LV.set(VD);
10635 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10636 return false;
10637 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10638 };
10639 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10640 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10641 });
10642}
10643
10644bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10645 // We don't call noteFailure immediately because the assignment happens after
10646 // we evaluate LHS and RHS.
10647 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10648 return Error(E);
10649
10650 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10651 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10652 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10653
10654 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10655 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010656 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010657
10658 if (E->isComparisonOp()) {
10659 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10660 // comparisons and then translating the result.
10661 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10662 const BinaryOperator *E) {
10663 using CCR = ComparisonCategoryResult;
10664 bool IsEqual = ResKind == CCR::Equal,
10665 IsLess = ResKind == CCR::Less,
10666 IsGreater = ResKind == CCR::Greater;
10667 auto Op = E->getOpcode();
10668 switch (Op) {
10669 default:
10670 llvm_unreachable("unsupported binary operator");
10671 case BO_EQ:
10672 case BO_NE:
10673 return Success(IsEqual == (Op == BO_EQ), E);
10674 case BO_LT: return Success(IsLess, E);
10675 case BO_GT: return Success(IsGreater, E);
10676 case BO_LE: return Success(IsEqual || IsLess, E);
10677 case BO_GE: return Success(IsEqual || IsGreater, E);
10678 }
10679 };
10680 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10681 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10682 });
10683 }
10684
10685 QualType LHSTy = E->getLHS()->getType();
10686 QualType RHSTy = E->getRHS()->getType();
10687
10688 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10689 E->getOpcode() == BO_Sub) {
10690 LValue LHSValue, RHSValue;
10691
10692 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10693 if (!LHSOK && !Info.noteFailure())
10694 return false;
10695
10696 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10697 return false;
10698
10699 // Reject differing bases from the normal codepath; we special-case
10700 // comparisons to null.
10701 if (!HasSameBase(LHSValue, RHSValue)) {
10702 // Handle &&A - &&B.
10703 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10704 return Error(E);
10705 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10706 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10707 if (!LHSExpr || !RHSExpr)
10708 return Error(E);
10709 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10710 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10711 if (!LHSAddrExpr || !RHSAddrExpr)
10712 return Error(E);
10713 // Make sure both labels come from the same function.
10714 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10715 RHSAddrExpr->getLabel()->getDeclContext())
10716 return Error(E);
10717 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10718 }
10719 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10720 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10721
10722 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10723 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10724
10725 // C++11 [expr.add]p6:
10726 // Unless both pointers point to elements of the same array object, or
10727 // one past the last element of the array object, the behavior is
10728 // undefined.
10729 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10730 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10731 RHSDesignator))
10732 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10733
10734 QualType Type = E->getLHS()->getType();
10735 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10736
10737 CharUnits ElementSize;
10738 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10739 return false;
10740
10741 // As an extension, a type may have zero size (empty struct or union in
10742 // C, array of zero length). Pointer subtraction in such cases has
10743 // undefined behavior, so is not constant.
10744 if (ElementSize.isZero()) {
10745 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10746 << ElementType;
10747 return false;
10748 }
10749
10750 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10751 // and produce incorrect results when it overflows. Such behavior
10752 // appears to be non-conforming, but is common, so perhaps we should
10753 // assume the standard intended for such cases to be undefined behavior
10754 // and check for them.
10755
10756 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10757 // overflow in the final conversion to ptrdiff_t.
10758 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10759 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10760 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10761 false);
10762 APSInt TrueResult = (LHS - RHS) / ElemSize;
10763 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10764
10765 if (Result.extend(65) != TrueResult &&
10766 !HandleOverflow(Info, E, TrueResult, E->getType()))
10767 return false;
10768 return Success(Result, E);
10769 }
10770
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010771 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010772}
10773
Peter Collingbournee190dee2011-03-11 19:24:49 +000010774/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10775/// a result as the expression's type.
10776bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10777 const UnaryExprOrTypeTraitExpr *E) {
10778 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010779 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010780 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010781 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010782 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10783 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010784 else
Richard Smith6822bd72018-10-26 19:26:45 +000010785 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10786 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010787 }
Eli Friedman64004332009-03-23 04:38:34 +000010788
Peter Collingbournee190dee2011-03-11 19:24:49 +000010789 case UETT_VecStep: {
10790 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010791
Peter Collingbournee190dee2011-03-11 19:24:49 +000010792 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010793 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010794
Peter Collingbournee190dee2011-03-11 19:24:49 +000010795 // The vec_step built-in functions that take a 3-component
10796 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10797 if (n == 3)
10798 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010799
Peter Collingbournee190dee2011-03-11 19:24:49 +000010800 return Success(n, E);
10801 } else
10802 return Success(1, E);
10803 }
10804
10805 case UETT_SizeOf: {
10806 QualType SrcTy = E->getTypeOfArgument();
10807 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10808 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010809 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10810 SrcTy = Ref->getPointeeType();
10811
Richard Smithd62306a2011-11-10 06:34:14 +000010812 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010813 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010814 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010815 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010816 }
Alexey Bataev00396512015-07-02 03:40:19 +000010817 case UETT_OpenMPRequiredSimdAlign:
10818 assert(E->isArgumentType());
10819 return Success(
10820 Info.Ctx.toCharUnitsFromBits(
10821 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10822 .getQuantity(),
10823 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010824 }
10825
10826 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010827}
10828
Peter Collingbournee9200682011-05-13 03:29:01 +000010829bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010830 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010831 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010832 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010833 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010834 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010835 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010836 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010837 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010838 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010839 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010840 APSInt IdxResult;
10841 if (!EvaluateInteger(Idx, IdxResult, Info))
10842 return false;
10843 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10844 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010845 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010846 CurrentType = AT->getElementType();
10847 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10848 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010849 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010850 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010851
James Y Knight7281c352015-12-29 22:31:18 +000010852 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010853 FieldDecl *MemberDecl = ON.getField();
10854 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010855 if (!RT)
10856 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010857 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010858 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010859 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010860 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010861 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010862 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010863 CurrentType = MemberDecl->getType().getNonReferenceType();
10864 break;
10865 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010866
James Y Knight7281c352015-12-29 22:31:18 +000010867 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010868 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010869
James Y Knight7281c352015-12-29 22:31:18 +000010870 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010871 CXXBaseSpecifier *BaseSpec = ON.getBase();
10872 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010873 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010874
10875 // Find the layout of the class whose base we are looking into.
10876 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010877 if (!RT)
10878 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010879 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010880 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010881 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10882
10883 // Find the base class itself.
10884 CurrentType = BaseSpec->getType();
10885 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10886 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010887 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010888
Douglas Gregord1702062010-04-29 00:18:15 +000010889 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010890 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010891 break;
10892 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010893 }
10894 }
Peter Collingbournee9200682011-05-13 03:29:01 +000010895 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010896}
10897
Chris Lattnere13042c2008-07-11 19:10:17 +000010898bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010899 switch (E->getOpcode()) {
10900 default:
10901 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10902 // See C99 6.6p3.
10903 return Error(E);
10904 case UO_Extension:
10905 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10906 // If so, we could clear the diagnostic ID.
10907 return Visit(E->getSubExpr());
10908 case UO_Plus:
10909 // The result is just the value.
10910 return Visit(E->getSubExpr());
10911 case UO_Minus: {
10912 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000010913 return false;
10914 if (!Result.isInt()) return Error(E);
10915 const APSInt &Value = Result.getInt();
10916 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10917 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10918 E->getType()))
10919 return false;
Richard Smithfe800032012-01-31 04:08:20 +000010920 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010921 }
10922 case UO_Not: {
10923 if (!Visit(E->getSubExpr()))
10924 return false;
10925 if (!Result.isInt()) return Error(E);
10926 return Success(~Result.getInt(), E);
10927 }
10928 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000010929 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000010930 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000010931 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000010932 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000010933 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010934 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010935}
Mike Stump11289f42009-09-09 15:08:12 +000010936
Chris Lattner477c4be2008-07-12 01:15:53 +000010937/// HandleCast - This is used to evaluate implicit or explicit casts where the
10938/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000010939bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10940 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010941 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000010942 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010943
Eli Friedmanc757de22011-03-25 00:43:55 +000010944 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000010945 case CK_BaseToDerived:
10946 case CK_DerivedToBase:
10947 case CK_UncheckedDerivedToBase:
10948 case CK_Dynamic:
10949 case CK_ToUnion:
10950 case CK_ArrayToPointerDecay:
10951 case CK_FunctionToPointerDecay:
10952 case CK_NullToPointer:
10953 case CK_NullToMemberPointer:
10954 case CK_BaseToDerivedMemberPointer:
10955 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000010956 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000010957 case CK_ConstructorConversion:
10958 case CK_IntegralToPointer:
10959 case CK_ToVoid:
10960 case CK_VectorSplat:
10961 case CK_IntegralToFloating:
10962 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010963 case CK_CPointerToObjCPointerCast:
10964 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010965 case CK_AnyPointerToBlockPointerCast:
10966 case CK_ObjCObjectLValueCast:
10967 case CK_FloatingRealToComplex:
10968 case CK_FloatingComplexToReal:
10969 case CK_FloatingComplexCast:
10970 case CK_FloatingComplexToIntegralComplex:
10971 case CK_IntegralRealToComplex:
10972 case CK_IntegralComplexCast:
10973 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000010974 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010975 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010976 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010977 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010978 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010979 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010980 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000010981 llvm_unreachable("invalid cast kind for integral value");
10982
Eli Friedman9faf2f92011-03-25 19:07:11 +000010983 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010984 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010985 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000010986 case CK_ARCProduceObject:
10987 case CK_ARCConsumeObject:
10988 case CK_ARCReclaimReturnedObject:
10989 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010990 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010991 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010992
Richard Smith4ef685b2012-01-17 21:17:26 +000010993 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000010994 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010995 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000010996 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000010997 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000010998 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010999
11000 case CK_MemberPointerToBoolean:
11001 case CK_PointerToBoolean:
11002 case CK_IntegralToBoolean:
11003 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011004 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000011005 case CK_FloatingComplexToBoolean:
11006 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011007 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000011008 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000011009 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000011010 uint64_t IntResult = BoolResult;
11011 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11012 IntResult = (uint64_t)-1;
11013 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011014 }
11015
Leonard Chan8f7caae2019-03-06 00:28:43 +000011016 case CK_FixedPointToIntegral: {
11017 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11018 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11019 return false;
11020 bool Overflowed;
11021 llvm::APSInt Result = Src.convertToInt(
11022 Info.Ctx.getIntWidth(DestType),
11023 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11024 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11025 return false;
11026 return Success(Result, E);
11027 }
11028
Leonard Chanb4ba4672018-10-23 17:55:35 +000011029 case CK_FixedPointToBoolean: {
11030 // Unsigned padding does not affect this.
11031 APValue Val;
11032 if (!Evaluate(Val, Info, SubExpr))
11033 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011034 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000011035 }
11036
Eli Friedmanc757de22011-03-25 00:43:55 +000011037 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000011038 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000011039 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000011040
Eli Friedman742421e2009-02-20 01:15:07 +000011041 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000011042 // Allow casts of address-of-label differences if they are no-ops
11043 // or narrowing. (The narrowing case isn't actually guaranteed to
11044 // be constant-evaluatable except in some narrow cases which are hard
11045 // to detect here. We let it through on the assumption the user knows
11046 // what they are doing.)
11047 if (Result.isAddrLabelDiff())
11048 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000011049 // Only allow casts of lvalues if they are lossless.
11050 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11051 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000011052
Richard Smith911e1422012-01-30 22:27:01 +000011053 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11054 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000011055 }
Mike Stump11289f42009-09-09 15:08:12 +000011056
Eli Friedmanc757de22011-03-25 00:43:55 +000011057 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000011058 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11059
John McCall45d55e42010-05-07 21:00:08 +000011060 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000011061 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000011062 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000011063
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011064 if (LV.getLValueBase()) {
11065 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000011066 // FIXME: Allow a larger integer size than the pointer size, and allow
11067 // narrowing back down to pointer width in subsequent integral casts.
11068 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011069 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011070 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011071
Richard Smithcf74da72011-11-16 07:18:12 +000011072 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000011073 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011074 return true;
11075 }
11076
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000011077 APSInt AsInt;
11078 APValue V;
11079 LV.moveInto(V);
11080 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11081 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000011082
Richard Smith911e1422012-01-30 22:27:01 +000011083 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011084 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011085
Eli Friedmanc757de22011-03-25 00:43:55 +000011086 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000011087 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011088 if (!EvaluateComplex(SubExpr, C, Info))
11089 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000011090 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011091 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000011092
Eli Friedmanc757de22011-03-25 00:43:55 +000011093 case CK_FloatingToIntegral: {
11094 APFloat F(0.0);
11095 if (!EvaluateFloat(SubExpr, F, Info))
11096 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000011097
Richard Smith357362d2011-12-13 06:39:58 +000011098 APSInt Value;
11099 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11100 return false;
11101 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011102 }
11103 }
Mike Stump11289f42009-09-09 15:08:12 +000011104
Eli Friedmanc757de22011-03-25 00:43:55 +000011105 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000011106}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011107
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011108bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11109 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011110 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011111 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11112 return false;
11113 if (!LV.isComplexInt())
11114 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011115 return Success(LV.getComplexIntReal(), E);
11116 }
11117
11118 return Visit(E->getSubExpr());
11119}
11120
Eli Friedman4e7a2412009-02-27 04:45:43 +000011121bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011122 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011123 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011124 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11125 return false;
11126 if (!LV.isComplexInt())
11127 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011128 return Success(LV.getComplexIntImag(), E);
11129 }
11130
Richard Smith4a678122011-10-24 18:44:57 +000011131 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000011132 return Success(0, E);
11133}
11134
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011135bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11136 return Success(E->getPackLength(), E);
11137}
11138
Sebastian Redl5f0180d2010-09-10 20:55:47 +000011139bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11140 return Success(E->getValue(), E);
11141}
11142
Leonard Chandb01c3a2018-06-20 17:19:40 +000011143bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11144 switch (E->getOpcode()) {
11145 default:
11146 // Invalid unary operators
11147 return Error(E);
11148 case UO_Plus:
11149 // The result is just the value.
11150 return Visit(E->getSubExpr());
11151 case UO_Minus: {
11152 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011153 if (!Result.isFixedPoint())
11154 return Error(E);
11155 bool Overflowed;
11156 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11157 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11158 return false;
11159 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011160 }
11161 case UO_LNot: {
11162 bool bres;
11163 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11164 return false;
11165 return Success(!bres, E);
11166 }
11167 }
11168}
11169
Leonard Chand3f3e162019-01-18 21:04:25 +000011170bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11171 const Expr *SubExpr = E->getSubExpr();
11172 QualType DestType = E->getType();
11173 assert(DestType->isFixedPointType() &&
11174 "Expected destination type to be a fixed point type");
11175 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11176
11177 switch (E->getCastKind()) {
11178 case CK_FixedPointCast: {
11179 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11180 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11181 return false;
11182 bool Overflowed;
11183 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11184 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11185 return false;
11186 return Success(Result, E);
11187 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011188 case CK_IntegralToFixedPoint: {
11189 APSInt Src;
11190 if (!EvaluateInteger(SubExpr, Src, Info))
11191 return false;
11192
11193 bool Overflowed;
11194 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11195 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11196
11197 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11198 return false;
11199
11200 return Success(IntResult, E);
11201 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011202 case CK_NoOp:
11203 case CK_LValueToRValue:
11204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11205 default:
11206 return Error(E);
11207 }
11208}
11209
11210bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11211 const Expr *LHS = E->getLHS();
11212 const Expr *RHS = E->getRHS();
11213 FixedPointSemantics ResultFXSema =
11214 Info.Ctx.getFixedPointSemantics(E->getType());
11215
11216 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11217 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11218 return false;
11219 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11220 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11221 return false;
11222
11223 switch (E->getOpcode()) {
11224 case BO_Add: {
11225 bool AddOverflow, ConversionOverflow;
11226 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11227 .convert(ResultFXSema, &ConversionOverflow);
11228 if ((AddOverflow || ConversionOverflow) &&
11229 !HandleOverflow(Info, E, Result, E->getType()))
11230 return false;
11231 return Success(Result, E);
11232 }
11233 default:
11234 return false;
11235 }
11236 llvm_unreachable("Should've exited before this");
11237}
11238
Chris Lattner05706e882008-07-11 18:11:29 +000011239//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000011240// Float Evaluation
11241//===----------------------------------------------------------------------===//
11242
11243namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011244class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011245 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000011246 APFloat &Result;
11247public:
11248 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011249 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000011250
Richard Smith2e312c82012-03-03 22:46:17 +000011251 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011252 Result = V.getFloat();
11253 return true;
11254 }
Eli Friedman24c01542008-08-22 00:06:13 +000011255
Richard Smithfddd3842011-12-30 21:15:51 +000011256 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000011257 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11258 return true;
11259 }
11260
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011261 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011262
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011263 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011264 bool VisitBinaryOperator(const BinaryOperator *E);
11265 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011266 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000011267
John McCallb1fb0d32010-05-07 22:08:54 +000011268 bool VisitUnaryReal(const UnaryOperator *E);
11269 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000011270
Richard Smithfddd3842011-12-30 21:15:51 +000011271 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000011272};
11273} // end anonymous namespace
11274
11275static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011276 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011277 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000011278}
11279
Jay Foad39c79802011-01-12 09:06:06 +000011280static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000011281 QualType ResultTy,
11282 const Expr *Arg,
11283 bool SNaN,
11284 llvm::APFloat &Result) {
11285 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11286 if (!S) return false;
11287
11288 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11289
11290 llvm::APInt fill;
11291
11292 // Treat empty strings as if they were zero.
11293 if (S->getString().empty())
11294 fill = llvm::APInt(32, 0);
11295 else if (S->getString().getAsInteger(0, fill))
11296 return false;
11297
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000011298 if (Context.getTargetInfo().isNan2008()) {
11299 if (SNaN)
11300 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11301 else
11302 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11303 } else {
11304 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11305 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11306 // a different encoding to what became a standard in 2008, and for pre-
11307 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11308 // sNaN. This is now known as "legacy NaN" encoding.
11309 if (SNaN)
11310 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11311 else
11312 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11313 }
11314
John McCall16291492010-02-28 13:00:19 +000011315 return true;
11316}
11317
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011318bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000011319 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011320 default:
11321 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11322
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011323 case Builtin::BI__builtin_huge_val:
11324 case Builtin::BI__builtin_huge_valf:
11325 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011326 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011327 case Builtin::BI__builtin_inf:
11328 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011329 case Builtin::BI__builtin_infl:
11330 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011331 const llvm::fltSemantics &Sem =
11332 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000011333 Result = llvm::APFloat::getInf(Sem);
11334 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011335 }
Mike Stump11289f42009-09-09 15:08:12 +000011336
John McCall16291492010-02-28 13:00:19 +000011337 case Builtin::BI__builtin_nans:
11338 case Builtin::BI__builtin_nansf:
11339 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011340 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011341 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11342 true, Result))
11343 return Error(E);
11344 return true;
John McCall16291492010-02-28 13:00:19 +000011345
Chris Lattner0b7282e2008-10-06 06:31:58 +000011346 case Builtin::BI__builtin_nan:
11347 case Builtin::BI__builtin_nanf:
11348 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011349 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000011350 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000011351 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000011352 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11353 false, Result))
11354 return Error(E);
11355 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011356
11357 case Builtin::BI__builtin_fabs:
11358 case Builtin::BI__builtin_fabsf:
11359 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011360 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011361 if (!EvaluateFloat(E->getArg(0), Result, Info))
11362 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011363
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011364 if (Result.isNegative())
11365 Result.changeSign();
11366 return true;
11367
Richard Smith8889a3d2013-06-13 06:26:32 +000011368 // FIXME: Builtin::BI__builtin_powi
11369 // FIXME: Builtin::BI__builtin_powif
11370 // FIXME: Builtin::BI__builtin_powil
11371
Mike Stump11289f42009-09-09 15:08:12 +000011372 case Builtin::BI__builtin_copysign:
11373 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011374 case Builtin::BI__builtin_copysignl:
11375 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011376 APFloat RHS(0.);
11377 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11378 !EvaluateFloat(E->getArg(1), RHS, Info))
11379 return false;
11380 Result.copySign(RHS);
11381 return true;
11382 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011383 }
11384}
11385
John McCallb1fb0d32010-05-07 22:08:54 +000011386bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011387 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11388 ComplexValue CV;
11389 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11390 return false;
11391 Result = CV.FloatReal;
11392 return true;
11393 }
11394
11395 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000011396}
11397
11398bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011399 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11400 ComplexValue CV;
11401 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11402 return false;
11403 Result = CV.FloatImag;
11404 return true;
11405 }
11406
Richard Smith4a678122011-10-24 18:44:57 +000011407 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011408 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11409 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011410 return true;
11411}
11412
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011413bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011414 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011415 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011416 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011417 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011418 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011419 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11420 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011421 Result.changeSign();
11422 return true;
11423 }
11424}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011425
Eli Friedman24c01542008-08-22 00:06:13 +000011426bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011427 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11428 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011429
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011430 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011431 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011432 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011433 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011434 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11435 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011436}
11437
11438bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11439 Result = E->getValue();
11440 return true;
11441}
11442
Peter Collingbournee9200682011-05-13 03:29:01 +000011443bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11444 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011445
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011446 switch (E->getCastKind()) {
11447 default:
Richard Smith11562c52011-10-28 17:51:58 +000011448 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011449
11450 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011451 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011452 return EvaluateInteger(SubExpr, IntResult, Info) &&
11453 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11454 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011455 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011456
11457 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011458 if (!Visit(SubExpr))
11459 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011460 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11461 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011462 }
John McCalld7646252010-11-14 08:17:51 +000011463
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011464 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011465 ComplexValue V;
11466 if (!EvaluateComplex(SubExpr, V, Info))
11467 return false;
11468 Result = V.getComplexFloatReal();
11469 return true;
11470 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011471 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011472}
11473
Eli Friedman24c01542008-08-22 00:06:13 +000011474//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011475// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011476//===----------------------------------------------------------------------===//
11477
11478namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011479class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011480 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011481 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011482
Anders Carlsson537969c2008-11-16 20:27:53 +000011483public:
John McCall93d91dc2010-05-07 17:22:02 +000011484 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011485 : ExprEvaluatorBaseTy(info), Result(Result) {}
11486
Richard Smith2e312c82012-03-03 22:46:17 +000011487 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011488 Result.setFrom(V);
11489 return true;
11490 }
Mike Stump11289f42009-09-09 15:08:12 +000011491
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011492 bool ZeroInitialization(const Expr *E);
11493
Anders Carlsson537969c2008-11-16 20:27:53 +000011494 //===--------------------------------------------------------------------===//
11495 // Visitor Methods
11496 //===--------------------------------------------------------------------===//
11497
Peter Collingbournee9200682011-05-13 03:29:01 +000011498 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011499 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011500 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011501 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011502 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011503};
11504} // end anonymous namespace
11505
John McCall93d91dc2010-05-07 17:22:02 +000011506static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11507 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011508 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011509 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011510}
11511
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011512bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011513 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011514 if (ElemTy->isRealFloatingType()) {
11515 Result.makeComplexFloat();
11516 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11517 Result.FloatReal = Zero;
11518 Result.FloatImag = Zero;
11519 } else {
11520 Result.makeComplexInt();
11521 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11522 Result.IntReal = Zero;
11523 Result.IntImag = Zero;
11524 }
11525 return true;
11526}
11527
Peter Collingbournee9200682011-05-13 03:29:01 +000011528bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11529 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011530
11531 if (SubExpr->getType()->isRealFloatingType()) {
11532 Result.makeComplexFloat();
11533 APFloat &Imag = Result.FloatImag;
11534 if (!EvaluateFloat(SubExpr, Imag, Info))
11535 return false;
11536
11537 Result.FloatReal = APFloat(Imag.getSemantics());
11538 return true;
11539 } else {
11540 assert(SubExpr->getType()->isIntegerType() &&
11541 "Unexpected imaginary literal.");
11542
11543 Result.makeComplexInt();
11544 APSInt &Imag = Result.IntImag;
11545 if (!EvaluateInteger(SubExpr, Imag, Info))
11546 return false;
11547
11548 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11549 return true;
11550 }
11551}
11552
Peter Collingbournee9200682011-05-13 03:29:01 +000011553bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011554
John McCallfcef3cf2010-12-14 17:51:41 +000011555 switch (E->getCastKind()) {
11556 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011557 case CK_BaseToDerived:
11558 case CK_DerivedToBase:
11559 case CK_UncheckedDerivedToBase:
11560 case CK_Dynamic:
11561 case CK_ToUnion:
11562 case CK_ArrayToPointerDecay:
11563 case CK_FunctionToPointerDecay:
11564 case CK_NullToPointer:
11565 case CK_NullToMemberPointer:
11566 case CK_BaseToDerivedMemberPointer:
11567 case CK_DerivedToBaseMemberPointer:
11568 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011569 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011570 case CK_ConstructorConversion:
11571 case CK_IntegralToPointer:
11572 case CK_PointerToIntegral:
11573 case CK_PointerToBoolean:
11574 case CK_ToVoid:
11575 case CK_VectorSplat:
11576 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011577 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011578 case CK_IntegralToBoolean:
11579 case CK_IntegralToFloating:
11580 case CK_FloatingToIntegral:
11581 case CK_FloatingToBoolean:
11582 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011583 case CK_CPointerToObjCPointerCast:
11584 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011585 case CK_AnyPointerToBlockPointerCast:
11586 case CK_ObjCObjectLValueCast:
11587 case CK_FloatingComplexToReal:
11588 case CK_FloatingComplexToBoolean:
11589 case CK_IntegralComplexToReal:
11590 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011591 case CK_ARCProduceObject:
11592 case CK_ARCConsumeObject:
11593 case CK_ARCReclaimReturnedObject:
11594 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011595 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011596 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011597 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011598 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011599 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011600 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011601 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011602 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011603 case CK_FixedPointToIntegral:
11604 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011605 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011606
John McCallfcef3cf2010-12-14 17:51:41 +000011607 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011608 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011609 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011610 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011611 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011612
11613 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011614 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011615 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011616 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011617
11618 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011619 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011620 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011621 return false;
11622
John McCallfcef3cf2010-12-14 17:51:41 +000011623 Result.makeComplexFloat();
11624 Result.FloatImag = APFloat(Real.getSemantics());
11625 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011626 }
11627
John McCallfcef3cf2010-12-14 17:51:41 +000011628 case CK_FloatingComplexCast: {
11629 if (!Visit(E->getSubExpr()))
11630 return false;
11631
11632 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11633 QualType From
11634 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11635
Richard Smith357362d2011-12-13 06:39:58 +000011636 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11637 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011638 }
11639
11640 case CK_FloatingComplexToIntegralComplex: {
11641 if (!Visit(E->getSubExpr()))
11642 return false;
11643
11644 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11645 QualType From
11646 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11647 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011648 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11649 To, Result.IntReal) &&
11650 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11651 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011652 }
11653
11654 case CK_IntegralRealToComplex: {
11655 APSInt &Real = Result.IntReal;
11656 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11657 return false;
11658
11659 Result.makeComplexInt();
11660 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11661 return true;
11662 }
11663
11664 case CK_IntegralComplexCast: {
11665 if (!Visit(E->getSubExpr()))
11666 return false;
11667
11668 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11669 QualType From
11670 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11671
Richard Smith911e1422012-01-30 22:27:01 +000011672 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11673 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011674 return true;
11675 }
11676
11677 case CK_IntegralComplexToFloatingComplex: {
11678 if (!Visit(E->getSubExpr()))
11679 return false;
11680
Ted Kremenek28831752012-08-23 20:46:57 +000011681 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011682 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011683 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011684 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011685 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11686 To, Result.FloatReal) &&
11687 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11688 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011689 }
11690 }
11691
11692 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011693}
11694
John McCall93d91dc2010-05-07 17:22:02 +000011695bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011696 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011697 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11698
Chandler Carrutha216cad2014-10-11 00:57:18 +000011699 // Track whether the LHS or RHS is real at the type system level. When this is
11700 // the case we can simplify our evaluation strategy.
11701 bool LHSReal = false, RHSReal = false;
11702
11703 bool LHSOK;
11704 if (E->getLHS()->getType()->isRealFloatingType()) {
11705 LHSReal = true;
11706 APFloat &Real = Result.FloatReal;
11707 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11708 if (LHSOK) {
11709 Result.makeComplexFloat();
11710 Result.FloatImag = APFloat(Real.getSemantics());
11711 }
11712 } else {
11713 LHSOK = Visit(E->getLHS());
11714 }
George Burgess IVa145e252016-05-25 22:38:36 +000011715 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011716 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011717
John McCall93d91dc2010-05-07 17:22:02 +000011718 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011719 if (E->getRHS()->getType()->isRealFloatingType()) {
11720 RHSReal = true;
11721 APFloat &Real = RHS.FloatReal;
11722 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11723 return false;
11724 RHS.makeComplexFloat();
11725 RHS.FloatImag = APFloat(Real.getSemantics());
11726 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011727 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011728
Chandler Carrutha216cad2014-10-11 00:57:18 +000011729 assert(!(LHSReal && RHSReal) &&
11730 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011731 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011732 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011733 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011734 if (Result.isComplexFloat()) {
11735 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11736 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011737 if (LHSReal)
11738 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11739 else if (!RHSReal)
11740 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11741 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011742 } else {
11743 Result.getComplexIntReal() += RHS.getComplexIntReal();
11744 Result.getComplexIntImag() += RHS.getComplexIntImag();
11745 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011746 break;
John McCalle3027922010-08-25 11:45:40 +000011747 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011748 if (Result.isComplexFloat()) {
11749 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11750 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011751 if (LHSReal) {
11752 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11753 Result.getComplexFloatImag().changeSign();
11754 } else if (!RHSReal) {
11755 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11756 APFloat::rmNearestTiesToEven);
11757 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011758 } else {
11759 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11760 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11761 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011762 break;
John McCalle3027922010-08-25 11:45:40 +000011763 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011764 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011765 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011766 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011767 // following naming scheme:
11768 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011769 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011770 APFloat &A = LHS.getComplexFloatReal();
11771 APFloat &B = LHS.getComplexFloatImag();
11772 APFloat &C = RHS.getComplexFloatReal();
11773 APFloat &D = RHS.getComplexFloatImag();
11774 APFloat &ResR = Result.getComplexFloatReal();
11775 APFloat &ResI = Result.getComplexFloatImag();
11776 if (LHSReal) {
11777 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11778 ResR = A * C;
11779 ResI = A * D;
11780 } else if (RHSReal) {
11781 ResR = C * A;
11782 ResI = C * B;
11783 } else {
11784 // In the fully general case, we need to handle NaNs and infinities
11785 // robustly.
11786 APFloat AC = A * C;
11787 APFloat BD = B * D;
11788 APFloat AD = A * D;
11789 APFloat BC = B * C;
11790 ResR = AC - BD;
11791 ResI = AD + BC;
11792 if (ResR.isNaN() && ResI.isNaN()) {
11793 bool Recalc = false;
11794 if (A.isInfinity() || B.isInfinity()) {
11795 A = APFloat::copySign(
11796 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11797 B = APFloat::copySign(
11798 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11799 if (C.isNaN())
11800 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11801 if (D.isNaN())
11802 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11803 Recalc = true;
11804 }
11805 if (C.isInfinity() || D.isInfinity()) {
11806 C = APFloat::copySign(
11807 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11808 D = APFloat::copySign(
11809 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11810 if (A.isNaN())
11811 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11812 if (B.isNaN())
11813 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11814 Recalc = true;
11815 }
11816 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11817 AD.isInfinity() || BC.isInfinity())) {
11818 if (A.isNaN())
11819 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11820 if (B.isNaN())
11821 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11822 if (C.isNaN())
11823 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11824 if (D.isNaN())
11825 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11826 Recalc = true;
11827 }
11828 if (Recalc) {
11829 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11830 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11831 }
11832 }
11833 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011834 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011835 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011836 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011837 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11838 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011839 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011840 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11841 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11842 }
11843 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011844 case BO_Div:
11845 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011846 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011847 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011848 // following naming scheme:
11849 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011850 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011851 APFloat &A = LHS.getComplexFloatReal();
11852 APFloat &B = LHS.getComplexFloatImag();
11853 APFloat &C = RHS.getComplexFloatReal();
11854 APFloat &D = RHS.getComplexFloatImag();
11855 APFloat &ResR = Result.getComplexFloatReal();
11856 APFloat &ResI = Result.getComplexFloatImag();
11857 if (RHSReal) {
11858 ResR = A / C;
11859 ResI = B / C;
11860 } else {
11861 if (LHSReal) {
11862 // No real optimizations we can do here, stub out with zero.
11863 B = APFloat::getZero(A.getSemantics());
11864 }
11865 int DenomLogB = 0;
11866 APFloat MaxCD = maxnum(abs(C), abs(D));
11867 if (MaxCD.isFinite()) {
11868 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011869 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11870 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011871 }
11872 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011873 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11874 APFloat::rmNearestTiesToEven);
11875 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11876 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011877 if (ResR.isNaN() && ResI.isNaN()) {
11878 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11879 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11880 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11881 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11882 D.isFinite()) {
11883 A = APFloat::copySign(
11884 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11885 B = APFloat::copySign(
11886 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11887 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11888 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11889 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11890 C = APFloat::copySign(
11891 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11892 D = APFloat::copySign(
11893 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11894 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11895 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11896 }
11897 }
11898 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011899 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011900 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11901 return Error(E, diag::note_expr_divide_by_zero);
11902
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011903 ComplexValue LHS = Result;
11904 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11905 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11906 Result.getComplexIntReal() =
11907 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11908 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11909 Result.getComplexIntImag() =
11910 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11911 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11912 }
11913 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011914 }
11915
John McCall93d91dc2010-05-07 17:22:02 +000011916 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011917}
11918
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011919bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11920 // Get the operand value into 'Result'.
11921 if (!Visit(E->getSubExpr()))
11922 return false;
11923
11924 switch (E->getOpcode()) {
11925 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011926 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011927 case UO_Extension:
11928 return true;
11929 case UO_Plus:
11930 // The result is always just the subexpr.
11931 return true;
11932 case UO_Minus:
11933 if (Result.isComplexFloat()) {
11934 Result.getComplexFloatReal().changeSign();
11935 Result.getComplexFloatImag().changeSign();
11936 }
11937 else {
11938 Result.getComplexIntReal() = -Result.getComplexIntReal();
11939 Result.getComplexIntImag() = -Result.getComplexIntImag();
11940 }
11941 return true;
11942 case UO_Not:
11943 if (Result.isComplexFloat())
11944 Result.getComplexFloatImag().changeSign();
11945 else
11946 Result.getComplexIntImag() = -Result.getComplexIntImag();
11947 return true;
11948 }
11949}
11950
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011951bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11952 if (E->getNumInits() == 2) {
11953 if (E->getType()->isComplexType()) {
11954 Result.makeComplexFloat();
11955 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11956 return false;
11957 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11958 return false;
11959 } else {
11960 Result.makeComplexInt();
11961 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11962 return false;
11963 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11964 return false;
11965 }
11966 return true;
11967 }
11968 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11969}
11970
Anders Carlsson537969c2008-11-16 20:27:53 +000011971//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000011972// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11973// implicit conversion.
11974//===----------------------------------------------------------------------===//
11975
11976namespace {
11977class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000011978 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011979 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000011980 APValue &Result;
11981public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011982 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11983 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000011984
11985 bool Success(const APValue &V, const Expr *E) {
11986 Result = V;
11987 return true;
11988 }
11989
11990 bool ZeroInitialization(const Expr *E) {
11991 ImplicitValueInitExpr VIE(
11992 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011993 // For atomic-qualified class (and array) types in C++, initialize the
11994 // _Atomic-wrapped subobject directly, in-place.
11995 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11996 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000011997 }
11998
11999 bool VisitCastExpr(const CastExpr *E) {
12000 switch (E->getCastKind()) {
12001 default:
12002 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12003 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012004 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12005 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000012006 }
12007 }
12008};
12009} // end anonymous namespace
12010
Richard Smith64cb9ca2017-02-22 22:09:50 +000012011static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12012 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000012013 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012014 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000012015}
12016
12017//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000012018// Void expression evaluation, primarily for a cast to void on the LHS of a
12019// comma operator
12020//===----------------------------------------------------------------------===//
12021
12022namespace {
12023class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012024 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000012025public:
12026 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12027
Richard Smith2e312c82012-03-03 22:46:17 +000012028 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000012029
Richard Smith7cd577b2017-08-17 19:35:50 +000012030 bool ZeroInitialization(const Expr *E) { return true; }
12031
Richard Smith42d3af92011-12-07 00:43:50 +000012032 bool VisitCastExpr(const CastExpr *E) {
12033 switch (E->getCastKind()) {
12034 default:
12035 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12036 case CK_ToVoid:
12037 VisitIgnoredValue(E->getSubExpr());
12038 return true;
12039 }
12040 }
Hal Finkela8443c32014-07-17 14:49:58 +000012041
12042 bool VisitCallExpr(const CallExpr *E) {
12043 switch (E->getBuiltinCallee()) {
12044 default:
12045 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12046 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000012047 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000012048 // The argument is not evaluated!
12049 return true;
12050 }
12051 }
Richard Smith42d3af92011-12-07 00:43:50 +000012052};
12053} // end anonymous namespace
12054
12055static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12056 assert(E->isRValue() && E->getType()->isVoidType());
12057 return VoidExprEvaluator(Info).Visit(E);
12058}
12059
12060//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000012061// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000012062//===----------------------------------------------------------------------===//
12063
Richard Smith2e312c82012-03-03 22:46:17 +000012064static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000012065 // In C, function designators are not lvalues, but we evaluate them as if they
12066 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000012067 QualType T = E->getType();
12068 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000012069 LValue LV;
12070 if (!EvaluateLValue(E, LV, Info))
12071 return false;
12072 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012073 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012074 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000012075 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012076 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012077 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012078 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012079 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000012080 LValue LV;
12081 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012082 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012083 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012084 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000012085 llvm::APFloat F(0.0);
12086 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012087 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000012088 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000012089 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000012090 ComplexValue C;
12091 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012092 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012093 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012094 } else if (T->isFixedPointType()) {
12095 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012096 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000012097 MemberPtr P;
12098 if (!EvaluateMemberPointer(E, P, Info))
12099 return false;
12100 P.moveInto(Result);
12101 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000012102 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012103 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012104 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012105 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000012106 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012107 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012108 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012109 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012110 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012111 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000012112 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012113 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012114 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012115 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000012116 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000012117 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000012118 if (!EvaluateVoid(E, Info))
12119 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012120 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012121 QualType Unqual = T.getAtomicUnqualifiedType();
12122 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12123 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012124 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012125 if (!EvaluateAtomic(E, &LV, Value, Info))
12126 return false;
12127 } else {
12128 if (!EvaluateAtomic(E, nullptr, Result, Info))
12129 return false;
12130 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012131 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000012132 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000012133 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012134 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000012135 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000012136 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012137 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012138
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000012139 return true;
12140}
12141
Richard Smithb228a862012-02-15 02:18:13 +000012142/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12143/// cases, the in-place evaluation is essential, since later initializers for
12144/// an object can indirectly refer to subobjects which were initialized earlier.
12145static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000012146 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000012147 assert(!E->isValueDependent());
12148
Richard Smith7525ff62013-05-09 07:14:00 +000012149 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000012150 return false;
12151
12152 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000012153 // Evaluate arrays and record types in-place, so that later initializers can
12154 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000012155 QualType T = E->getType();
12156 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000012157 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012158 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000012159 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012160 else if (T->isAtomicType()) {
12161 QualType Unqual = T.getAtomicUnqualifiedType();
12162 if (Unqual->isArrayType() || Unqual->isRecordType())
12163 return EvaluateAtomic(E, &This, Result, Info);
12164 }
Richard Smithed5165f2011-11-04 05:33:44 +000012165 }
12166
12167 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000012168 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000012169}
12170
Richard Smithf57d8cb2011-12-09 22:58:01 +000012171/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12172/// lvalue-to-rvalue cast if it is an lvalue.
12173static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Licker950b70d2019-09-13 09:46:16 +000012174 if (Info.EnableNewConstInterp) {
12175 auto &InterpCtx = Info.Ctx.getInterpContext();
12176 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
12177 case interp::InterpResult::Success:
12178 return true;
12179 case interp::InterpResult::Fail:
12180 return false;
12181 case interp::InterpResult::Bail:
12182 break;
12183 }
12184 }
12185
James Dennett0492ef02014-03-14 17:44:10 +000012186 if (E->getType().isNull())
12187 return false;
12188
Nick Lewyckyc190f962017-05-02 01:06:16 +000012189 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000012190 return false;
12191
Richard Smith2e312c82012-03-03 22:46:17 +000012192 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012193 return false;
12194
12195 if (E->isGLValue()) {
12196 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000012197 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000012198 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012199 return false;
12200 }
12201
Richard Smith2e312c82012-03-03 22:46:17 +000012202 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000012203 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012204}
Richard Smith11562c52011-10-28 17:51:58 +000012205
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012206static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000012207 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012208 // Fast-path evaluations of integer literals, since we sometimes see files
12209 // containing vast quantities of these.
12210 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12211 Result.Val = APValue(APSInt(L->getValue(),
12212 L->getType()->isUnsignedIntegerType()));
12213 IsConst = true;
12214 return true;
12215 }
James Dennett0492ef02014-03-14 17:44:10 +000012216
12217 // This case should be rare, but we need to check it before we check on
12218 // the type below.
12219 if (Exp->getType().isNull()) {
12220 IsConst = false;
12221 return true;
12222 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012223
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012224 // FIXME: Evaluating values of large array and record types can cause
12225 // performance problems. Only do so in C++11 for now.
12226 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12227 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000012228 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012229 IsConst = false;
12230 return true;
12231 }
12232 return false;
12233}
12234
Fangrui Song407659a2018-11-30 23:41:18 +000012235static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12236 Expr::SideEffectsKind SEK) {
12237 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12238 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12239}
12240
12241static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12242 const ASTContext &Ctx, EvalInfo &Info) {
12243 bool IsConst;
12244 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12245 return IsConst;
12246
12247 return EvaluateAsRValue(Info, E, Result.Val);
12248}
12249
12250static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12251 const ASTContext &Ctx,
12252 Expr::SideEffectsKind AllowSideEffects,
12253 EvalInfo &Info) {
12254 if (!E->getType()->isIntegralOrEnumerationType())
12255 return false;
12256
12257 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12258 !ExprResult.Val.isInt() ||
12259 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12260 return false;
12261
12262 return true;
12263}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012264
Leonard Chand3f3e162019-01-18 21:04:25 +000012265static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12266 const ASTContext &Ctx,
12267 Expr::SideEffectsKind AllowSideEffects,
12268 EvalInfo &Info) {
12269 if (!E->getType()->isFixedPointType())
12270 return false;
12271
12272 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12273 return false;
12274
12275 if (!ExprResult.Val.isFixedPoint() ||
12276 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12277 return false;
12278
12279 return true;
12280}
12281
Richard Smith7b553f12011-10-29 00:50:52 +000012282/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000012283/// any crazy technique (that has nothing to do with language standards) that
12284/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000012285/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12286/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000012287bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12288 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012289 assert(!isValueDependent() &&
12290 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000012291 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012292 Info.InConstantContext = InConstantContext;
12293 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000012294}
12295
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012296bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12297 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012298 assert(!isValueDependent() &&
12299 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000012300 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012301 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000012302 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000012303}
12304
Fangrui Song407659a2018-11-30 23:41:18 +000012305bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012306 SideEffectsKind AllowSideEffects,
12307 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012308 assert(!isValueDependent() &&
12309 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000012310 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012311 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000012312 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000012313}
12314
Leonard Chand3f3e162019-01-18 21:04:25 +000012315bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012316 SideEffectsKind AllowSideEffects,
12317 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012318 assert(!isValueDependent() &&
12319 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000012320 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012321 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000012322 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12323}
12324
Richard Trieube234c32016-04-21 21:04:55 +000012325bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012326 SideEffectsKind AllowSideEffects,
12327 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012328 assert(!isValueDependent() &&
12329 "Expression evaluator can't be called on a dependent expression.");
12330
Richard Trieube234c32016-04-21 21:04:55 +000012331 if (!getType()->isRealFloatingType())
12332 return false;
12333
12334 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012335 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12336 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000012337 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000012338 return false;
12339
12340 Result = ExprResult.Val.getFloat();
12341 return true;
12342}
12343
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012344bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12345 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012346 assert(!isValueDependent() &&
12347 "Expression evaluator can't be called on a dependent expression.");
12348
Richard Smith6d4c6582013-11-05 22:18:15 +000012349 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012350 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000012351 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000012352 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12353 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000012354 Ctx.getLValueReferenceType(getType()), LV,
12355 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000012356 return false;
12357
Richard Smith2e312c82012-03-03 22:46:17 +000012358 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000012359 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000012360}
12361
Reid Kleckner1a840d22018-05-10 18:57:35 +000012362bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12363 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012364 assert(!isValueDependent() &&
12365 "Expression evaluator can't be called on a dependent expression.");
12366
Reid Kleckner1a840d22018-05-10 18:57:35 +000012367 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12368 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000012369 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000012370
Reid Kleckner1a840d22018-05-10 18:57:35 +000012371 if (!::Evaluate(Result.Val, Info, this))
12372 return false;
12373
12374 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12375 Usage);
12376}
12377
Richard Smithd0b4dd62011-12-19 06:19:21 +000012378bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12379 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012380 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012381 assert(!isValueDependent() &&
12382 "Expression evaluator can't be called on a dependent expression.");
12383
Richard Smithdafff942012-01-14 04:30:29 +000012384 // FIXME: Evaluating initializers for large array and record types can cause
12385 // performance problems. Only do so in C++11 for now.
12386 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012387 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000012388 return false;
12389
Richard Smithd0b4dd62011-12-19 06:19:21 +000012390 Expr::EvalStatus EStatus;
12391 EStatus.Diag = &Notes;
12392
Nandor Licker950b70d2019-09-13 09:46:16 +000012393 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000012394 ? EvalInfo::EM_ConstantExpression
12395 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000012396 Info.setEvaluatingDecl(VD, Value);
12397 Info.InConstantContext = true;
12398
12399 SourceLocation DeclLoc = VD->getLocation();
12400 QualType DeclTy = VD->getType();
12401
12402 if (Info.EnableNewConstInterp) {
12403 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
12404 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
12405 case interp::InterpResult::Fail:
12406 // Bail out if an error was encountered.
12407 return false;
12408 case interp::InterpResult::Success:
12409 // Evaluation succeeded and value was set.
12410 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
12411 case interp::InterpResult::Bail:
12412 // Evaluate the value again for the tree evaluator to use.
12413 break;
12414 }
12415 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000012416
12417 LValue LVal;
12418 LVal.set(VD);
12419
Richard Smithfddd3842011-12-30 21:15:51 +000012420 // C++11 [basic.start.init]p2:
12421 // Variables with static storage duration or thread storage duration shall be
12422 // zero-initialized before any other initialization takes place.
12423 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012424 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Nandor Licker950b70d2019-09-13 09:46:16 +000012425 !DeclTy->isReferenceType()) {
12426 ImplicitValueInitExpr VIE(DeclTy);
12427 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000012428 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000012429 return false;
12430 }
12431
Nandor Licker950b70d2019-09-13 09:46:16 +000012432 if (!EvaluateInPlace(Value, Info, LVal, this,
Richard Smith7525ff62013-05-09 07:14:00 +000012433 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012434 EStatus.HasSideEffects)
12435 return false;
12436
Nandor Licker950b70d2019-09-13 09:46:16 +000012437 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012438}
12439
Richard Smith7b553f12011-10-29 00:50:52 +000012440/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12441/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012442bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012443 assert(!isValueDependent() &&
12444 "Expression evaluator can't be called on a dependent expression.");
12445
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012446 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012447 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012448 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012449}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012450
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012451APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012452 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012453 assert(!isValueDependent() &&
12454 "Expression evaluator can't be called on a dependent expression.");
12455
Fangrui Song407659a2018-11-30 23:41:18 +000012456 EvalResult EVResult;
12457 EVResult.Diag = Diag;
12458 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12459 Info.InConstantContext = true;
12460
12461 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012462 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012463 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012464 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012465
Fangrui Song407659a2018-11-30 23:41:18 +000012466 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012467}
John McCall864e3962010-05-07 05:32:02 +000012468
David Bolvansky3b6ae572018-10-18 20:49:06 +000012469APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12470 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012471 assert(!isValueDependent() &&
12472 "Expression evaluator can't be called on a dependent expression.");
12473
Fangrui Song407659a2018-11-30 23:41:18 +000012474 EvalResult EVResult;
12475 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000012476 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012477 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000012478 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000012479
12480 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012481 (void)Result;
12482 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012483 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012484
Fangrui Song407659a2018-11-30 23:41:18 +000012485 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012486}
12487
Richard Smithe9ff7702013-11-05 22:23:30 +000012488void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012489 assert(!isValueDependent() &&
12490 "Expression evaluator can't be called on a dependent expression.");
12491
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012492 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012493 EvalResult EVResult;
12494 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000012495 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12496 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000012497 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012498 }
12499}
12500
Richard Smithe6c01442013-06-05 00:46:14 +000012501bool Expr::EvalResult::isGlobalLValue() const {
12502 assert(Val.isLValue());
12503 return IsGlobalLValue(Val.getLValueBase());
12504}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012505
12506
John McCall864e3962010-05-07 05:32:02 +000012507/// isIntegerConstantExpr - this recursive routine will test if an expression is
12508/// an integer constant expression.
12509
12510/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12511/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012512
12513// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012514// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12515// and a (possibly null) SourceLocation indicating the location of the problem.
12516//
John McCall864e3962010-05-07 05:32:02 +000012517// Note that to reduce code duplication, this helper does no evaluation
12518// itself; the caller checks whether the expression is evaluatable, and
12519// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012520// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012521
Dan Gohman28ade552010-07-26 21:25:24 +000012522namespace {
12523
Richard Smith9e575da2012-12-28 13:25:52 +000012524enum ICEKind {
12525 /// This expression is an ICE.
12526 IK_ICE,
12527 /// This expression is not an ICE, but if it isn't evaluated, it's
12528 /// a legal subexpression for an ICE. This return value is used to handle
12529 /// the comma operator in C99 mode, and non-constant subexpressions.
12530 IK_ICEIfUnevaluated,
12531 /// This expression is not an ICE, and is not a legal subexpression for one.
12532 IK_NotICE
12533};
12534
John McCall864e3962010-05-07 05:32:02 +000012535struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012536 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012537 SourceLocation Loc;
12538
Richard Smith9e575da2012-12-28 13:25:52 +000012539 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012540};
12541
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012542}
Dan Gohman28ade552010-07-26 21:25:24 +000012543
Richard Smith9e575da2012-12-28 13:25:52 +000012544static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12545
12546static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012547
Craig Toppera31a8822013-08-22 07:09:37 +000012548static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012549 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012550 Expr::EvalStatus Status;
12551 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12552
12553 Info.InConstantContext = true;
12554 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012555 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012556 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012557
John McCall864e3962010-05-07 05:32:02 +000012558 return NoDiag();
12559}
12560
Craig Toppera31a8822013-08-22 07:09:37 +000012561static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012562 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012563 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012564 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012565
12566 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012567#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012568#define STMT(Node, Base) case Expr::Node##Class:
12569#define EXPR(Node, Base)
12570#include "clang/AST/StmtNodes.inc"
12571 case Expr::PredefinedExprClass:
12572 case Expr::FloatingLiteralClass:
12573 case Expr::ImaginaryLiteralClass:
12574 case Expr::StringLiteralClass:
12575 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012576 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012577 case Expr::MemberExprClass:
12578 case Expr::CompoundAssignOperatorClass:
12579 case Expr::CompoundLiteralExprClass:
12580 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012581 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012582 case Expr::ArrayInitLoopExprClass:
12583 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012584 case Expr::NoInitExprClass:
12585 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012586 case Expr::ImplicitValueInitExprClass:
12587 case Expr::ParenListExprClass:
12588 case Expr::VAArgExprClass:
12589 case Expr::AddrLabelExprClass:
12590 case Expr::StmtExprClass:
12591 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012592 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012593 case Expr::CXXDynamicCastExprClass:
12594 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012595 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012596 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012597 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012598 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012599 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012600 case Expr::CXXThisExprClass:
12601 case Expr::CXXThrowExprClass:
12602 case Expr::CXXNewExprClass:
12603 case Expr::CXXDeleteExprClass:
12604 case Expr::CXXPseudoDestructorExprClass:
12605 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012606 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012607 case Expr::DependentScopeDeclRefExprClass:
12608 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012609 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012610 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012611 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012612 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012613 case Expr::CXXTemporaryObjectExprClass:
12614 case Expr::CXXUnresolvedConstructExprClass:
12615 case Expr::CXXDependentScopeMemberExprClass:
12616 case Expr::UnresolvedMemberExprClass:
12617 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012618 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012619 case Expr::ObjCArrayLiteralClass:
12620 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012621 case Expr::ObjCEncodeExprClass:
12622 case Expr::ObjCMessageExprClass:
12623 case Expr::ObjCSelectorExprClass:
12624 case Expr::ObjCProtocolExprClass:
12625 case Expr::ObjCIvarRefExprClass:
12626 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012627 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012628 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012629 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012630 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012631 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012632 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012633 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012634 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000012635 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000012636 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000012637 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000012638 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000012639 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000012640 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000012641 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000012642 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000012643 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000012644 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012645 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000012646 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012647 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012648 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000012649
Richard Smithf137f932014-01-25 20:50:08 +000012650 case Expr::InitListExprClass: {
12651 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12652 // form "T x = { a };" is equivalent to "T x = a;".
12653 // Unless we're initializing a reference, T is a scalar as it is known to be
12654 // of integral or enumeration type.
12655 if (E->isRValue())
12656 if (cast<InitListExpr>(E)->getNumInits() == 1)
12657 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012658 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012659 }
12660
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012661 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012662 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012663 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012664 return NoDiag();
12665
John McCall7c454bb2011-07-15 05:09:51 +000012666 case Expr::SubstNonTypeTemplateParmExprClass:
12667 return
12668 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12669
Bill Wendling7c44da22018-10-31 03:48:47 +000012670 case Expr::ConstantExprClass:
12671 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12672
John McCall864e3962010-05-07 05:32:02 +000012673 case Expr::ParenExprClass:
12674 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012675 case Expr::GenericSelectionExprClass:
12676 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012677 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012678 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012679 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012680 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012681 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012682 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012683 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012684 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012685 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012686 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012687 return NoDiag();
12688 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012689 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012690 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12691 // constant expressions, but they can never be ICEs because an ICE cannot
12692 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012693 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012694 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012695 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012696 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012697 }
Richard Smith6365c912012-02-24 22:12:32 +000012698 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012699 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12700 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012701 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012702 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012703 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012704 // Parameter variables are never constants. Without this check,
12705 // getAnyInitializer() can find a default argument, which leads
12706 // to chaos.
12707 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012708 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012709
12710 // C++ 7.1.5.1p2
12711 // A variable of non-volatile const-qualified integral or enumeration
12712 // type initialized by an ICE can be used in ICEs.
12713 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012714 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012715 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012716
Richard Smithd0b4dd62011-12-19 06:19:21 +000012717 const VarDecl *VD;
12718 // Look for a declaration of this variable that has an initializer, and
12719 // check whether it is an ICE.
12720 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12721 return NoDiag();
12722 else
Richard Smith9e575da2012-12-28 13:25:52 +000012723 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012724 }
12725 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012726 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012727 }
John McCall864e3962010-05-07 05:32:02 +000012728 case Expr::UnaryOperatorClass: {
12729 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12730 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012731 case UO_PostInc:
12732 case UO_PostDec:
12733 case UO_PreInc:
12734 case UO_PreDec:
12735 case UO_AddrOf:
12736 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012737 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012738 // C99 6.6/3 allows increment and decrement within unevaluated
12739 // subexpressions of constant expressions, but they can never be ICEs
12740 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012741 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012742 case UO_Extension:
12743 case UO_LNot:
12744 case UO_Plus:
12745 case UO_Minus:
12746 case UO_Not:
12747 case UO_Real:
12748 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012749 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012750 }
Reid Klecknere540d972018-11-01 17:51:48 +000012751 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012752 }
12753 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012754 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12755 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12756 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12757 // compliance: we should warn earlier for offsetof expressions with
12758 // array subscripts that aren't ICEs, and if the array subscripts
12759 // are ICEs, the value of the offsetof must be an integer constant.
12760 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012761 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012762 case Expr::UnaryExprOrTypeTraitExprClass: {
12763 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12764 if ((Exp->getKind() == UETT_SizeOf) &&
12765 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012766 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012767 return NoDiag();
12768 }
12769 case Expr::BinaryOperatorClass: {
12770 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12771 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012772 case BO_PtrMemD:
12773 case BO_PtrMemI:
12774 case BO_Assign:
12775 case BO_MulAssign:
12776 case BO_DivAssign:
12777 case BO_RemAssign:
12778 case BO_AddAssign:
12779 case BO_SubAssign:
12780 case BO_ShlAssign:
12781 case BO_ShrAssign:
12782 case BO_AndAssign:
12783 case BO_XorAssign:
12784 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012785 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12786 // constant expressions, but they can never be ICEs because an ICE cannot
12787 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012788 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012789
John McCalle3027922010-08-25 11:45:40 +000012790 case BO_Mul:
12791 case BO_Div:
12792 case BO_Rem:
12793 case BO_Add:
12794 case BO_Sub:
12795 case BO_Shl:
12796 case BO_Shr:
12797 case BO_LT:
12798 case BO_GT:
12799 case BO_LE:
12800 case BO_GE:
12801 case BO_EQ:
12802 case BO_NE:
12803 case BO_And:
12804 case BO_Xor:
12805 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012806 case BO_Comma:
12807 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012808 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12809 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012810 if (Exp->getOpcode() == BO_Div ||
12811 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012812 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012813 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012814 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012815 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012816 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012817 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012818 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012819 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012820 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012821 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012822 }
12823 }
12824 }
John McCalle3027922010-08-25 11:45:40 +000012825 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012826 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012827 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12828 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012829 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012830 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012831 } else {
12832 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012833 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012834 }
12835 }
Richard Smith9e575da2012-12-28 13:25:52 +000012836 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012837 }
John McCalle3027922010-08-25 11:45:40 +000012838 case BO_LAnd:
12839 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012840 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12841 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012842 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012843 // Rare case where the RHS has a comma "side-effect"; we need
12844 // to actually check the condition to see whether the side
12845 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012846 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012847 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012848 return RHSResult;
12849 return NoDiag();
12850 }
12851
Richard Smith9e575da2012-12-28 13:25:52 +000012852 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012853 }
12854 }
Reid Klecknere540d972018-11-01 17:51:48 +000012855 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012856 }
12857 case Expr::ImplicitCastExprClass:
12858 case Expr::CStyleCastExprClass:
12859 case Expr::CXXFunctionalCastExprClass:
12860 case Expr::CXXStaticCastExprClass:
12861 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012862 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012863 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012864 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012865 if (isa<ExplicitCastExpr>(E)) {
12866 if (const FloatingLiteral *FL
12867 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12868 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12869 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12870 APSInt IgnoredVal(DestWidth, !DestSigned);
12871 bool Ignored;
12872 // If the value does not fit in the destination type, the behavior is
12873 // undefined, so we are not required to treat it as a constant
12874 // expression.
12875 if (FL->getValue().convertToInteger(IgnoredVal,
12876 llvm::APFloat::rmTowardZero,
12877 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012878 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012879 return NoDiag();
12880 }
12881 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012882 switch (cast<CastExpr>(E)->getCastKind()) {
12883 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012884 case CK_AtomicToNonAtomic:
12885 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012886 case CK_NoOp:
12887 case CK_IntegralToBoolean:
12888 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012889 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012890 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012891 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012892 }
John McCall864e3962010-05-07 05:32:02 +000012893 }
John McCallc07a0c72011-02-17 10:25:35 +000012894 case Expr::BinaryConditionalOperatorClass: {
12895 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12896 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012897 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012898 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012899 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12900 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12901 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012902 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012903 return FalseResult;
12904 }
John McCall864e3962010-05-07 05:32:02 +000012905 case Expr::ConditionalOperatorClass: {
12906 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12907 // If the condition (ignoring parens) is a __builtin_constant_p call,
12908 // then only the true side is actually considered in an integer constant
12909 // expression, and it is fully evaluated. This is an important GNU
12910 // extension. See GCC PR38377 for discussion.
12911 if (const CallExpr *CallCE
12912 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012913 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012914 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012915 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012916 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012917 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012918
Richard Smithf57d8cb2011-12-09 22:58:01 +000012919 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12920 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012921
Richard Smith9e575da2012-12-28 13:25:52 +000012922 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012923 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012924 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012925 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012926 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000012927 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012928 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000012929 return NoDiag();
12930 // Rare case where the diagnostics depend on which side is evaluated
12931 // Note that if we get here, CondResult is 0, and at least one of
12932 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000012933 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000012934 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000012935 return TrueResult;
12936 }
12937 case Expr::CXXDefaultArgExprClass:
12938 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000012939 case Expr::CXXDefaultInitExprClass:
12940 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012941 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000012942 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012943 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012944 case Expr::BuiltinBitCastExprClass: {
12945 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
12946 return ICEDiag(IK_NotICE, E->getBeginLoc());
12947 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
12948 }
John McCall864e3962010-05-07 05:32:02 +000012949 }
12950
David Blaikiee4d798f2012-01-20 21:50:17 +000012951 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000012952}
12953
Richard Smithf57d8cb2011-12-09 22:58:01 +000012954/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000012955static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012956 const Expr *E,
12957 llvm::APSInt *Value,
12958 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000012959 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012960 if (Loc) *Loc = E->getExprLoc();
12961 return false;
12962 }
12963
Richard Smith66e05fe2012-01-18 05:21:49 +000012964 APValue Result;
12965 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000012966 return false;
12967
Richard Smith98710fc2014-11-13 23:03:19 +000012968 if (!Result.isInt()) {
12969 if (Loc) *Loc = E->getExprLoc();
12970 return false;
12971 }
12972
Richard Smith66e05fe2012-01-18 05:21:49 +000012973 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000012974 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012975}
12976
Craig Toppera31a8822013-08-22 07:09:37 +000012977bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12978 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012979 assert(!isValueDependent() &&
12980 "Expression evaluator can't be called on a dependent expression.");
12981
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012982 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000012983 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012984
Richard Smith9e575da2012-12-28 13:25:52 +000012985 ICEDiag D = CheckICE(this, Ctx);
12986 if (D.Kind != IK_ICE) {
12987 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000012988 return false;
12989 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000012990 return true;
12991}
12992
Craig Toppera31a8822013-08-22 07:09:37 +000012993bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012994 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012995 assert(!isValueDependent() &&
12996 "Expression evaluator can't be called on a dependent expression.");
12997
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012998 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000012999 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13000
13001 if (!isIntegerConstantExpr(Ctx, Loc))
13002 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000013003
Richard Smith5c40f092015-12-04 03:00:44 +000013004 // The only possible side-effects here are due to UB discovered in the
13005 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13006 // required to treat the expression as an ICE, so we produce the folded
13007 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000013008 EvalResult ExprResult;
13009 Expr::EvalStatus Status;
13010 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13011 Info.InConstantContext = true;
13012
13013 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000013014 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000013015
13016 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000013017 return true;
13018}
Richard Smith66e05fe2012-01-18 05:21:49 +000013019
Craig Toppera31a8822013-08-22 07:09:37 +000013020bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013021 assert(!isValueDependent() &&
13022 "Expression evaluator can't be called on a dependent expression.");
13023
Richard Smith9e575da2012-12-28 13:25:52 +000013024 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000013025}
13026
Craig Toppera31a8822013-08-22 07:09:37 +000013027bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000013028 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013029 assert(!isValueDependent() &&
13030 "Expression evaluator can't be called on a dependent expression.");
13031
Richard Smith66e05fe2012-01-18 05:21:49 +000013032 // We support this checking in C++98 mode in order to diagnose compatibility
13033 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013034 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000013035
Richard Smith98a0a492012-02-14 21:38:30 +000013036 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000013037 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013038 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000013039 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000013040 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000013041
13042 APValue Scratch;
13043 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13044
13045 if (!Diags.empty()) {
13046 IsConstExpr = false;
13047 if (Loc) *Loc = Diags[0].first;
13048 } else if (!IsConstExpr) {
13049 // FIXME: This shouldn't happen.
13050 if (Loc) *Loc = getExprLoc();
13051 }
13052
13053 return IsConstExpr;
13054}
Richard Smith253c2a32012-01-27 01:14:48 +000013055
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013056bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13057 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000013058 ArrayRef<const Expr*> Args,
13059 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013060 assert(!isValueDependent() &&
13061 "Expression evaluator can't be called on a dependent expression.");
13062
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013063 Expr::EvalStatus Status;
13064 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013065 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013066
George Burgess IV177399e2017-01-09 04:12:14 +000013067 LValue ThisVal;
13068 const LValue *ThisPtr = nullptr;
13069 if (This) {
13070#ifndef NDEBUG
13071 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13072 assert(MD && "Don't provide `this` for non-methods.");
13073 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13074#endif
13075 if (EvaluateObjectArgument(Info, This, ThisVal))
13076 ThisPtr = &ThisVal;
13077 if (Info.EvalStatus.HasSideEffects)
13078 return false;
13079 }
13080
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013081 ArgVector ArgValues(Args.size());
13082 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13083 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000013084 if ((*I)->isValueDependent() ||
13085 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013086 // If evaluation fails, throw away the argument entirely.
13087 ArgValues[I - Args.begin()] = APValue();
13088 if (Info.EvalStatus.HasSideEffects)
13089 return false;
13090 }
13091
13092 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000013093 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013094 ArgValues.data());
13095 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13096}
13097
Richard Smith253c2a32012-01-27 01:14:48 +000013098bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013099 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000013100 PartialDiagnosticAt> &Diags) {
13101 // FIXME: It would be useful to check constexpr function templates, but at the
13102 // moment the constant expression evaluator cannot cope with the non-rigorous
13103 // ASTs which we build for dependent expressions.
13104 if (FD->isDependentContext())
13105 return true;
13106
13107 Expr::EvalStatus Status;
13108 Status.Diag = &Diags;
13109
Richard Smith045b2272019-09-10 21:24:09 +000013110 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000013111 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013112 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000013113
Nandor Licker950b70d2019-09-13 09:46:16 +000013114 // The constexpr VM attempts to compile all methods to bytecode here.
13115 if (Info.EnableNewConstInterp) {
13116 auto &InterpCtx = Info.Ctx.getInterpContext();
13117 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
13118 case interp::InterpResult::Success:
13119 case interp::InterpResult::Fail:
13120 return Diags.empty();
13121 case interp::InterpResult::Bail:
13122 break;
13123 }
13124 }
13125
Richard Smith253c2a32012-01-27 01:14:48 +000013126 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000013127 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000013128
Richard Smith7525ff62013-05-09 07:14:00 +000013129 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000013130 // is a temporary being used as the 'this' pointer.
13131 LValue This;
13132 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000013133 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000013134
Richard Smith253c2a32012-01-27 01:14:48 +000013135 ArrayRef<const Expr*> Args;
13136
Richard Smith2e312c82012-03-03 22:46:17 +000013137 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000013138 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13139 // Evaluate the call as a constant initializer, to allow the construction
13140 // of objects of non-literal types.
13141 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000013142 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13143 } else {
13144 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000013145 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000013146 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000013147 }
Richard Smith253c2a32012-01-27 01:14:48 +000013148
13149 return Diags.empty();
13150}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013151
13152bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13153 const FunctionDecl *FD,
13154 SmallVectorImpl<
13155 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013156 assert(!E->isValueDependent() &&
13157 "Expression evaluator can't be called on a dependent expression.");
13158
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013159 Expr::EvalStatus Status;
13160 Status.Diag = &Diags;
13161
13162 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000013163 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013164 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013165 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013166
13167 // Fabricate a call stack frame to give the arguments a plausible cover story.
13168 ArrayRef<const Expr*> Args;
13169 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013170 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013171 (void)Success;
13172 assert(Success &&
13173 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000013174 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013175
13176 APValue ResultScratch;
13177 Evaluate(ResultScratch, Info, E);
13178 return Diags.empty();
13179}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013180
13181bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13182 unsigned Type) const {
13183 if (!getType()->isPointerType())
13184 return false;
13185
13186 Expr::EvalStatus Status;
13187 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000013188 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013189}