Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST/ExprConstant.cpp
Warning:line 3278, column 10
Access to field 'Callee' results in a dereference of a null pointer (loaded from field 'CurrentCall')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ExprConstant.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST/ExprConstant.cpp
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// 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
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
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//
33//===----------------------------------------------------------------------===//
34
35#include "Interp/Context.h"
36#include "Interp/Frame.h"
37#include "Interp/State.h"
38#include "clang/AST/APValue.h"
39#include "clang/AST/ASTContext.h"
40#include "clang/AST/ASTDiagnostic.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
43#include "clang/AST/CXXInheritance.h"
44#include "clang/AST/CharUnits.h"
45#include "clang/AST/CurrentSourceLocExprScope.h"
46#include "clang/AST/Expr.h"
47#include "clang/AST/OSLog.h"
48#include "clang/AST/OptionalDiagnostic.h"
49#include "clang/AST/RecordLayout.h"
50#include "clang/AST/StmtVisitor.h"
51#include "clang/AST/TypeLoc.h"
52#include "clang/Basic/Builtins.h"
53#include "clang/Basic/TargetInfo.h"
54#include "llvm/ADT/APFixedPoint.h"
55#include "llvm/ADT/Optional.h"
56#include "llvm/ADT/SmallBitVector.h"
57#include "llvm/Support/Debug.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/raw_ostream.h"
60#include <cstring>
61#include <functional>
62
63#define DEBUG_TYPE"exprconstant" "exprconstant"
64
65using namespace clang;
66using llvm::APFixedPoint;
67using llvm::APInt;
68using llvm::APSInt;
69using llvm::APFloat;
70using llvm::FixedPointSemantics;
71using llvm::Optional;
72
73namespace {
74 struct LValue;
75 class CallStackFrame;
76 class EvalInfo;
77
78 using SourceLocExprScopeGuard =
79 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80
81 static QualType getType(APValue::LValueBase B) {
82 return B.getType();
83 }
84
85 /// Get an LValue path entry, which is known to not be an array index, as a
86 /// field declaration.
87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89 }
90 /// Get an LValue path entry, which is known to not be an array index, as a
91 /// base class declaration.
92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94 }
95 /// Determine whether this LValue path entry for a base class names a virtual
96 /// base class.
97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98 return E.getAsBaseOrMember().getInt();
99 }
100
101 /// Given an expression, determine the type used to store the result of
102 /// evaluating that expression.
103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104 if (E->isPRValue())
105 return E->getType();
106 return Ctx.getLValueReferenceType(E->getType());
107 }
108
109 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112 return DirectCallee->getAttr<AllocSizeAttr>();
113 if (const Decl *IndirectCallee = CE->getCalleeDecl())
114 return IndirectCallee->getAttr<AllocSizeAttr>();
115 return nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return getAllocSizeAttr(CE) ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind",
"clang/lib/AST/ExprConstant.cpp", 163)
;
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind",
"clang/lib/AST/ExprConstant.cpp", 176)
;
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191 ArrayRef<APValue::LValuePathEntry> Path,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&(static_cast <bool> (!isBaseAnAllocSizeCall(Base) &&
"Unsized arrays shouldn't appear here") ? void (0) : __assert_fail
("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__
))
197 "Unsized arrays shouldn't appear here")(static_cast <bool> (!isBaseAnAllocSizeCall(Base) &&
"Unsized arrays shouldn't appear here") ? void (0) : __assert_fail
("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__
))
;
198 unsigned MostDerivedLength = 0;
199 Type = getType(Base);
200
201 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202 if (Type->isArrayType()) {
203 const ArrayType *AT = Ctx.getAsArrayType(Type);
204 Type = AT->getElementType();
205 MostDerivedLength = I + 1;
206 IsArray = true;
207
208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209 ArraySize = CAT->getSize().getZExtValue();
210 } else {
211 assert(I == 0 && "unexpected unsized array designator")(static_cast <bool> (I == 0 && "unexpected unsized array designator"
) ? void (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\""
, "clang/lib/AST/ExprConstant.cpp", 211, __extension__ __PRETTY_FUNCTION__
))
;
212 FirstEntryIsUnsizedArray = true;
213 ArraySize = AssumedSizeForUnsizedArray;
214 }
215 } else if (Type->isAnyComplexType()) {
216 const ComplexType *CT = Type->castAs<ComplexType>();
217 Type = CT->getElementType();
218 ArraySize = 2;
219 MostDerivedLength = I + 1;
220 IsArray = true;
221 } else if (const FieldDecl *FD = getAsField(Path[I])) {
222 Type = FD->getType();
223 ArraySize = 0;
224 MostDerivedLength = I + 1;
225 IsArray = false;
226 } else {
227 // Path[I] describes a base class.
228 ArraySize = 0;
229 IsArray = false;
230 }
231 }
232 return MostDerivedLength;
233 }
234
235 /// A path from a glvalue to a subobject of that glvalue.
236 struct SubobjectDesignator {
237 /// True if the subobject was named in a manner not supported by C++11. Such
238 /// lvalues can still be folded, but they are not core constant expressions
239 /// and we cannot perform lvalue-to-rvalue conversions on them.
240 unsigned Invalid : 1;
241
242 /// Is this a pointer one past the end of an object?
243 unsigned IsOnePastTheEnd : 1;
244
245 /// Indicator of whether the first entry is an unsized array.
246 unsigned FirstEntryIsAnUnsizedArray : 1;
247
248 /// Indicator of whether the most-derived object is an array element.
249 unsigned MostDerivedIsArrayElement : 1;
250
251 /// The length of the path to the most-derived object of which this is a
252 /// subobject.
253 unsigned MostDerivedPathLength : 28;
254
255 /// The size of the array of which the most-derived object is an element.
256 /// This will always be 0 if the most-derived object is not an array
257 /// element. 0 is not an indicator of whether or not the most-derived object
258 /// is an array, however, because 0-length arrays are allowed.
259 ///
260 /// If the current array is an unsized array, the value of this is
261 /// undefined.
262 uint64_t MostDerivedArraySize;
263
264 /// The type of the most derived object referred to by this address.
265 QualType MostDerivedType;
266
267 typedef APValue::LValuePathEntry PathEntry;
268
269 /// The entries on the path from the glvalue to the designated subobject.
270 SmallVector<PathEntry, 8> Entries;
271
272 SubobjectDesignator() : Invalid(true) {}
273
274 explicit SubobjectDesignator(QualType T)
275 : Invalid(false), IsOnePastTheEnd(false),
276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277 MostDerivedPathLength(0), MostDerivedArraySize(0),
278 MostDerivedType(T) {}
279
280 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283 MostDerivedPathLength(0), MostDerivedArraySize(0) {
284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?")(static_cast <bool> (V.isLValue() && "Non-LValue used to make an LValue designator?"
) ? void (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\""
, "clang/lib/AST/ExprConstant.cpp", 284, __extension__ __PRETTY_FUNCTION__
))
;
285 if (!Invalid) {
286 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287 ArrayRef<PathEntry> VEntries = V.getLValuePath();
288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289 if (V.getLValueBase()) {
290 bool IsArray = false;
291 bool FirstIsUnsizedArray = false;
292 MostDerivedPathLength = findMostDerivedSubobject(
293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294 MostDerivedType, IsArray, FirstIsUnsizedArray);
295 MostDerivedIsArrayElement = IsArray;
296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297 }
298 }
299 }
300
301 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302 unsigned NewLength) {
303 if (Invalid)
304 return;
305
306 assert(Base && "cannot truncate path for null pointer")(static_cast <bool> (Base && "cannot truncate path for null pointer"
) ? void (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\""
, "clang/lib/AST/ExprConstant.cpp", 306, __extension__ __PRETTY_FUNCTION__
))
;
307 assert(NewLength <= Entries.size() && "not a truncation")(static_cast <bool> (NewLength <= Entries.size() &&
"not a truncation") ? void (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\""
, "clang/lib/AST/ExprConstant.cpp", 307, __extension__ __PRETTY_FUNCTION__
))
;
308
309 if (NewLength == Entries.size())
310 return;
311 Entries.resize(NewLength);
312
313 bool IsArray = false;
314 bool FirstIsUnsizedArray = false;
315 MostDerivedPathLength = findMostDerivedSubobject(
316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317 FirstIsUnsizedArray);
318 MostDerivedIsArrayElement = IsArray;
319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320 }
321
322 void setInvalid() {
323 Invalid = true;
324 Entries.clear();
325 }
326
327 /// Determine whether the most derived subobject is an array without a
328 /// known bound.
329 bool isMostDerivedAnUnsizedArray() const {
330 assert(!Invalid && "Calling this makes no sense on invalid designators")(static_cast <bool> (!Invalid && "Calling this makes no sense on invalid designators"
) ? void (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\""
, "clang/lib/AST/ExprConstant.cpp", 330, __extension__ __PRETTY_FUNCTION__
))
;
331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332 }
333
334 /// Determine what the most derived array's size is. Results in an assertion
335 /// failure if the most derived array lacks a size.
336 uint64_t getMostDerivedArraySize() const {
337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")(static_cast <bool> (!isMostDerivedAnUnsizedArray() &&
"Unsized array has no size") ? void (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\""
, "clang/lib/AST/ExprConstant.cpp", 337, __extension__ __PRETTY_FUNCTION__
))
;
338 return MostDerivedArraySize;
339 }
340
341 /// Determine whether this is a one-past-the-end pointer.
342 bool isOnePastTheEnd() const {
343 assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail
("!Invalid", "clang/lib/AST/ExprConstant.cpp", 343, __extension__
__PRETTY_FUNCTION__))
;
344 if (IsOnePastTheEnd)
345 return true;
346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348 MostDerivedArraySize)
349 return true;
350 return false;
351 }
352
353 /// Get the range of valid index adjustments in the form
354 /// {maximum value that can be subtracted from this pointer,
355 /// maximum value that can be added to this pointer}
356 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357 if (Invalid || isMostDerivedAnUnsizedArray())
358 return {0, 0};
359
360 // [expr.add]p4: For the purposes of these operators, a pointer to a
361 // nonarray object behaves the same as a pointer to the first element of
362 // an array of length one with the type of the object as its element type.
363 bool IsArray = MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement;
365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366 : (uint64_t)IsOnePastTheEnd;
367 uint64_t ArraySize =
368 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369 return {ArrayIndex, ArraySize - ArrayIndex};
370 }
371
372 /// Check that this refers to a valid subobject.
373 bool isValidSubobject() const {
374 if (Invalid)
375 return false;
376 return !isOnePastTheEnd();
377 }
378 /// Check that this refers to a valid subobject, and if not, produce a
379 /// relevant diagnostic and set the designator as invalid.
380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381
382 /// Get the type of the designated object.
383 QualType getType(ASTContext &Ctx) const {
384 assert(!Invalid && "invalid designator has no subobject type")(static_cast <bool> (!Invalid && "invalid designator has no subobject type"
) ? void (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\""
, "clang/lib/AST/ExprConstant.cpp", 384, __extension__ __PRETTY_FUNCTION__
))
;
385 return MostDerivedPathLength == Entries.size()
386 ? MostDerivedType
387 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388 }
389
390 /// Update this designator to refer to the first element within this array.
391 void addArrayUnchecked(const ConstantArrayType *CAT) {
392 Entries.push_back(PathEntry::ArrayIndex(0));
393
394 // This is a most-derived object.
395 MostDerivedType = CAT->getElementType();
396 MostDerivedIsArrayElement = true;
397 MostDerivedArraySize = CAT->getSize().getZExtValue();
398 MostDerivedPathLength = Entries.size();
399 }
400 /// Update this designator to refer to the first element within the array of
401 /// elements of type T. This is an array of unknown size.
402 void addUnsizedArrayUnchecked(QualType ElemTy) {
403 Entries.push_back(PathEntry::ArrayIndex(0));
404
405 MostDerivedType = ElemTy;
406 MostDerivedIsArrayElement = true;
407 // The value in MostDerivedArraySize is undefined in this case. So, set it
408 // to an arbitrary value that's likely to loudly break things if it's
409 // used.
410 MostDerivedArraySize = AssumedSizeForUnsizedArray;
411 MostDerivedPathLength = Entries.size();
412 }
413 /// Update this designator to refer to the given base or member of this
414 /// object.
415 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417
418 // If this isn't a base class, it's a new most-derived object.
419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420 MostDerivedType = FD->getType();
421 MostDerivedIsArrayElement = false;
422 MostDerivedArraySize = 0;
423 MostDerivedPathLength = Entries.size();
424 }
425 }
426 /// Update this designator to refer to the given complex component.
427 void addComplexUnchecked(QualType EltTy, bool Imag) {
428 Entries.push_back(PathEntry::ArrayIndex(Imag));
429
430 // This is technically a most-derived object, though in practice this
431 // is unlikely to matter.
432 MostDerivedType = EltTy;
433 MostDerivedIsArrayElement = true;
434 MostDerivedArraySize = 2;
435 MostDerivedPathLength = Entries.size();
436 }
437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439 const APSInt &N);
440 /// Add N to the address of this subobject.
441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442 if (Invalid || !N) return;
443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444 if (isMostDerivedAnUnsizedArray()) {
445 diagnoseUnsizedArrayPointerArithmetic(Info, E);
446 // Can't verify -- trust that the user is doing the right thing (or if
447 // not, trust that the caller will catch the bad behavior).
448 // FIXME: Should we reject if this overflows, at least?
449 Entries.back() = PathEntry::ArrayIndex(
450 Entries.back().getAsArrayIndex() + TruncatedN);
451 return;
452 }
453
454 // [expr.add]p4: For the purposes of these operators, a pointer to a
455 // nonarray object behaves the same as a pointer to the first element of
456 // an array of length one with the type of the object as its element type.
457 bool IsArray = MostDerivedPathLength == Entries.size() &&
458 MostDerivedIsArrayElement;
459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460 : (uint64_t)IsOnePastTheEnd;
461 uint64_t ArraySize =
462 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463
464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465 // Calculate the actual index in a wide enough type, so we can include
466 // it in the note.
467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468 (llvm::APInt&)N += ArrayIndex;
469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")(static_cast <bool> (N.ugt(ArraySize) && "bounds check failed for in-bounds index"
) ? void (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\""
, "clang/lib/AST/ExprConstant.cpp", 469, __extension__ __PRETTY_FUNCTION__
))
;
470 diagnosePointerArithmetic(Info, E, N);
471 setInvalid();
472 return;
473 }
474
475 ArrayIndex += TruncatedN;
476 assert(ArrayIndex <= ArraySize &&(static_cast <bool> (ArrayIndex <= ArraySize &&
"bounds check succeeded for out-of-bounds index") ? void (0)
: __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
477 "bounds check succeeded for out-of-bounds index")(static_cast <bool> (ArrayIndex <= ArraySize &&
"bounds check succeeded for out-of-bounds index") ? void (0)
: __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
;
478
479 if (IsArray)
480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481 else
482 IsOnePastTheEnd = (ArrayIndex != 0);
483 }
484 };
485
486 /// A scope at the end of which an object can need to be destroyed.
487 enum class ScopeKind {
488 Block,
489 FullExpression,
490 Call
491 };
492
493 /// A reference to a particular call and its arguments.
494 struct CallRef {
495 CallRef() : OrigCallee(), CallIndex(0), Version() {}
496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498
499 explicit operator bool() const { return OrigCallee; }
500
501 /// Get the parameter that the caller initialized, corresponding to the
502 /// given parameter in the callee.
503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505 : PVD;
506 }
507
508 /// The callee at the point where the arguments were evaluated. This might
509 /// be different from the actual callee (a different redeclaration, or a
510 /// virtual override), but this function's parameters are the ones that
511 /// appear in the parameter map.
512 const FunctionDecl *OrigCallee;
513 /// The call index of the frame that holds the argument values.
514 unsigned CallIndex;
515 /// The version of the parameters corresponding to this call.
516 unsigned Version;
517 };
518
519 /// A stack frame in the constexpr call stack.
520 class CallStackFrame : public interp::Frame {
521 public:
522 EvalInfo &Info;
523
524 /// Parent - The caller of this stack frame.
525 CallStackFrame *Caller;
526
527 /// Callee - The function which was called.
528 const FunctionDecl *Callee;
529
530 /// This - The binding for the this pointer in this call, if any.
531 const LValue *This;
532
533 /// Information on how to find the arguments to this call. Our arguments
534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535 /// key and this value as the version.
536 CallRef Arguments;
537
538 /// Source location information about the default argument or default
539 /// initializer expression we're evaluating, if any.
540 CurrentSourceLocExprScope CurSourceLocExprScope;
541
542 // Note that we intentionally use std::map here so that references to
543 // values are stable.
544 typedef std::pair<const void *, unsigned> MapKeyTy;
545 typedef std::map<MapKeyTy, APValue> MapTy;
546 /// Temporaries - Temporary lvalues materialized within this stack frame.
547 MapTy Temporaries;
548
549 /// CallLoc - The location of the call expression for this call.
550 SourceLocation CallLoc;
551
552 /// Index - The call index of this call.
553 unsigned Index;
554
555 /// The stack of integers for tracking version numbers for temporaries.
556 SmallVector<unsigned, 2> TempVersionStack = {1};
557 unsigned CurTempVersion = TempVersionStack.back();
558
559 unsigned getTempVersion() const { return TempVersionStack.back(); }
560
561 void pushTempVersion() {
562 TempVersionStack.push_back(++CurTempVersion);
563 }
564
565 void popTempVersion() {
566 TempVersionStack.pop_back();
567 }
568
569 CallRef createCall(const FunctionDecl *Callee) {
570 return {Callee, Index, ++CurTempVersion};
571 }
572
573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574 // on the overall stack usage of deeply-recursing constexpr evaluations.
575 // (We should cache this map rather than recomputing it repeatedly.)
576 // But let's try this and see how it goes; we can look into caching the map
577 // as a later change.
578
579 /// LambdaCaptureFields - Mapping from captured variables/this to
580 /// corresponding data members in the closure class.
581 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
582 FieldDecl *LambdaThisCaptureField;
583
584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585 const FunctionDecl *Callee, const LValue *This,
586 CallRef Arguments);
587 ~CallStackFrame();
588
589 // Return the temporary for Key whose version number is Version.
590 APValue *getTemporary(const void *Key, unsigned Version) {
591 MapKeyTy KV(Key, Version);
592 auto LB = Temporaries.lower_bound(KV);
593 if (LB != Temporaries.end() && LB->first == KV)
594 return &LB->second;
595 // Pair (Key,Version) wasn't found in the map. Check that no elements
596 // in the map have 'Key' as their key.
597 assert((LB == Temporaries.end() || LB->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB->
first.first != Key) && (LB == Temporaries.begin() || std
::prev(LB)->first.first != Key) && "Element with key 'Key' found in map"
) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "clang/lib/AST/ExprConstant.cpp", 599, __extension__ __PRETTY_FUNCTION__
))
598 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB->
first.first != Key) && (LB == Temporaries.begin() || std
::prev(LB)->first.first != Key) && "Element with key 'Key' found in map"
) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "clang/lib/AST/ExprConstant.cpp", 599, __extension__ __PRETTY_FUNCTION__
))
599 "Element with key 'Key' found in map")(static_cast <bool> ((LB == Temporaries.end() || LB->
first.first != Key) && (LB == Temporaries.begin() || std
::prev(LB)->first.first != Key) && "Element with key 'Key' found in map"
) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "clang/lib/AST/ExprConstant.cpp", 599, __extension__ __PRETTY_FUNCTION__
))
;
600 return nullptr;
601 }
602
603 // Return the current temporary for Key in the map.
604 APValue *getCurrentTemporary(const void *Key) {
605 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
606 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607 return &std::prev(UB)->second;
608 return nullptr;
609 }
610
611 // Return the version number of the current temporary for Key.
612 unsigned getCurrentTemporaryVersion(const void *Key) const {
613 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
614 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615 return std::prev(UB)->first.second;
616 return 0;
617 }
618
619 /// Allocate storage for an object of type T in this stack frame.
620 /// Populates LV with a handle to the created object. Key identifies
621 /// the temporary within the stack frame, and must not be reused without
622 /// bumping the temporary version number.
623 template<typename KeyT>
624 APValue &createTemporary(const KeyT *Key, QualType T,
625 ScopeKind Scope, LValue &LV);
626
627 /// Allocate storage for a parameter of a function call made in this frame.
628 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629
630 void describe(llvm::raw_ostream &OS) override;
631
632 Frame *getCaller() const override { return Caller; }
633 SourceLocation getCallLocation() const override { return CallLoc; }
634 const FunctionDecl *getCallee() const override { return Callee; }
635
636 bool isStdFunction() const {
637 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638 if (DC->isStdNamespace())
639 return true;
640 return false;
641 }
642
643 private:
644 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645 ScopeKind Scope);
646 };
647
648 /// Temporarily override 'this'.
649 class ThisOverrideRAII {
650 public:
651 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652 : Frame(Frame), OldThis(Frame.This) {
653 if (Enable)
654 Frame.This = NewThis;
655 }
656 ~ThisOverrideRAII() {
657 Frame.This = OldThis;
658 }
659 private:
660 CallStackFrame &Frame;
661 const LValue *OldThis;
662 };
663}
664
665static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666 const LValue &This, QualType ThisType);
667static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668 APValue::LValueBase LVBase, APValue &Value,
669 QualType T);
670
671namespace {
672 /// A cleanup, and a flag indicating whether it is lifetime-extended.
673 class Cleanup {
674 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675 APValue::LValueBase Base;
676 QualType T;
677
678 public:
679 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680 ScopeKind Scope)
681 : Value(Val, Scope), Base(Base), T(T) {}
682
683 /// Determine whether this cleanup should be performed at the end of the
684 /// given kind of scope.
685 bool isDestroyedAtEndOf(ScopeKind K) const {
686 return (int)Value.getInt() >= (int)K;
687 }
688 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689 if (RunDestructors) {
690 SourceLocation Loc;
691 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692 Loc = VD->getLocation();
693 else if (const Expr *E = Base.dyn_cast<const Expr*>())
694 Loc = E->getExprLoc();
695 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696 }
697 *Value.getPointer() = APValue();
698 return true;
699 }
700
701 bool hasSideEffect() {
702 return T.isDestructedType();
703 }
704 };
705
706 /// A reference to an object whose construction we are currently evaluating.
707 struct ObjectUnderConstruction {
708 APValue::LValueBase Base;
709 ArrayRef<APValue::LValuePathEntry> Path;
710 friend bool operator==(const ObjectUnderConstruction &LHS,
711 const ObjectUnderConstruction &RHS) {
712 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713 }
714 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715 return llvm::hash_combine(Obj.Base, Obj.Path);
716 }
717 };
718 enum class ConstructionPhase {
719 None,
720 Bases,
721 AfterBases,
722 AfterFields,
723 Destroying,
724 DestroyingBases
725 };
726}
727
728namespace llvm {
729template<> struct DenseMapInfo<ObjectUnderConstruction> {
730 using Base = DenseMapInfo<APValue::LValueBase>;
731 static ObjectUnderConstruction getEmptyKey() {
732 return {Base::getEmptyKey(), {}}; }
733 static ObjectUnderConstruction getTombstoneKey() {
734 return {Base::getTombstoneKey(), {}};
735 }
736 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737 return hash_value(Object);
738 }
739 static bool isEqual(const ObjectUnderConstruction &LHS,
740 const ObjectUnderConstruction &RHS) {
741 return LHS == RHS;
742 }
743};
744}
745
746namespace {
747 /// A dynamically-allocated heap object.
748 struct DynAlloc {
749 /// The value of this heap-allocated object.
750 APValue Value;
751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752 /// or a CallExpr (the latter is for direct calls to operator new inside
753 /// std::allocator<T>::allocate).
754 const Expr *AllocExpr = nullptr;
755
756 enum Kind {
757 New,
758 ArrayNew,
759 StdAllocator
760 };
761
762 /// Get the kind of the allocation. This must match between allocation
763 /// and deallocation.
764 Kind getKind() const {
765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766 return NE->isArray() ? ArrayNew : New;
767 assert(isa<CallExpr>(AllocExpr))(static_cast <bool> (isa<CallExpr>(AllocExpr)) ? void
(0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "clang/lib/AST/ExprConstant.cpp"
, 767, __extension__ __PRETTY_FUNCTION__))
;
768 return StdAllocator;
769 }
770 };
771
772 struct DynAllocOrder {
773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774 return L.getIndex() < R.getIndex();
775 }
776 };
777
778 /// EvalInfo - This is a private struct used by the evaluator to capture
779 /// information about a subexpression as it is folded. It retains information
780 /// about the AST context, but also maintains information about the folded
781 /// expression.
782 ///
783 /// If an expression could be evaluated, it is still possible it is not a C
784 /// "integer constant expression" or constant expression. If not, this struct
785 /// captures information about how and why not.
786 ///
787 /// One bit of information passed *into* the request for constant folding
788 /// indicates whether the subexpression is "evaluated" or not according to C
789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
790 /// evaluate the expression regardless of what the RHS is, but C only allows
791 /// certain things in certain situations.
792 class EvalInfo : public interp::State {
793 public:
794 ASTContext &Ctx;
795
796 /// EvalStatus - Contains information about the evaluation.
797 Expr::EvalStatus &EvalStatus;
798
799 /// CurrentCall - The top of the constexpr call stack.
800 CallStackFrame *CurrentCall;
801
802 /// CallStackDepth - The number of calls in the call stack right now.
803 unsigned CallStackDepth;
804
805 /// NextCallIndex - The next call index to assign.
806 unsigned NextCallIndex;
807
808 /// StepsLeft - The remaining number of evaluation steps we're permitted
809 /// to perform. This is essentially a limit for the number of statements
810 /// we will evaluate.
811 unsigned StepsLeft;
812
813 /// Enable the experimental new constant interpreter. If an expression is
814 /// not supported by the interpreter, an error is triggered.
815 bool EnableNewConstInterp;
816
817 /// BottomFrame - The frame in which evaluation started. This must be
818 /// initialized after CurrentCall and CallStackDepth.
819 CallStackFrame BottomFrame;
820
821 /// A stack of values whose lifetimes end at the end of some surrounding
822 /// evaluation frame.
823 llvm::SmallVector<Cleanup, 16> CleanupStack;
824
825 /// EvaluatingDecl - This is the declaration whose initializer is being
826 /// evaluated, if any.
827 APValue::LValueBase EvaluatingDecl;
828
829 enum class EvaluatingDeclKind {
830 None,
831 /// We're evaluating the construction of EvaluatingDecl.
832 Ctor,
833 /// We're evaluating the destruction of EvaluatingDecl.
834 Dtor,
835 };
836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837
838 /// EvaluatingDeclValue - This is the value being constructed for the
839 /// declaration whose initializer is being evaluated, if any.
840 APValue *EvaluatingDeclValue;
841
842 /// Set of objects that are currently being constructed.
843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844 ObjectsUnderConstruction;
845
846 /// Current heap allocations, along with the location where each was
847 /// allocated. We use std::map here because we need stable addresses
848 /// for the stored APValues.
849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850
851 /// The number of heap allocations performed so far in this evaluation.
852 unsigned NumHeapAllocs = 0;
853
854 struct EvaluatingConstructorRAII {
855 EvalInfo &EI;
856 ObjectUnderConstruction Object;
857 bool DidInsert;
858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859 bool HasBases)
860 : EI(EI), Object(Object) {
861 DidInsert =
862 EI.ObjectsUnderConstruction
863 .insert({Object, HasBases ? ConstructionPhase::Bases
864 : ConstructionPhase::AfterBases})
865 .second;
866 }
867 void finishedConstructingBases() {
868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869 }
870 void finishedConstructingFields() {
871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872 }
873 ~EvaluatingConstructorRAII() {
874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875 }
876 };
877
878 struct EvaluatingDestructorRAII {
879 EvalInfo &EI;
880 ObjectUnderConstruction Object;
881 bool DidInsert;
882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883 : EI(EI), Object(Object) {
884 DidInsert = EI.ObjectsUnderConstruction
885 .insert({Object, ConstructionPhase::Destroying})
886 .second;
887 }
888 void startedDestroyingBases() {
889 EI.ObjectsUnderConstruction[Object] =
890 ConstructionPhase::DestroyingBases;
891 }
892 ~EvaluatingDestructorRAII() {
893 if (DidInsert)
894 EI.ObjectsUnderConstruction.erase(Object);
895 }
896 };
897
898 ConstructionPhase
899 isEvaluatingCtorDtor(APValue::LValueBase Base,
900 ArrayRef<APValue::LValuePathEntry> Path) {
901 return ObjectsUnderConstruction.lookup({Base, Path});
902 }
903
904 /// If we're currently speculatively evaluating, the outermost call stack
905 /// depth at which we can mutate state, otherwise 0.
906 unsigned SpeculativeEvaluationDepth = 0;
907
908 /// The current array initialization index, if we're performing array
909 /// initialization.
910 uint64_t ArrayInitIndex = -1;
911
912 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913 /// notes attached to it will also be stored, otherwise they will not be.
914 bool HasActiveDiagnostic;
915
916 /// Have we emitted a diagnostic explaining why we couldn't constant
917 /// fold (not just why it's not strictly a constant expression)?
918 bool HasFoldFailureDiagnostic;
919
920 /// Whether or not we're in a context where the front end requires a
921 /// constant value.
922 bool InConstantContext;
923
924 /// Whether we're checking that an expression is a potential constant
925 /// expression. If so, do not fail on constructs that could become constant
926 /// later on (such as a use of an undefined global).
927 bool CheckingPotentialConstantExpression = false;
928
929 /// Whether we're checking for an expression that has undefined behavior.
930 /// If so, we will produce warnings if we encounter an operation that is
931 /// always undefined.
932 ///
933 /// Note that we still need to evaluate the expression normally when this
934 /// is set; this is used when evaluating ICEs in C.
935 bool CheckingForUndefinedBehavior = false;
936
937 enum EvaluationMode {
938 /// Evaluate as a constant expression. Stop if we find that the expression
939 /// is not a constant expression.
940 EM_ConstantExpression,
941
942 /// Evaluate as a constant expression. Stop if we find that the expression
943 /// is not a constant expression. Some expressions can be retried in the
944 /// optimizer if we don't constant fold them here, but in an unevaluated
945 /// context we try to fold them immediately since the optimizer never
946 /// gets a chance to look at it.
947 EM_ConstantExpressionUnevaluated,
948
949 /// Fold the expression to a constant. Stop if we hit a side-effect that
950 /// we can't model.
951 EM_ConstantFold,
952
953 /// Evaluate in any way we know how. Don't worry about side-effects that
954 /// can't be modeled.
955 EM_IgnoreSideEffects,
956 } EvalMode;
957
958 /// Are we checking whether the expression is a potential constant
959 /// expression?
960 bool checkingPotentialConstantExpression() const override {
961 return CheckingPotentialConstantExpression;
962 }
963
964 /// Are we checking an expression for overflow?
965 // FIXME: We should check for any kind of undefined or suspicious behavior
966 // in such constructs, not just overflow.
967 bool checkingForUndefinedBehavior() const override {
968 return CheckingForUndefinedBehavior;
969 }
970
971 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973 CallStackDepth(0), NextCallIndex(1),
974 StepsLeft(C.getLangOpts().ConstexprStepLimit),
975 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977 EvaluatingDecl((const ValueDecl *)nullptr),
978 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979 HasFoldFailureDiagnostic(false), InConstantContext(false),
980 EvalMode(Mode) {}
981
982 ~EvalInfo() {
983 discardCleanups();
984 }
985
986 ASTContext &getCtx() const override { return Ctx; }
987
988 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990 EvaluatingDecl = Base;
991 IsEvaluatingDecl = EDK;
992 EvaluatingDeclValue = &Value;
993 }
994
995 bool CheckCallLimit(SourceLocation Loc) {
996 // Don't perform any constexpr calls (other than the call we're checking)
997 // when checking a potential constant expression.
998 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999 return false;
1000 if (NextCallIndex == 0) {
1001 // NextCallIndex has wrapped around.
1002 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003 return false;
1004 }
1005 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006 return true;
1007 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008 << getLangOpts().ConstexprCallDepth;
1009 return false;
1010 }
1011
1012 std::pair<CallStackFrame *, unsigned>
1013 getCallFrameAndDepth(unsigned CallIndex) {
1014 assert(CallIndex && "no call index in getCallFrameAndDepth")(static_cast <bool> (CallIndex && "no call index in getCallFrameAndDepth"
) ? void (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\""
, "clang/lib/AST/ExprConstant.cpp", 1014, __extension__ __PRETTY_FUNCTION__
))
;
1015 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016 // be null in this loop.
1017 unsigned Depth = CallStackDepth;
1018 CallStackFrame *Frame = CurrentCall;
1019 while (Frame->Index > CallIndex) {
1020 Frame = Frame->Caller;
1021 --Depth;
1022 }
1023 if (Frame->Index == CallIndex)
1024 return {Frame, Depth};
1025 return {nullptr, 0};
1026 }
1027
1028 bool nextStep(const Stmt *S) {
1029 if (!StepsLeft) {
1030 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031 return false;
1032 }
1033 --StepsLeft;
1034 return true;
1035 }
1036
1037 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038
1039 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040 Optional<DynAlloc*> Result;
1041 auto It = HeapAllocs.find(DA);
1042 if (It != HeapAllocs.end())
1043 Result = &It->second;
1044 return Result;
1045 }
1046
1047 /// Get the allocated storage for the given parameter of the given call.
1048 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051 : nullptr;
1052 }
1053
1054 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055 struct StdAllocatorCaller {
1056 unsigned FrameIndex;
1057 QualType ElemType;
1058 explicit operator bool() const { return FrameIndex != 0; };
1059 };
1060
1061 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063 Call = Call->Caller) {
1064 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065 if (!MD)
1066 continue;
1067 const IdentifierInfo *FnII = MD->getIdentifier();
1068 if (!FnII || !FnII->isStr(FnName))
1069 continue;
1070
1071 const auto *CTSD =
1072 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073 if (!CTSD)
1074 continue;
1075
1076 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078 if (CTSD->isInStdNamespace() && ClassII &&
1079 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080 TAL[0].getKind() == TemplateArgument::Type)
1081 return {Call->Index, TAL[0].getAsType()};
1082 }
1083
1084 return {};
1085 }
1086
1087 void performLifetimeExtension() {
1088 // Disable the cleanups for lifetime-extended temporaries.
1089 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091 });
1092 }
1093
1094 /// Throw away any remaining cleanups at the end of evaluation. If any
1095 /// cleanups would have had a side-effect, note that as an unmodeled
1096 /// side-effect and return false. Otherwise, return true.
1097 bool discardCleanups() {
1098 for (Cleanup &C : CleanupStack) {
1099 if (C.hasSideEffect() && !noteSideEffect()) {
1100 CleanupStack.clear();
1101 return false;
1102 }
1103 }
1104 CleanupStack.clear();
1105 return true;
1106 }
1107
1108 private:
1109 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1110 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111
1112 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1113 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114
1115 void setFoldFailureDiagnostic(bool Flag) override {
1116 HasFoldFailureDiagnostic = Flag;
1117 }
1118
1119 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1120
1121 // If we have a prior diagnostic, it will be noting that the expression
1122 // isn't a constant expression. This diagnostic is more important,
1123 // unless we require this evaluation to produce a constant expression.
1124 //
1125 // FIXME: We might want to show both diagnostics to the user in
1126 // EM_ConstantFold mode.
1127 bool hasPriorDiagnostic() override {
1128 if (!EvalStatus.Diag->empty()) {
1129 switch (EvalMode) {
1130 case EM_ConstantFold:
1131 case EM_IgnoreSideEffects:
1132 if (!HasFoldFailureDiagnostic)
1133 break;
1134 // We've already failed to fold something. Keep that diagnostic.
1135 [[fallthrough]];
1136 case EM_ConstantExpression:
1137 case EM_ConstantExpressionUnevaluated:
1138 setActiveDiagnostic(false);
1139 return true;
1140 }
1141 }
1142 return false;
1143 }
1144
1145 unsigned getCallStackDepth() override { return CallStackDepth; }
1146
1147 public:
1148 /// Should we continue evaluation after encountering a side-effect that we
1149 /// couldn't model?
1150 bool keepEvaluatingAfterSideEffect() {
1151 switch (EvalMode) {
1152 case EM_IgnoreSideEffects:
1153 return true;
1154
1155 case EM_ConstantExpression:
1156 case EM_ConstantExpressionUnevaluated:
1157 case EM_ConstantFold:
1158 // By default, assume any side effect might be valid in some other
1159 // evaluation of this expression from a different context.
1160 return checkingPotentialConstantExpression() ||
1161 checkingForUndefinedBehavior();
1162 }
1163 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1163)
;
1164 }
1165
1166 /// Note that we have had a side-effect, and determine whether we should
1167 /// keep evaluating.
1168 bool noteSideEffect() {
1169 EvalStatus.HasSideEffects = true;
1170 return keepEvaluatingAfterSideEffect();
1171 }
1172
1173 /// Should we continue evaluation after encountering undefined behavior?
1174 bool keepEvaluatingAfterUndefinedBehavior() {
1175 switch (EvalMode) {
1176 case EM_IgnoreSideEffects:
1177 case EM_ConstantFold:
1178 return true;
1179
1180 case EM_ConstantExpression:
1181 case EM_ConstantExpressionUnevaluated:
1182 return checkingForUndefinedBehavior();
1183 }
1184 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1184)
;
1185 }
1186
1187 /// Note that we hit something that was technically undefined behavior, but
1188 /// that we can evaluate past it (such as signed overflow or floating-point
1189 /// division by zero.)
1190 bool noteUndefinedBehavior() override {
1191 EvalStatus.HasUndefinedBehavior = true;
1192 return keepEvaluatingAfterUndefinedBehavior();
1193 }
1194
1195 /// Should we continue evaluation as much as possible after encountering a
1196 /// construct which can't be reduced to a value?
1197 bool keepEvaluatingAfterFailure() const override {
1198 if (!StepsLeft)
1199 return false;
1200
1201 switch (EvalMode) {
1202 case EM_ConstantExpression:
1203 case EM_ConstantExpressionUnevaluated:
1204 case EM_ConstantFold:
1205 case EM_IgnoreSideEffects:
1206 return checkingPotentialConstantExpression() ||
1207 checkingForUndefinedBehavior();
1208 }
1209 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp"
, 1209)
;
1210 }
1211
1212 /// Notes that we failed to evaluate an expression that other expressions
1213 /// directly depend on, and determine if we should keep evaluating. This
1214 /// should only be called if we actually intend to keep evaluating.
1215 ///
1216 /// Call noteSideEffect() instead if we may be able to ignore the value that
1217 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218 ///
1219 /// (Foo(), 1) // use noteSideEffect
1220 /// (Foo() || true) // use noteSideEffect
1221 /// Foo() + 1 // use noteFailure
1222 [[nodiscard]] bool noteFailure() {
1223 // Failure when evaluating some expression often means there is some
1224 // subexpression whose evaluation was skipped. Therefore, (because we
1225 // don't track whether we skipped an expression when unwinding after an
1226 // evaluation failure) every evaluation failure that bubbles up from a
1227 // subexpression implies that a side-effect has potentially happened. We
1228 // skip setting the HasSideEffects flag to true until we decide to
1229 // continue evaluating after that point, which happens here.
1230 bool KeepGoing = keepEvaluatingAfterFailure();
1231 EvalStatus.HasSideEffects |= KeepGoing;
1232 return KeepGoing;
1233 }
1234
1235 class ArrayInitLoopIndex {
1236 EvalInfo &Info;
1237 uint64_t OuterIndex;
1238
1239 public:
1240 ArrayInitLoopIndex(EvalInfo &Info)
1241 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242 Info.ArrayInitIndex = 0;
1243 }
1244 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245
1246 operator uint64_t&() { return Info.ArrayInitIndex; }
1247 };
1248 };
1249
1250 /// Object used to treat all foldable expressions as constant expressions.
1251 struct FoldConstant {
1252 EvalInfo &Info;
1253 bool Enabled;
1254 bool HadNoPriorDiags;
1255 EvalInfo::EvaluationMode OldMode;
1256
1257 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258 : Info(Info),
1259 Enabled(Enabled),
1260 HadNoPriorDiags(Info.EvalStatus.Diag &&
1261 Info.EvalStatus.Diag->empty() &&
1262 !Info.EvalStatus.HasSideEffects),
1263 OldMode(Info.EvalMode) {
1264 if (Enabled)
1265 Info.EvalMode = EvalInfo::EM_ConstantFold;
1266 }
1267 void keepDiagnostics() { Enabled = false; }
1268 ~FoldConstant() {
1269 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270 !Info.EvalStatus.HasSideEffects)
1271 Info.EvalStatus.Diag->clear();
1272 Info.EvalMode = OldMode;
1273 }
1274 };
1275
1276 /// RAII object used to set the current evaluation mode to ignore
1277 /// side-effects.
1278 struct IgnoreSideEffectsRAII {
1279 EvalInfo &Info;
1280 EvalInfo::EvaluationMode OldMode;
1281 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282 : Info(Info), OldMode(Info.EvalMode) {
1283 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284 }
1285
1286 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287 };
1288
1289 /// RAII object used to optionally suppress diagnostics and side-effects from
1290 /// a speculative evaluation.
1291 class SpeculativeEvaluationRAII {
1292 EvalInfo *Info = nullptr;
1293 Expr::EvalStatus OldStatus;
1294 unsigned OldSpeculativeEvaluationDepth;
1295
1296 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297 Info = Other.Info;
1298 OldStatus = Other.OldStatus;
1299 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300 Other.Info = nullptr;
1301 }
1302
1303 void maybeRestoreState() {
1304 if (!Info)
1305 return;
1306
1307 Info->EvalStatus = OldStatus;
1308 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309 }
1310
1311 public:
1312 SpeculativeEvaluationRAII() = default;
1313
1314 SpeculativeEvaluationRAII(
1315 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316 : Info(&Info), OldStatus(Info.EvalStatus),
1317 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318 Info.EvalStatus.Diag = NewDiag;
1319 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320 }
1321
1322 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324 moveFromAndCancel(std::move(Other));
1325 }
1326
1327 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328 maybeRestoreState();
1329 moveFromAndCancel(std::move(Other));
1330 return *this;
1331 }
1332
1333 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334 };
1335
1336 /// RAII object wrapping a full-expression or block scope, and handling
1337 /// the ending of the lifetime of temporaries created within it.
1338 template<ScopeKind Kind>
1339 class ScopeRAII {
1340 EvalInfo &Info;
1341 unsigned OldStackSize;
1342 public:
1343 ScopeRAII(EvalInfo &Info)
1344 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345 // Push a new temporary version. This is needed to distinguish between
1346 // temporaries created in different iterations of a loop.
1347 Info.CurrentCall->pushTempVersion();
1348 }
1349 bool destroy(bool RunDestructors = true) {
1350 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351 OldStackSize = -1U;
1352 return OK;
1353 }
1354 ~ScopeRAII() {
1355 if (OldStackSize != -1U)
1356 destroy(false);
1357 // Body moved to a static method to encourage the compiler to inline away
1358 // instances of this class.
1359 Info.CurrentCall->popTempVersion();
1360 }
1361 private:
1362 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363 unsigned OldStackSize) {
1364 assert(OldStackSize <= Info.CleanupStack.size() &&(static_cast <bool> (OldStackSize <= Info.CleanupStack
.size() && "running cleanups out of order?") ? void (
0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\""
, "clang/lib/AST/ExprConstant.cpp", 1365, __extension__ __PRETTY_FUNCTION__
))
1365 "running cleanups out of order?")(static_cast <bool> (OldStackSize <= Info.CleanupStack
.size() && "running cleanups out of order?") ? void (
0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\""
, "clang/lib/AST/ExprConstant.cpp", 1365, __extension__ __PRETTY_FUNCTION__
))
;
1366
1367 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368 // for a full-expression scope.
1369 bool Success = true;
1370 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373 Success = false;
1374 break;
1375 }
1376 }
1377 }
1378
1379 // Compact any retained cleanups.
1380 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381 if (Kind != ScopeKind::Block)
1382 NewEnd =
1383 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384 return C.isDestroyedAtEndOf(Kind);
1385 });
1386 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387 return Success;
1388 }
1389 };
1390 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393}
1394
1395bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396 CheckSubobjectKind CSK) {
1397 if (Invalid)
1398 return false;
1399 if (isOnePastTheEnd()) {
1400 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401 << CSK;
1402 setInvalid();
1403 return false;
1404 }
1405 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406 // must actually be at least one array element; even a VLA cannot have a
1407 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408 return true;
1409}
1410
1411void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412 const Expr *E) {
1413 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414 // Do not set the designator as invalid: we can represent this situation,
1415 // and correct handling of __builtin_object_size requires us to do so.
1416}
1417
1418void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419 const Expr *E,
1420 const APSInt &N) {
1421 // If we're complaining, we must be able to statically determine the size of
1422 // the most derived array.
1423 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424 Info.CCEDiag(E, diag::note_constexpr_array_index)
1425 << N << /*array*/ 0
1426 << static_cast<unsigned>(getMostDerivedArraySize());
1427 else
1428 Info.CCEDiag(E, diag::note_constexpr_array_index)
1429 << N << /*non-array*/ 1;
1430 setInvalid();
1431}
1432
1433CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434 const FunctionDecl *Callee, const LValue *This,
1435 CallRef Call)
1436 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438 Info.CurrentCall = this;
1439 ++Info.CallStackDepth;
1440}
1441
1442CallStackFrame::~CallStackFrame() {
1443 assert(Info.CurrentCall == this && "calls retired out of order")(static_cast <bool> (Info.CurrentCall == this &&
"calls retired out of order") ? void (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\""
, "clang/lib/AST/ExprConstant.cpp", 1443, __extension__ __PRETTY_FUNCTION__
))
;
1444 --Info.CallStackDepth;
1445 Info.CurrentCall = Caller;
1446}
1447
1448static bool isRead(AccessKinds AK) {
1449 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450}
1451
1452static bool isModification(AccessKinds AK) {
1453 switch (AK) {
1454 case AK_Read:
1455 case AK_ReadObjectRepresentation:
1456 case AK_MemberCall:
1457 case AK_DynamicCast:
1458 case AK_TypeId:
1459 return false;
1460 case AK_Assign:
1461 case AK_Increment:
1462 case AK_Decrement:
1463 case AK_Construct:
1464 case AK_Destroy:
1465 return true;
1466 }
1467 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp"
, 1467)
;
1468}
1469
1470static bool isAnyAccess(AccessKinds AK) {
1471 return isRead(AK) || isModification(AK);
1472}
1473
1474/// Is this an access per the C++ definition?
1475static bool isFormalAccess(AccessKinds AK) {
1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477}
1478
1479/// Is this kind of axcess valid on an indeterminate object value?
1480static bool isValidIndeterminateAccess(AccessKinds AK) {
1481 switch (AK) {
1482 case AK_Read:
1483 case AK_Increment:
1484 case AK_Decrement:
1485 // These need the object's value.
1486 return false;
1487
1488 case AK_ReadObjectRepresentation:
1489 case AK_Assign:
1490 case AK_Construct:
1491 case AK_Destroy:
1492 // Construction and destruction don't need the value.
1493 return true;
1494
1495 case AK_MemberCall:
1496 case AK_DynamicCast:
1497 case AK_TypeId:
1498 // These aren't really meaningful on scalars.
1499 return true;
1500 }
1501 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp"
, 1501)
;
1502}
1503
1504namespace {
1505 struct ComplexValue {
1506 private:
1507 bool IsInt;
1508
1509 public:
1510 APSInt IntReal, IntImag;
1511 APFloat FloatReal, FloatImag;
1512
1513 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514
1515 void makeComplexFloat() { IsInt = false; }
1516 bool isComplexFloat() const { return !IsInt; }
1517 APFloat &getComplexFloatReal() { return FloatReal; }
1518 APFloat &getComplexFloatImag() { return FloatImag; }
1519
1520 void makeComplexInt() { IsInt = true; }
1521 bool isComplexInt() const { return IsInt; }
1522 APSInt &getComplexIntReal() { return IntReal; }
1523 APSInt &getComplexIntImag() { return IntImag; }
1524
1525 void moveInto(APValue &v) const {
1526 if (isComplexFloat())
1527 v = APValue(FloatReal, FloatImag);
1528 else
1529 v = APValue(IntReal, IntImag);
1530 }
1531 void setFrom(const APValue &v) {
1532 assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt
()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()"
, "clang/lib/AST/ExprConstant.cpp", 1532, __extension__ __PRETTY_FUNCTION__
))
;
1533 if (v.isComplexFloat()) {
1534 makeComplexFloat();
1535 FloatReal = v.getComplexFloatReal();
1536 FloatImag = v.getComplexFloatImag();
1537 } else {
1538 makeComplexInt();
1539 IntReal = v.getComplexIntReal();
1540 IntImag = v.getComplexIntImag();
1541 }
1542 }
1543 };
1544
1545 struct LValue {
1546 APValue::LValueBase Base;
1547 CharUnits Offset;
1548 SubobjectDesignator Designator;
1549 bool IsNullPtr : 1;
1550 bool InvalidBase : 1;
1551
1552 const APValue::LValueBase getLValueBase() const { return Base; }
1553 CharUnits &getLValueOffset() { return Offset; }
1554 const CharUnits &getLValueOffset() const { return Offset; }
1555 SubobjectDesignator &getLValueDesignator() { return Designator; }
1556 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557 bool isNullPointer() const { return IsNullPtr;}
1558
1559 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560 unsigned getLValueVersion() const { return Base.getVersion(); }
1561
1562 void moveInto(APValue &V) const {
1563 if (Designator.Invalid)
1564 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565 else {
1566 assert(!InvalidBase && "APValues can't handle invalid LValue bases")(static_cast <bool> (!InvalidBase && "APValues can't handle invalid LValue bases"
) ? void (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\""
, "clang/lib/AST/ExprConstant.cpp", 1566, __extension__ __PRETTY_FUNCTION__
))
;
1567 V = APValue(Base, Offset, Designator.Entries,
1568 Designator.IsOnePastTheEnd, IsNullPtr);
1569 }
1570 }
1571 void setFrom(ASTContext &Ctx, const APValue &V) {
1572 assert(V.isLValue() && "Setting LValue from a non-LValue?")(static_cast <bool> (V.isLValue() && "Setting LValue from a non-LValue?"
) ? void (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\""
, "clang/lib/AST/ExprConstant.cpp", 1572, __extension__ __PRETTY_FUNCTION__
))
;
1573 Base = V.getLValueBase();
1574 Offset = V.getLValueOffset();
1575 InvalidBase = false;
1576 Designator = SubobjectDesignator(Ctx, V);
1577 IsNullPtr = V.isNullPointer();
1578 }
1579
1580 void set(APValue::LValueBase B, bool BInvalid = false) {
1581#ifndef NDEBUG
1582 // We only allow a few types of invalid bases. Enforce that here.
1583 if (BInvalid) {
1584 const auto *E = B.get<const Expr *>();
1585 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall
(E)) && "Unexpected type of invalid base") ? void (0)
: __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "clang/lib/AST/ExprConstant.cpp", 1586, __extension__ __PRETTY_FUNCTION__
))
1586 "Unexpected type of invalid base")(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall
(E)) && "Unexpected type of invalid base") ? void (0)
: __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "clang/lib/AST/ExprConstant.cpp", 1586, __extension__ __PRETTY_FUNCTION__
))
;
1587 }
1588#endif
1589
1590 Base = B;
1591 Offset = CharUnits::fromQuantity(0);
1592 InvalidBase = BInvalid;
1593 Designator = SubobjectDesignator(getType(B));
1594 IsNullPtr = false;
1595 }
1596
1597 void setNull(ASTContext &Ctx, QualType PointerTy) {
1598 Base = (const ValueDecl *)nullptr;
1599 Offset =
1600 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601 InvalidBase = false;
1602 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603 IsNullPtr = true;
1604 }
1605
1606 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607 set(B, true);
1608 }
1609
1610 std::string toString(ASTContext &Ctx, QualType T) const {
1611 APValue Printable;
1612 moveInto(Printable);
1613 return Printable.getAsString(Ctx, T);
1614 }
1615
1616 private:
1617 // Check that this LValue is not based on a null pointer. If it is, produce
1618 // a diagnostic and mark the designator as invalid.
1619 template <typename GenDiagType>
1620 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621 if (Designator.Invalid)
1622 return false;
1623 if (IsNullPtr) {
1624 GenDiag();
1625 Designator.setInvalid();
1626 return false;
1627 }
1628 return true;
1629 }
1630
1631 public:
1632 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633 CheckSubobjectKind CSK) {
1634 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636 });
1637 }
1638
1639 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640 AccessKinds AK) {
1641 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643 });
1644 }
1645
1646 // Check this LValue refers to an object. If not, set the designator to be
1647 // invalid and emit a diagnostic.
1648 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650 Designator.checkSubobject(Info, E, CSK);
1651 }
1652
1653 void addDecl(EvalInfo &Info, const Expr *E,
1654 const Decl *D, bool Virtual = false) {
1655 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656 Designator.addDeclUnchecked(D, Virtual);
1657 }
1658 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659 if (!Designator.Entries.empty()) {
1660 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661 Designator.setInvalid();
1662 return;
1663 }
1664 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())(static_cast <bool> (getType(Base)->isPointerType() ||
getType(Base)->isArrayType()) ? void (0) : __assert_fail (
"getType(Base)->isPointerType() || getType(Base)->isArrayType()"
, "clang/lib/AST/ExprConstant.cpp", 1665, __extension__ __PRETTY_FUNCTION__
))
;
1666 Designator.FirstEntryIsAnUnsizedArray = true;
1667 Designator.addUnsizedArrayUnchecked(ElemTy);
1668 }
1669 }
1670 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672 Designator.addArrayUnchecked(CAT);
1673 }
1674 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676 Designator.addComplexUnchecked(EltTy, Imag);
1677 }
1678 void clearIsNullPointer() {
1679 IsNullPtr = false;
1680 }
1681 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682 const APSInt &Index, CharUnits ElementSize) {
1683 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684 // but we're not required to diagnose it and it's valid in C++.)
1685 if (!Index)
1686 return;
1687
1688 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690 // offsets.
1691 uint64_t Offset64 = Offset.getQuantity();
1692 uint64_t ElemSize64 = ElementSize.getQuantity();
1693 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695
1696 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697 Designator.adjustIndex(Info, E, Index);
1698 clearIsNullPointer();
1699 }
1700 void adjustOffset(CharUnits N) {
1701 Offset += N;
1702 if (N.getQuantity())
1703 clearIsNullPointer();
1704 }
1705 };
1706
1707 struct MemberPtr {
1708 MemberPtr() {}
1709 explicit MemberPtr(const ValueDecl *Decl)
1710 : DeclAndIsDerivedMember(Decl, false) {}
1711
1712 /// The member or (direct or indirect) field referred to by this member
1713 /// pointer, or 0 if this is a null member pointer.
1714 const ValueDecl *getDecl() const {
1715 return DeclAndIsDerivedMember.getPointer();
1716 }
1717 /// Is this actually a member of some type derived from the relevant class?
1718 bool isDerivedMember() const {
1719 return DeclAndIsDerivedMember.getInt();
1720 }
1721 /// Get the class which the declaration actually lives in.
1722 const CXXRecordDecl *getContainingRecord() const {
1723 return cast<CXXRecordDecl>(
1724 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725 }
1726
1727 void moveInto(APValue &V) const {
1728 V = APValue(getDecl(), isDerivedMember(), Path);
1729 }
1730 void setFrom(const APValue &V) {
1731 assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail
("V.isMemberPointer()", "clang/lib/AST/ExprConstant.cpp", 1731
, __extension__ __PRETTY_FUNCTION__))
;
1732 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734 Path.clear();
1735 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736 Path.insert(Path.end(), P.begin(), P.end());
1737 }
1738
1739 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740 /// whether the member is a member of some class derived from the class type
1741 /// of the member pointer.
1742 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743 /// Path - The path of base/derived classes from the member declaration's
1744 /// class (exclusive) to the class type of the member pointer (inclusive).
1745 SmallVector<const CXXRecordDecl*, 4> Path;
1746
1747 /// Perform a cast towards the class of the Decl (either up or down the
1748 /// hierarchy).
1749 bool castBack(const CXXRecordDecl *Class) {
1750 assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail
("!Path.empty()", "clang/lib/AST/ExprConstant.cpp", 1750, __extension__
__PRETTY_FUNCTION__))
;
1751 const CXXRecordDecl *Expected;
1752 if (Path.size() >= 2)
1753 Expected = Path[Path.size() - 2];
1754 else
1755 Expected = getContainingRecord();
1756 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758 // if B does not contain the original member and is not a base or
1759 // derived class of the class containing the original member, the result
1760 // of the cast is undefined.
1761 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762 // (D::*). We consider that to be a language defect.
1763 return false;
1764 }
1765 Path.pop_back();
1766 return true;
1767 }
1768 /// Perform a base-to-derived member pointer cast.
1769 bool castToDerived(const CXXRecordDecl *Derived) {
1770 if (!getDecl())
1771 return true;
1772 if (!isDerivedMember()) {
1773 Path.push_back(Derived);
1774 return true;
1775 }
1776 if (!castBack(Derived))
1777 return false;
1778 if (Path.empty())
1779 DeclAndIsDerivedMember.setInt(false);
1780 return true;
1781 }
1782 /// Perform a derived-to-base member pointer cast.
1783 bool castToBase(const CXXRecordDecl *Base) {
1784 if (!getDecl())
1785 return true;
1786 if (Path.empty())
1787 DeclAndIsDerivedMember.setInt(true);
1788 if (isDerivedMember()) {
1789 Path.push_back(Base);
1790 return true;
1791 }
1792 return castBack(Base);
1793 }
1794 };
1795
1796 /// Compare two member pointers, which are assumed to be of the same type.
1797 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798 if (!LHS.getDecl() || !RHS.getDecl())
1799 return !LHS.getDecl() && !RHS.getDecl();
1800 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801 return false;
1802 return LHS.Path == RHS.Path;
1803 }
1804}
1805
1806static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808 const LValue &This, const Expr *E,
1809 bool AllowNonLiteralTypes = false);
1810static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811 bool InvalidBaseOK = false);
1812static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813 bool InvalidBaseOK = false);
1814static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815 EvalInfo &Info);
1816static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819 EvalInfo &Info);
1820static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823 EvalInfo &Info);
1824static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826 EvalInfo &Info);
1827
1828/// Evaluate an integer or fixed point expression into an APResult.
1829static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830 EvalInfo &Info);
1831
1832/// Evaluate only a fixed point expression into an APResult.
1833static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834 EvalInfo &Info);
1835
1836//===----------------------------------------------------------------------===//
1837// Misc utilities
1838//===----------------------------------------------------------------------===//
1839
1840/// Negate an APSInt in place, converting it to a signed form if necessary, and
1841/// preserving its value (by extending by up to one bit as needed).
1842static void negateAsSigned(APSInt &Int) {
1843 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844 Int = Int.extend(Int.getBitWidth() + 1);
1845 Int.setIsSigned(true);
1846 }
1847 Int = -Int;
1848}
1849
1850template<typename KeyT>
1851APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852 ScopeKind Scope, LValue &LV) {
1853 unsigned Version = getTempVersion();
1854 APValue::LValueBase Base(Key, Index, Version);
1855 LV.set(Base);
1856 return createLocal(Base, Key, T, Scope);
1857}
1858
1859/// Allocate storage for a parameter of a function call made in this frame.
1860APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861 LValue &LV) {
1862 assert(Args.CallIndex == Index && "creating parameter in wrong frame")(static_cast <bool> (Args.CallIndex == Index &&
"creating parameter in wrong frame") ? void (0) : __assert_fail
("Args.CallIndex == Index && \"creating parameter in wrong frame\""
, "clang/lib/AST/ExprConstant.cpp", 1862, __extension__ __PRETTY_FUNCTION__
))
;
1863 APValue::LValueBase Base(PVD, Index, Args.Version);
1864 LV.set(Base);
1865 // We always destroy parameters at the end of the call, even if we'd allow
1866 // them to live to the end of the full-expression at runtime, in order to
1867 // give portable results and match other compilers.
1868 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869}
1870
1871APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872 QualType T, ScopeKind Scope) {
1873 assert(Base.getCallIndex() == Index && "lvalue for wrong frame")(static_cast <bool> (Base.getCallIndex() == Index &&
"lvalue for wrong frame") ? void (0) : __assert_fail ("Base.getCallIndex() == Index && \"lvalue for wrong frame\""
, "clang/lib/AST/ExprConstant.cpp", 1873, __extension__ __PRETTY_FUNCTION__
))
;
1874 unsigned Version = Base.getVersion();
1875 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876 assert(Result.isAbsent() && "local created multiple times")(static_cast <bool> (Result.isAbsent() && "local created multiple times"
) ? void (0) : __assert_fail ("Result.isAbsent() && \"local created multiple times\""
, "clang/lib/AST/ExprConstant.cpp", 1876, __extension__ __PRETTY_FUNCTION__
))
;
1877
1878 // If we're creating a local immediately in the operand of a speculative
1879 // evaluation, don't register a cleanup to be run outside the speculative
1880 // evaluation context, since we won't actually be able to initialize this
1881 // object.
1882 if (Index <= Info.SpeculativeEvaluationDepth) {
1883 if (T.isDestructedType())
1884 Info.noteSideEffect();
1885 } else {
1886 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887 }
1888 return Result;
1889}
1890
1891APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894 return nullptr;
1895 }
1896
1897 DynamicAllocLValue DA(NumHeapAllocs++);
1898 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900 std::forward_as_tuple(DA), std::tuple<>());
1901 assert(Result.second && "reused a heap alloc index?")(static_cast <bool> (Result.second && "reused a heap alloc index?"
) ? void (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\""
, "clang/lib/AST/ExprConstant.cpp", 1901, __extension__ __PRETTY_FUNCTION__
))
;
1902 Result.first->second.AllocExpr = E;
1903 return &Result.first->second.Value;
1904}
1905
1906/// Produce a string describing the given constexpr call.
1907void CallStackFrame::describe(raw_ostream &Out) {
1908 unsigned ArgIndex = 0;
1909 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910 !isa<CXXConstructorDecl>(Callee) &&
1911 cast<CXXMethodDecl>(Callee)->isInstance();
1912
1913 if (!IsMemberCall)
1914 Out << *Callee << '(';
1915
1916 if (This && IsMemberCall) {
1917 APValue Val;
1918 This->moveInto(Val);
1919 Val.printPretty(Out, Info.Ctx,
1920 This->Designator.MostDerivedType);
1921 // FIXME: Add parens around Val if needed.
1922 Out << "->" << *Callee << '(';
1923 IsMemberCall = false;
1924 }
1925
1926 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928 if (ArgIndex > (unsigned)IsMemberCall)
1929 Out << ", ";
1930
1931 const ParmVarDecl *Param = *I;
1932 APValue *V = Info.getParamSlot(Arguments, Param);
1933 if (V)
1934 V->printPretty(Out, Info.Ctx, Param->getType());
1935 else
1936 Out << "<...>";
1937
1938 if (ArgIndex == 0 && IsMemberCall)
1939 Out << "->" << *Callee << '(';
1940 }
1941
1942 Out << ')';
1943}
1944
1945/// Evaluate an expression to see if it had side-effects, and discard its
1946/// result.
1947/// \return \c true if the caller should keep evaluating.
1948static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
;
1950 APValue Scratch;
1951 if (!Evaluate(Scratch, Info, E))
1952 // We don't need the value, but we might have skipped a side effect here.
1953 return Info.noteSideEffect();
1954 return true;
1955}
1956
1957/// Should this call expression be treated as a constant?
1958static bool IsConstantCall(const CallExpr *E) {
1959 unsigned Builtin = E->getBuiltinCallee();
1960 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962 Builtin == Builtin::BI__builtin_function_start);
1963}
1964
1965static bool IsGlobalLValue(APValue::LValueBase B) {
1966 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967 // constant expression of pointer type that evaluates to...
1968
1969 // ... a null pointer value, or a prvalue core constant expression of type
1970 // std::nullptr_t.
1971 if (!B) return true;
1972
1973 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974 // ... the address of an object with static storage duration,
1975 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976 return VD->hasGlobalStorage();
1977 if (isa<TemplateParamObjectDecl>(D))
1978 return true;
1979 // ... the address of a function,
1980 // ... the address of a GUID [MS extension],
1981 // ... the address of an unnamed global constant
1982 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1983 }
1984
1985 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1986 return true;
1987
1988 const Expr *E = B.get<const Expr*>();
1989 switch (E->getStmtClass()) {
1990 default:
1991 return false;
1992 case Expr::CompoundLiteralExprClass: {
1993 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1994 return CLE->isFileScope() && CLE->isLValue();
1995 }
1996 case Expr::MaterializeTemporaryExprClass:
1997 // A materialized temporary might have been lifetime-extended to static
1998 // storage duration.
1999 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2000 // A string literal has static storage duration.
2001 case Expr::StringLiteralClass:
2002 case Expr::PredefinedExprClass:
2003 case Expr::ObjCStringLiteralClass:
2004 case Expr::ObjCEncodeExprClass:
2005 return true;
2006 case Expr::ObjCBoxedExprClass:
2007 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2008 case Expr::CallExprClass:
2009 return IsConstantCall(cast<CallExpr>(E));
2010 // For GCC compatibility, &&label has static storage duration.
2011 case Expr::AddrLabelExprClass:
2012 return true;
2013 // A Block literal expression may be used as the initialization value for
2014 // Block variables at global or local static scope.
2015 case Expr::BlockExprClass:
2016 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2017 // The APValue generated from a __builtin_source_location will be emitted as a
2018 // literal.
2019 case Expr::SourceLocExprClass:
2020 return true;
2021 case Expr::ImplicitValueInitExprClass:
2022 // FIXME:
2023 // We can never form an lvalue with an implicit value initialization as its
2024 // base through expression evaluation, so these only appear in one case: the
2025 // implicit variable declaration we invent when checking whether a constexpr
2026 // constructor can produce a constant expression. We must assume that such
2027 // an expression might be a global lvalue.
2028 return true;
2029 }
2030}
2031
2032static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2033 return LVal.Base.dyn_cast<const ValueDecl*>();
2034}
2035
2036static bool IsLiteralLValue(const LValue &Value) {
2037 if (Value.getLValueCallIndex())
2038 return false;
2039 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2040 return E && !isa<MaterializeTemporaryExpr>(E);
2041}
2042
2043static bool IsWeakLValue(const LValue &Value) {
2044 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045 return Decl && Decl->isWeak();
2046}
2047
2048static bool isZeroSized(const LValue &Value) {
2049 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2050 if (Decl && isa<VarDecl>(Decl)) {
2051 QualType Ty = Decl->getType();
2052 if (Ty->isArrayType())
2053 return Ty->isIncompleteType() ||
2054 Decl->getASTContext().getTypeSize(Ty) == 0;
2055 }
2056 return false;
2057}
2058
2059static bool HasSameBase(const LValue &A, const LValue &B) {
2060 if (!A.getLValueBase())
2061 return !B.getLValueBase();
2062 if (!B.getLValueBase())
2063 return false;
2064
2065 if (A.getLValueBase().getOpaqueValue() !=
2066 B.getLValueBase().getOpaqueValue())
2067 return false;
2068
2069 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2070 A.getLValueVersion() == B.getLValueVersion();
2071}
2072
2073static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2074 assert(Base && "no location for a null lvalue")(static_cast <bool> (Base && "no location for a null lvalue"
) ? void (0) : __assert_fail ("Base && \"no location for a null lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2074, __extension__ __PRETTY_FUNCTION__
))
;
2075 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2076
2077 // For a parameter, find the corresponding call stack frame (if it still
2078 // exists), and point at the parameter of the function definition we actually
2079 // invoked.
2080 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2081 unsigned Idx = PVD->getFunctionScopeIndex();
2082 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2083 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2084 F->Arguments.Version == Base.getVersion() && F->Callee &&
2085 Idx < F->Callee->getNumParams()) {
2086 VD = F->Callee->getParamDecl(Idx);
2087 break;
2088 }
2089 }
2090 }
2091
2092 if (VD)
2093 Info.Note(VD->getLocation(), diag::note_declared_at);
2094 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2095 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2096 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2097 // FIXME: Produce a note for dangling pointers too.
2098 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2099 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2100 diag::note_constexpr_dynamic_alloc_here);
2101 }
2102 // We have no information to show for a typeid(T) object.
2103}
2104
2105enum class CheckEvaluationResultKind {
2106 ConstantExpression,
2107 FullyInitialized,
2108};
2109
2110/// Materialized temporaries that we've already checked to determine if they're
2111/// initializsed by a constant expression.
2112using CheckedTemporaries =
2113 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2114
2115static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2116 EvalInfo &Info, SourceLocation DiagLoc,
2117 QualType Type, const APValue &Value,
2118 ConstantExprKind Kind,
2119 SourceLocation SubobjectLoc,
2120 CheckedTemporaries &CheckedTemps);
2121
2122/// Check that this reference or pointer core constant expression is a valid
2123/// value for an address or reference constant expression. Return true if we
2124/// can fold this expression, whether or not it's a constant expression.
2125static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2126 QualType Type, const LValue &LVal,
2127 ConstantExprKind Kind,
2128 CheckedTemporaries &CheckedTemps) {
2129 bool IsReferenceType = Type->isReferenceType();
2130
2131 APValue::LValueBase Base = LVal.getLValueBase();
2132 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2133
2134 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2135 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2136
2137 // Additional restrictions apply in a template argument. We only enforce the
2138 // C++20 restrictions here; additional syntactic and semantic restrictions
2139 // are applied elsewhere.
2140 if (isTemplateArgument(Kind)) {
2141 int InvalidBaseKind = -1;
2142 StringRef Ident;
2143 if (Base.is<TypeInfoLValue>())
2144 InvalidBaseKind = 0;
2145 else if (isa_and_nonnull<StringLiteral>(BaseE))
2146 InvalidBaseKind = 1;
2147 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2148 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2149 InvalidBaseKind = 2;
2150 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2151 InvalidBaseKind = 3;
2152 Ident = PE->getIdentKindName();
2153 }
2154
2155 if (InvalidBaseKind != -1) {
2156 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2157 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2158 << Ident;
2159 return false;
2160 }
2161 }
2162
2163 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2164 if (FD->isConsteval()) {
2165 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2166 << !Type->isAnyPointerType();
2167 Info.Note(FD->getLocation(), diag::note_declared_at);
2168 return false;
2169 }
2170 }
2171
2172 // Check that the object is a global. Note that the fake 'this' object we
2173 // manufacture when checking potential constant expressions is conservatively
2174 // assumed to be global here.
2175 if (!IsGlobalLValue(Base)) {
2176 if (Info.getLangOpts().CPlusPlus11) {
2177 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2178 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2179 << BaseVD;
2180 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2181 if (VarD && VarD->isConstexpr()) {
2182 // Non-static local constexpr variables have unintuitive semantics:
2183 // constexpr int a = 1;
2184 // constexpr const int *p = &a;
2185 // ... is invalid because the address of 'a' is not constant. Suggest
2186 // adding a 'static' in this case.
2187 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2188 << VarD
2189 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2190 } else {
2191 NoteLValueLocation(Info, Base);
2192 }
2193 } else {
2194 Info.FFDiag(Loc);
2195 }
2196 // Don't allow references to temporaries to escape.
2197 return false;
2198 }
2199 assert((Info.checkingPotentialConstantExpression() ||(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2201, __extension__ __PRETTY_FUNCTION__
))
2200 LVal.getLValueCallIndex() == 0) &&(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2201, __extension__ __PRETTY_FUNCTION__
))
2201 "have call index for global lvalue")(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "clang/lib/AST/ExprConstant.cpp", 2201, __extension__ __PRETTY_FUNCTION__
))
;
2202
2203 if (Base.is<DynamicAllocLValue>()) {
2204 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2205 << IsReferenceType << !Designator.Entries.empty();
2206 NoteLValueLocation(Info, Base);
2207 return false;
2208 }
2209
2210 if (BaseVD) {
2211 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2212 // Check if this is a thread-local variable.
2213 if (Var->getTLSKind())
2214 // FIXME: Diagnostic!
2215 return false;
2216
2217 // A dllimport variable never acts like a constant, unless we're
2218 // evaluating a value for use only in name mangling.
2219 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2220 // FIXME: Diagnostic!
2221 return false;
2222
2223 // In CUDA/HIP device compilation, only device side variables have
2224 // constant addresses.
2225 if (Info.getCtx().getLangOpts().CUDA &&
2226 Info.getCtx().getLangOpts().CUDAIsDevice &&
2227 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2228 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2229 !Var->hasAttr<CUDAConstantAttr>() &&
2230 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2231 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2232 Var->hasAttr<HIPManagedAttr>())
2233 return false;
2234 }
2235 }
2236 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2237 // __declspec(dllimport) must be handled very carefully:
2238 // We must never initialize an expression with the thunk in C++.
2239 // Doing otherwise would allow the same id-expression to yield
2240 // different addresses for the same function in different translation
2241 // units. However, this means that we must dynamically initialize the
2242 // expression with the contents of the import address table at runtime.
2243 //
2244 // The C language has no notion of ODR; furthermore, it has no notion of
2245 // dynamic initialization. This means that we are permitted to
2246 // perform initialization with the address of the thunk.
2247 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2248 FD->hasAttr<DLLImportAttr>())
2249 // FIXME: Diagnostic!
2250 return false;
2251 }
2252 } else if (const auto *MTE =
2253 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2254 if (CheckedTemps.insert(MTE).second) {
2255 QualType TempType = getType(Base);
2256 if (TempType.isDestructedType()) {
2257 Info.FFDiag(MTE->getExprLoc(),
2258 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2259 << TempType;
2260 return false;
2261 }
2262
2263 APValue *V = MTE->getOrCreateValue(false);
2264 assert(V && "evasluation result refers to uninitialised temporary")(static_cast <bool> (V && "evasluation result refers to uninitialised temporary"
) ? void (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\""
, "clang/lib/AST/ExprConstant.cpp", 2264, __extension__ __PRETTY_FUNCTION__
))
;
2265 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2266 Info, MTE->getExprLoc(), TempType, *V,
2267 Kind, SourceLocation(), CheckedTemps))
2268 return false;
2269 }
2270 }
2271
2272 // Allow address constant expressions to be past-the-end pointers. This is
2273 // an extension: the standard requires them to point to an object.
2274 if (!IsReferenceType)
2275 return true;
2276
2277 // A reference constant expression must refer to an object.
2278 if (!Base) {
2279 // FIXME: diagnostic
2280 Info.CCEDiag(Loc);
2281 return true;
2282 }
2283
2284 // Does this refer one past the end of some object?
2285 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2286 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2287 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2288 NoteLValueLocation(Info, Base);
2289 }
2290
2291 return true;
2292}
2293
2294/// Member pointers are constant expressions unless they point to a
2295/// non-virtual dllimport member function.
2296static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2297 SourceLocation Loc,
2298 QualType Type,
2299 const APValue &Value,
2300 ConstantExprKind Kind) {
2301 const ValueDecl *Member = Value.getMemberPointerDecl();
2302 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2303 if (!FD)
2304 return true;
2305 if (FD->isConsteval()) {
2306 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2307 Info.Note(FD->getLocation(), diag::note_declared_at);
2308 return false;
2309 }
2310 return isForManglingOnly(Kind) || FD->isVirtual() ||
2311 !FD->hasAttr<DLLImportAttr>();
2312}
2313
2314/// Check that this core constant expression is of literal type, and if not,
2315/// produce an appropriate diagnostic.
2316static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2317 const LValue *This = nullptr) {
2318 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2319 return true;
2320
2321 // C++1y: A constant initializer for an object o [...] may also invoke
2322 // constexpr constructors for o and its subobjects even if those objects
2323 // are of non-literal class types.
2324 //
2325 // C++11 missed this detail for aggregates, so classes like this:
2326 // struct foo_t { union { int i; volatile int j; } u; };
2327 // are not (obviously) initializable like so:
2328 // __attribute__((__require_constant_initialization__))
2329 // static const foo_t x = {{0}};
2330 // because "i" is a subobject with non-literal initialization (due to the
2331 // volatile member of the union). See:
2332 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2333 // Therefore, we use the C++1y behavior.
2334 if (This && Info.EvaluatingDecl == This->getLValueBase())
2335 return true;
2336
2337 // Prvalue constant expressions must be of literal types.
2338 if (Info.getLangOpts().CPlusPlus11)
2339 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2340 << E->getType();
2341 else
2342 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2343 return false;
2344}
2345
2346static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2347 EvalInfo &Info, SourceLocation DiagLoc,
2348 QualType Type, const APValue &Value,
2349 ConstantExprKind Kind,
2350 SourceLocation SubobjectLoc,
2351 CheckedTemporaries &CheckedTemps) {
2352 if (!Value.hasValue()) {
2353 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2354 << true << Type;
2355 if (SubobjectLoc.isValid())
2356 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2357 return false;
2358 }
2359
2360 // We allow _Atomic(T) to be initialized from anything that T can be
2361 // initialized from.
2362 if (const AtomicType *AT = Type->getAs<AtomicType>())
2363 Type = AT->getValueType();
2364
2365 // Core issue 1454: For a literal constant expression of array or class type,
2366 // each subobject of its value shall have been initialized by a constant
2367 // expression.
2368 if (Value.isArray()) {
2369 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2370 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2371 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2372 Value.getArrayInitializedElt(I), Kind,
2373 SubobjectLoc, CheckedTemps))
2374 return false;
2375 }
2376 if (!Value.hasArrayFiller())
2377 return true;
2378 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2379 Value.getArrayFiller(), Kind, SubobjectLoc,
2380 CheckedTemps);
2381 }
2382 if (Value.isUnion() && Value.getUnionField()) {
2383 return CheckEvaluationResult(
2384 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2385 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2386 CheckedTemps);
2387 }
2388 if (Value.isStruct()) {
2389 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2390 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2391 unsigned BaseIndex = 0;
2392 for (const CXXBaseSpecifier &BS : CD->bases()) {
2393 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2394 Value.getStructBase(BaseIndex), Kind,
2395 BS.getBeginLoc(), CheckedTemps))
2396 return false;
2397 ++BaseIndex;
2398 }
2399 }
2400 for (const auto *I : RD->fields()) {
2401 if (I->isUnnamedBitfield())
2402 continue;
2403
2404 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2405 Value.getStructField(I->getFieldIndex()),
2406 Kind, I->getLocation(), CheckedTemps))
2407 return false;
2408 }
2409 }
2410
2411 if (Value.isLValue() &&
2412 CERK == CheckEvaluationResultKind::ConstantExpression) {
2413 LValue LVal;
2414 LVal.setFrom(Info.Ctx, Value);
2415 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2416 CheckedTemps);
2417 }
2418
2419 if (Value.isMemberPointer() &&
2420 CERK == CheckEvaluationResultKind::ConstantExpression)
2421 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2422
2423 // Everything else is fine.
2424 return true;
2425}
2426
2427/// Check that this core constant expression value is a valid value for a
2428/// constant expression. If not, report an appropriate diagnostic. Does not
2429/// check that the expression is of literal type.
2430static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2431 QualType Type, const APValue &Value,
2432 ConstantExprKind Kind) {
2433 // Nothing to check for a constant expression of type 'cv void'.
2434 if (Type->isVoidType())
2435 return true;
2436
2437 CheckedTemporaries CheckedTemps;
2438 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2439 Info, DiagLoc, Type, Value, Kind,
2440 SourceLocation(), CheckedTemps);
2441}
2442
2443/// Check that this evaluated value is fully-initialized and can be loaded by
2444/// an lvalue-to-rvalue conversion.
2445static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2446 QualType Type, const APValue &Value) {
2447 CheckedTemporaries CheckedTemps;
2448 return CheckEvaluationResult(
2449 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2450 ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2451}
2452
2453/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2454/// "the allocated storage is deallocated within the evaluation".
2455static bool CheckMemoryLeaks(EvalInfo &Info) {
2456 if (!Info.HeapAllocs.empty()) {
2457 // We can still fold to a constant despite a compile-time memory leak,
2458 // so long as the heap allocation isn't referenced in the result (we check
2459 // that in CheckConstantExpression).
2460 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2461 diag::note_constexpr_memory_leak)
2462 << unsigned(Info.HeapAllocs.size() - 1);
2463 }
2464 return true;
2465}
2466
2467static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2468 // A null base expression indicates a null pointer. These are always
2469 // evaluatable, and they are false unless the offset is zero.
2470 if (!Value.getLValueBase()) {
2471 Result = !Value.getLValueOffset().isZero();
2472 return true;
2473 }
2474
2475 // We have a non-null base. These are generally known to be true, but if it's
2476 // a weak declaration it can be null at runtime.
2477 Result = true;
2478 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2479 return !Decl || !Decl->isWeak();
2480}
2481
2482static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2483 switch (Val.getKind()) {
2484 case APValue::None:
2485 case APValue::Indeterminate:
2486 return false;
2487 case APValue::Int:
2488 Result = Val.getInt().getBoolValue();
2489 return true;
2490 case APValue::FixedPoint:
2491 Result = Val.getFixedPoint().getBoolValue();
2492 return true;
2493 case APValue::Float:
2494 Result = !Val.getFloat().isZero();
2495 return true;
2496 case APValue::ComplexInt:
2497 Result = Val.getComplexIntReal().getBoolValue() ||
2498 Val.getComplexIntImag().getBoolValue();
2499 return true;
2500 case APValue::ComplexFloat:
2501 Result = !Val.getComplexFloatReal().isZero() ||
2502 !Val.getComplexFloatImag().isZero();
2503 return true;
2504 case APValue::LValue:
2505 return EvalPointerValueAsBool(Val, Result);
2506 case APValue::MemberPointer:
2507 Result = Val.getMemberPointerDecl();
2508 return true;
2509 case APValue::Vector:
2510 case APValue::Array:
2511 case APValue::Struct:
2512 case APValue::Union:
2513 case APValue::AddrLabelDiff:
2514 return false;
2515 }
2516
2517 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "clang/lib/AST/ExprConstant.cpp"
, 2517)
;
2518}
2519
2520static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2521 EvalInfo &Info) {
2522 assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void (
0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 2522, __extension__ __PRETTY_FUNCTION__))
;
2523 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition")(static_cast <bool> (E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"
) ? void (0) : __assert_fail ("E->isPRValue() && \"missing lvalue-to-rvalue conv in bool condition\""
, "clang/lib/AST/ExprConstant.cpp", 2523, __extension__ __PRETTY_FUNCTION__
))
;
2524 APValue Val;
2525 if (!Evaluate(Val, Info, E))
2526 return false;
2527 return HandleConversionToBool(Val, Result);
2528}
2529
2530template<typename T>
2531static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2532 const T &SrcValue, QualType DestType) {
2533 Info.CCEDiag(E, diag::note_constexpr_overflow)
2534 << SrcValue << DestType;
2535 return Info.noteUndefinedBehavior();
2536}
2537
2538static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2539 QualType SrcType, const APFloat &Value,
2540 QualType DestType, APSInt &Result) {
2541 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2542 // Determine whether we are converting to unsigned or signed.
2543 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2544
2545 Result = APSInt(DestWidth, !DestSigned);
2546 bool ignored;
2547 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2548 & APFloat::opInvalidOp)
2549 return HandleOverflow(Info, E, Value, DestType);
2550 return true;
2551}
2552
2553/// Get rounding mode to use in evaluation of the specified expression.
2554///
2555/// If rounding mode is unknown at compile time, still try to evaluate the
2556/// expression. If the result is exact, it does not depend on rounding mode.
2557/// So return "tonearest" mode instead of "dynamic".
2558static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2559 llvm::RoundingMode RM =
2560 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2561 if (RM == llvm::RoundingMode::Dynamic)
2562 RM = llvm::RoundingMode::NearestTiesToEven;
2563 return RM;
2564}
2565
2566/// Check if the given evaluation result is allowed for constant evaluation.
2567static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2568 APFloat::opStatus St) {
2569 // In a constant context, assume that any dynamic rounding mode or FP
2570 // exception state matches the default floating-point environment.
2571 if (Info.InConstantContext)
2572 return true;
2573
2574 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2575 if ((St & APFloat::opInexact) &&
2576 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2577 // Inexact result means that it depends on rounding mode. If the requested
2578 // mode is dynamic, the evaluation cannot be made in compile time.
2579 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2580 return false;
2581 }
2582
2583 if ((St != APFloat::opOK) &&
2584 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2585 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2586 FPO.getAllowFEnvAccess())) {
2587 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2588 return false;
2589 }
2590
2591 if ((St & APFloat::opStatus::opInvalidOp) &&
2592 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2593 // There is no usefully definable result.
2594 Info.FFDiag(E);
2595 return false;
2596 }
2597
2598 // FIXME: if:
2599 // - evaluation triggered other FP exception, and
2600 // - exception mode is not "ignore", and
2601 // - the expression being evaluated is not a part of global variable
2602 // initializer,
2603 // the evaluation probably need to be rejected.
2604 return true;
2605}
2606
2607static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2608 QualType SrcType, QualType DestType,
2609 APFloat &Result) {
2610 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E))(static_cast <bool> (isa<CastExpr>(E) || isa<CompoundAssignOperator
>(E)) ? void (0) : __assert_fail ("isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)"
, "clang/lib/AST/ExprConstant.cpp", 2610, __extension__ __PRETTY_FUNCTION__
))
;
2611 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2612 APFloat::opStatus St;
2613 APFloat Value = Result;
2614 bool ignored;
2615 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2616 return checkFloatingPointResult(Info, E, St);
2617}
2618
2619static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2620 QualType DestType, QualType SrcType,
2621 const APSInt &Value) {
2622 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2623 // Figure out if this is a truncate, extend or noop cast.
2624 // If the input is signed, do a sign extend, noop, or truncate.
2625 APSInt Result = Value.extOrTrunc(DestWidth);
2626 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2627 if (DestType->isBooleanType())
2628 Result = Value.getBoolValue();
2629 return Result;
2630}
2631
2632static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2633 const FPOptions FPO,
2634 QualType SrcType, const APSInt &Value,
2635 QualType DestType, APFloat &Result) {
2636 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2637 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2638 APFloat::rmNearestTiesToEven);
2639 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2640 FPO.isFPConstrained()) {
2641 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2642 return false;
2643 }
2644 return true;
2645}
2646
2647static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2648 APValue &Value, const FieldDecl *FD) {
2649 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")(static_cast <bool> (FD->isBitField() && "truncateBitfieldValue on non-bitfield"
) ? void (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\""
, "clang/lib/AST/ExprConstant.cpp", 2649, __extension__ __PRETTY_FUNCTION__
))
;
2650
2651 if (!Value.isInt()) {
2652 // Trying to store a pointer-cast-to-integer into a bitfield.
2653 // FIXME: In this case, we should provide the diagnostic for casting
2654 // a pointer to an integer.
2655 assert(Value.isLValue() && "integral value neither int nor lvalue?")(static_cast <bool> (Value.isLValue() && "integral value neither int nor lvalue?"
) ? void (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\""
, "clang/lib/AST/ExprConstant.cpp", 2655, __extension__ __PRETTY_FUNCTION__
))
;
2656 Info.FFDiag(E);
2657 return false;
2658 }
2659
2660 APSInt &Int = Value.getInt();
2661 unsigned OldBitWidth = Int.getBitWidth();
2662 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2663 if (NewBitWidth < OldBitWidth)
2664 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2665 return true;
2666}
2667
2668static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2669 llvm::APInt &Res) {
2670 APValue SVal;
2671 if (!Evaluate(SVal, Info, E))
2672 return false;
2673 if (SVal.isInt()) {
2674 Res = SVal.getInt();
2675 return true;
2676 }
2677 if (SVal.isFloat()) {
2678 Res = SVal.getFloat().bitcastToAPInt();
2679 return true;
2680 }
2681 if (SVal.isVector()) {
2682 QualType VecTy = E->getType();
2683 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2684 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2685 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2686 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2687 Res = llvm::APInt::getZero(VecSize);
2688 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2689 APValue &Elt = SVal.getVectorElt(i);
2690 llvm::APInt EltAsInt;
2691 if (Elt.isInt()) {
2692 EltAsInt = Elt.getInt();
2693 } else if (Elt.isFloat()) {
2694 EltAsInt = Elt.getFloat().bitcastToAPInt();
2695 } else {
2696 // Don't try to handle vectors of anything other than int or float
2697 // (not sure if it's possible to hit this case).
2698 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2699 return false;
2700 }
2701 unsigned BaseEltSize = EltAsInt.getBitWidth();
2702 if (BigEndian)
2703 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2704 else
2705 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2706 }
2707 return true;
2708 }
2709 // Give up if the input isn't an int, float, or vector. For example, we
2710 // reject "(v4i16)(intptr_t)&a".
2711 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2712 return false;
2713}
2714
2715/// Perform the given integer operation, which is known to need at most BitWidth
2716/// bits, and check for overflow in the original type (if that type was not an
2717/// unsigned type).
2718template<typename Operation>
2719static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2720 const APSInt &LHS, const APSInt &RHS,
2721 unsigned BitWidth, Operation Op,
2722 APSInt &Result) {
2723 if (LHS.isUnsigned()) {
2724 Result = Op(LHS, RHS);
2725 return true;
2726 }
2727
2728 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2729 Result = Value.trunc(LHS.getBitWidth());
2730 if (Result.extend(BitWidth) != Value) {
2731 if (Info.checkingForUndefinedBehavior())
2732 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2733 diag::warn_integer_constant_overflow)
2734 << toString(Result, 10) << E->getType();
2735 return HandleOverflow(Info, E, Value, E->getType());
2736 }
2737 return true;
2738}
2739
2740/// Perform the given binary integer operation.
2741static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2742 BinaryOperatorKind Opcode, APSInt RHS,
2743 APSInt &Result) {
2744 switch (Opcode) {
2745 default:
2746 Info.FFDiag(E);
2747 return false;
2748 case BO_Mul:
2749 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2750 std::multiplies<APSInt>(), Result);
2751 case BO_Add:
2752 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2753 std::plus<APSInt>(), Result);
2754 case BO_Sub:
2755 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2756 std::minus<APSInt>(), Result);
2757 case BO_And: Result = LHS & RHS; return true;
2758 case BO_Xor: Result = LHS ^ RHS; return true;
2759 case BO_Or: Result = LHS | RHS; return true;
2760 case BO_Div:
2761 case BO_Rem:
2762 if (RHS == 0) {
2763 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2764 return false;
2765 }
2766 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2767 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2768 // this operation and gives the two's complement result.
2769 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2770 LHS.isMinSignedValue())
2771 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2772 E->getType());
2773 return true;
2774 case BO_Shl: {
2775 if (Info.getLangOpts().OpenCL)
2776 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2777 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2778 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2779 RHS.isUnsigned());
2780 else if (RHS.isSigned() && RHS.isNegative()) {
2781 // During constant-folding, a negative shift is an opposite shift. Such
2782 // a shift is not a constant expression.
2783 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2784 RHS = -RHS;
2785 goto shift_right;
2786 }
2787 shift_left:
2788 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2789 // the shifted type.
2790 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2791 if (SA != RHS) {
2792 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2793 << RHS << E->getType() << LHS.getBitWidth();
2794 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2795 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2796 // operand, and must not overflow the corresponding unsigned type.
2797 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2798 // E1 x 2^E2 module 2^N.
2799 if (LHS.isNegative())
2800 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2801 else if (LHS.countLeadingZeros() < SA)
2802 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2803 }
2804 Result = LHS << SA;
2805 return true;
2806 }
2807 case BO_Shr: {
2808 if (Info.getLangOpts().OpenCL)
2809 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2810 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2811 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2812 RHS.isUnsigned());
2813 else if (RHS.isSigned() && RHS.isNegative()) {
2814 // During constant-folding, a negative shift is an opposite shift. Such a
2815 // shift is not a constant expression.
2816 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2817 RHS = -RHS;
2818 goto shift_left;
2819 }
2820 shift_right:
2821 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2822 // shifted type.
2823 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2824 if (SA != RHS)
2825 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2826 << RHS << E->getType() << LHS.getBitWidth();
2827 Result = LHS >> SA;
2828 return true;
2829 }
2830
2831 case BO_LT: Result = LHS < RHS; return true;
2832 case BO_GT: Result = LHS > RHS; return true;
2833 case BO_LE: Result = LHS <= RHS; return true;
2834 case BO_GE: Result = LHS >= RHS; return true;
2835 case BO_EQ: Result = LHS == RHS; return true;
2836 case BO_NE: Result = LHS != RHS; return true;
2837 case BO_Cmp:
2838 llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere"
, "clang/lib/AST/ExprConstant.cpp", 2838)
;
2839 }
2840}
2841
2842/// Perform the given binary floating-point operation, in-place, on LHS.
2843static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2844 APFloat &LHS, BinaryOperatorKind Opcode,
2845 const APFloat &RHS) {
2846 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2847 APFloat::opStatus St;
2848 switch (Opcode) {
2849 default:
2850 Info.FFDiag(E);
2851 return false;
2852 case BO_Mul:
2853 St = LHS.multiply(RHS, RM);
2854 break;
2855 case BO_Add:
2856 St = LHS.add(RHS, RM);
2857 break;
2858 case BO_Sub:
2859 St = LHS.subtract(RHS, RM);
2860 break;
2861 case BO_Div:
2862 // [expr.mul]p4:
2863 // If the second operand of / or % is zero the behavior is undefined.
2864 if (RHS.isZero())
2865 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2866 St = LHS.divide(RHS, RM);
2867 break;
2868 }
2869
2870 // [expr.pre]p4:
2871 // If during the evaluation of an expression, the result is not
2872 // mathematically defined [...], the behavior is undefined.
2873 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2874 if (LHS.isNaN()) {
2875 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2876 return Info.noteUndefinedBehavior();
2877 }
2878
2879 return checkFloatingPointResult(Info, E, St);
2880}
2881
2882static bool handleLogicalOpForVector(const APInt &LHSValue,
2883 BinaryOperatorKind Opcode,
2884 const APInt &RHSValue, APInt &Result) {
2885 bool LHS = (LHSValue != 0);
2886 bool RHS = (RHSValue != 0);
2887
2888 if (Opcode == BO_LAnd)
2889 Result = LHS && RHS;
2890 else
2891 Result = LHS || RHS;
2892 return true;
2893}
2894static bool handleLogicalOpForVector(const APFloat &LHSValue,
2895 BinaryOperatorKind Opcode,
2896 const APFloat &RHSValue, APInt &Result) {
2897 bool LHS = !LHSValue.isZero();
2898 bool RHS = !RHSValue.isZero();
2899
2900 if (Opcode == BO_LAnd)
2901 Result = LHS && RHS;
2902 else
2903 Result = LHS || RHS;
2904 return true;
2905}
2906
2907static bool handleLogicalOpForVector(const APValue &LHSValue,
2908 BinaryOperatorKind Opcode,
2909 const APValue &RHSValue, APInt &Result) {
2910 // The result is always an int type, however operands match the first.
2911 if (LHSValue.getKind() == APValue::Int)
2912 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2913 RHSValue.getInt(), Result);
2914 assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float
&& "Should be no other options") ? void (0) : __assert_fail
("LHSValue.getKind() == APValue::Float && \"Should be no other options\""
, "clang/lib/AST/ExprConstant.cpp", 2914, __extension__ __PRETTY_FUNCTION__
))
;
2915 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2916 RHSValue.getFloat(), Result);
2917}
2918
2919template <typename APTy>
2920static bool
2921handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2922 const APTy &RHSValue, APInt &Result) {
2923 switch (Opcode) {
2924 default:
2925 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "clang/lib/AST/ExprConstant.cpp", 2925)
;
2926 case BO_EQ:
2927 Result = (LHSValue == RHSValue);
2928 break;
2929 case BO_NE:
2930 Result = (LHSValue != RHSValue);
2931 break;
2932 case BO_LT:
2933 Result = (LHSValue < RHSValue);
2934 break;
2935 case BO_GT:
2936 Result = (LHSValue > RHSValue);
2937 break;
2938 case BO_LE:
2939 Result = (LHSValue <= RHSValue);
2940 break;
2941 case BO_GE:
2942 Result = (LHSValue >= RHSValue);
2943 break;
2944 }
2945
2946 // The boolean operations on these vector types use an instruction that
2947 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2948 // to -1 to make sure that we produce the correct value.
2949 Result.negate();
2950
2951 return true;
2952}
2953
2954static bool handleCompareOpForVector(const APValue &LHSValue,
2955 BinaryOperatorKind Opcode,
2956 const APValue &RHSValue, APInt &Result) {
2957 // The result is always an int type, however operands match the first.
2958 if (LHSValue.getKind() == APValue::Int)
2959 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2960 RHSValue.getInt(), Result);
2961 assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float
&& "Should be no other options") ? void (0) : __assert_fail
("LHSValue.getKind() == APValue::Float && \"Should be no other options\""
, "clang/lib/AST/ExprConstant.cpp", 2961, __extension__ __PRETTY_FUNCTION__
))
;
2962 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2963 RHSValue.getFloat(), Result);
2964}
2965
2966// Perform binary operations for vector types, in place on the LHS.
2967static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2968 BinaryOperatorKind Opcode,
2969 APValue &LHSValue,
2970 const APValue &RHSValue) {
2971 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&(static_cast <bool> (Opcode != BO_PtrMemD && Opcode
!= BO_PtrMemI && "Operation not supported on vector types"
) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\""
, "clang/lib/AST/ExprConstant.cpp", 2972, __extension__ __PRETTY_FUNCTION__
))
2972 "Operation not supported on vector types")(static_cast <bool> (Opcode != BO_PtrMemD && Opcode
!= BO_PtrMemI && "Operation not supported on vector types"
) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\""
, "clang/lib/AST/ExprConstant.cpp", 2972, __extension__ __PRETTY_FUNCTION__
))
;
2973
2974 const auto *VT = E->getType()->castAs<VectorType>();
2975 unsigned NumElements = VT->getNumElements();
2976 QualType EltTy = VT->getElementType();
2977
2978 // In the cases (typically C as I've observed) where we aren't evaluating
2979 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2980 // just give up.
2981 if (!LHSValue.isVector()) {
2982 assert(LHSValue.isLValue() &&(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue"
) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\""
, "clang/lib/AST/ExprConstant.cpp", 2983, __extension__ __PRETTY_FUNCTION__
))
2983 "A vector result that isn't a vector OR uncalculated LValue")(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue"
) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\""
, "clang/lib/AST/ExprConstant.cpp", 2983, __extension__ __PRETTY_FUNCTION__
))
;
2984 Info.FFDiag(E);
2985 return false;
2986 }
2987
2988 assert(LHSValue.getVectorLength() == NumElements &&(static_cast <bool> (LHSValue.getVectorLength() == NumElements
&& RHSValue.getVectorLength() == NumElements &&
"Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\""
, "clang/lib/AST/ExprConstant.cpp", 2989, __extension__ __PRETTY_FUNCTION__
))
2989 RHSValue.getVectorLength() == NumElements && "Different vector sizes")(static_cast <bool> (LHSValue.getVectorLength() == NumElements
&& RHSValue.getVectorLength() == NumElements &&
"Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\""
, "clang/lib/AST/ExprConstant.cpp", 2989, __extension__ __PRETTY_FUNCTION__
))
;
2990
2991 SmallVector<APValue, 4> ResultElements;
2992
2993 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2994 APValue LHSElt = LHSValue.getVectorElt(EltNum);
2995 APValue RHSElt = RHSValue.getVectorElt(EltNum);
2996
2997 if (EltTy->isIntegerType()) {
2998 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2999 EltTy->isUnsignedIntegerType()};
3000 bool Success = true;
3001
3002 if (BinaryOperator::isLogicalOp(Opcode))
3003 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3004 else if (BinaryOperator::isComparisonOp(Opcode))
3005 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3006 else
3007 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3008 RHSElt.getInt(), EltResult);
3009
3010 if (!Success) {
3011 Info.FFDiag(E);
3012 return false;
3013 }
3014 ResultElements.emplace_back(EltResult);
3015
3016 } else if (EltTy->isFloatingType()) {
3017 assert(LHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float
&& RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type"
) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\""
, "clang/lib/AST/ExprConstant.cpp", 3019, __extension__ __PRETTY_FUNCTION__
))
3018 RHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float
&& RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type"
) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\""
, "clang/lib/AST/ExprConstant.cpp", 3019, __extension__ __PRETTY_FUNCTION__
))
3019 "Mismatched LHS/RHS/Result Type")(static_cast <bool> (LHSElt.getKind() == APValue::Float
&& RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type"
) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\""
, "clang/lib/AST/ExprConstant.cpp", 3019, __extension__ __PRETTY_FUNCTION__
))
;
3020 APFloat LHSFloat = LHSElt.getFloat();
3021
3022 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3023 RHSElt.getFloat())) {
3024 Info.FFDiag(E);
3025 return false;
3026 }
3027
3028 ResultElements.emplace_back(LHSFloat);
3029 }
3030 }
3031
3032 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3033 return true;
3034}
3035
3036/// Cast an lvalue referring to a base subobject to a derived class, by
3037/// truncating the lvalue's path to the given length.
3038static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3039 const RecordDecl *TruncatedType,
3040 unsigned TruncatedElements) {
3041 SubobjectDesignator &D = Result.Designator;
3042
3043 // Check we actually point to a derived class object.
3044 if (TruncatedElements == D.Entries.size())
3045 return true;
3046 assert(TruncatedElements >= D.MostDerivedPathLength &&(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength
&& "not casting to a derived class") ? void (0) : __assert_fail
("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "clang/lib/AST/ExprConstant.cpp", 3047, __extension__ __PRETTY_FUNCTION__
))
3047 "not casting to a derived class")(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength
&& "not casting to a derived class") ? void (0) : __assert_fail
("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "clang/lib/AST/ExprConstant.cpp", 3047, __extension__ __PRETTY_FUNCTION__
))
;
3048 if (!Result.checkSubobject(Info, E, CSK_Derived))
3049 return false;
3050
3051 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3052 const RecordDecl *RD = TruncatedType;
3053 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3054 if (RD->isInvalidDecl()) return false;
3055 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3056 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3057 if (isVirtualBaseClass(D.Entries[I]))
3058 Result.Offset -= Layout.getVBaseClassOffset(Base);
3059 else
3060 Result.Offset -= Layout.getBaseClassOffset(Base);
3061 RD = Base;
3062 }
3063 D.Entries.resize(TruncatedElements);
3064 return true;
3065}
3066
3067static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3068 const CXXRecordDecl *Derived,
3069 const CXXRecordDecl *Base,
3070 const ASTRecordLayout *RL = nullptr) {
3071 if (!RL) {
3072 if (Derived->isInvalidDecl()) return false;
3073 RL = &Info.Ctx.getASTRecordLayout(Derived);
3074 }
3075
3076 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3077 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3078 return true;
3079}
3080
3081static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3082 const CXXRecordDecl *DerivedDecl,
3083 const CXXBaseSpecifier *Base) {
3084 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3085
3086 if (!Base->isVirtual())
3087 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3088
3089 SubobjectDesignator &D = Obj.Designator;
3090 if (D.Invalid)
3091 return false;
3092
3093 // Extract most-derived object and corresponding type.
3094 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3095 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3096 return false;
3097
3098 // Find the virtual base class.
3099 if (DerivedDecl->isInvalidDecl()) return false;
3100 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3101 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3102 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3103 return true;
3104}
3105
3106static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3107 QualType Type, LValue &Result) {
3108 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3109 PathE = E->path_end();
3110 PathI != PathE; ++PathI) {
3111 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3112 *PathI))
3113 return false;
3114 Type = (*PathI)->getType();
3115 }
3116 return true;
3117}
3118
3119/// Cast an lvalue referring to a derived class to a known base subobject.
3120static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3121 const CXXRecordDecl *DerivedRD,
3122 const CXXRecordDecl *BaseRD) {
3123 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3124 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3125 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3126 llvm_unreachable("Class must be derived from the passed in base class!")::llvm::llvm_unreachable_internal("Class must be derived from the passed in base class!"
, "clang/lib/AST/ExprConstant.cpp", 3126)
;
3127
3128 for (CXXBasePathElement &Elem : Paths.front())
3129 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3130 return false;
3131 return true;
3132}
3133
3134/// Update LVal to refer to the given field, which must be a member of the type
3135/// currently described by LVal.
3136static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3137 const FieldDecl *FD,
3138 const ASTRecordLayout *RL = nullptr) {
3139 if (!RL) {
3140 if (FD->getParent()->isInvalidDecl()) return false;
3141 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3142 }
3143
3144 unsigned I = FD->getFieldIndex();
3145 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3146 LVal.addDecl(Info, E, FD);
3147 return true;
3148}
3149
3150/// Update LVal to refer to the given indirect field.
3151static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3152 LValue &LVal,
3153 const IndirectFieldDecl *IFD) {
3154 for (const auto *C : IFD->chain())
3155 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3156 return false;
3157 return true;
3158}
3159
3160/// Get the size of the given type in char units.
3161static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3162 QualType Type, CharUnits &Size) {
3163 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3164 // extension.
3165 if (Type->isVoidType() || Type->isFunctionType()) {
3166 Size = CharUnits::One();
3167 return true;
3168 }
3169
3170 if (Type->isDependentType()) {
3171 Info.FFDiag(Loc);
3172 return false;
3173 }
3174
3175 if (!Type->isConstantSizeType()) {
3176 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3177 // FIXME: Better diagnostic.
3178 Info.FFDiag(Loc);
3179 return false;
3180 }
3181
3182 Size = Info.Ctx.getTypeSizeInChars(Type);
3183 return true;
3184}
3185
3186/// Update a pointer value to model pointer arithmetic.
3187/// \param Info - Information about the ongoing evaluation.
3188/// \param E - The expression being evaluated, for diagnostic purposes.
3189/// \param LVal - The pointer value to be updated.
3190/// \param EltTy - The pointee type represented by LVal.
3191/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3192static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3193 LValue &LVal, QualType EltTy,
3194 APSInt Adjustment) {
3195 CharUnits SizeOfPointee;
3196 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3197 return false;
3198
3199 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3200 return true;
3201}
3202
3203static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3204 LValue &LVal, QualType EltTy,
3205 int64_t Adjustment) {
3206 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3207 APSInt::get(Adjustment));
3208}
3209
3210/// Update an lvalue to refer to a component of a complex number.
3211/// \param Info - Information about the ongoing evaluation.
3212/// \param LVal - The lvalue to be updated.
3213/// \param EltTy - The complex number's component type.
3214/// \param Imag - False for the real component, true for the imaginary.
3215static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3216 LValue &LVal, QualType EltTy,
3217 bool Imag) {
3218 if (Imag) {
3219 CharUnits SizeOfComponent;
3220 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3221 return false;
3222 LVal.Offset += SizeOfComponent;
3223 }
3224 LVal.addComplex(Info, E, EltTy, Imag);
3225 return true;
3226}
3227
3228/// Try to evaluate the initializer for a variable declaration.
3229///
3230/// \param Info Information about the ongoing evaluation.
3231/// \param E An expression to be used when printing diagnostics.
3232/// \param VD The variable whose initializer should be obtained.
3233/// \param Version The version of the variable within the frame.
3234/// \param Frame The frame in which the variable was created. Must be null
3235/// if this variable is not local to the evaluation.
3236/// \param Result Filled in with a pointer to the value of the variable.
3237static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3238 const VarDecl *VD, CallStackFrame *Frame,
3239 unsigned Version, APValue *&Result) {
3240 APValue::LValueBase Base(VD, Frame
9.1
'Frame' is null
? Frame->Index : 0, Version);
10
'?' condition is false
3241
3242 // If this is a local variable, dig out its value.
3243 if (Frame
10.1
'Frame' is null
) {
11
Taking false branch
3244 Result = Frame->getTemporary(VD, Version);
3245 if (Result)
3246 return true;
3247
3248 if (!isa<ParmVarDecl>(VD)) {
3249 // Assume variables referenced within a lambda's call operator that were
3250 // not declared within the call operator are captures and during checking
3251 // of a potential constant expression, assume they are unknown constant
3252 // expressions.
3253 assert(isLambdaCallOperator(Frame->Callee) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "clang/lib/AST/ExprConstant.cpp", 3255, __extension__ __PRETTY_FUNCTION__
))
3254 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "clang/lib/AST/ExprConstant.cpp", 3255, __extension__ __PRETTY_FUNCTION__
))
3255 "missing value for local variable")(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "clang/lib/AST/ExprConstant.cpp", 3255, __extension__ __PRETTY_FUNCTION__
))
;
3256 if (Info.checkingPotentialConstantExpression())
3257 return false;
3258 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3259 // still reachable at all?
3260 Info.FFDiag(E->getBeginLoc(),
3261 diag::note_unimplemented_constexpr_lambda_feature_ast)
3262 << "captures not currently allowed";
3263 return false;
3264 }
3265 }
3266
3267 // If we're currently evaluating the initializer of this declaration, use that
3268 // in-flight value.
3269 if (Info.EvaluatingDecl == Base) {
12
Assuming the condition is false
13
Taking false branch
3270 Result = Info.EvaluatingDeclValue;
3271 return true;
3272 }
3273
3274 if (isa<ParmVarDecl>(VD)) {
14
Assuming 'VD' is a 'class clang::ParmVarDecl &'
3275 // Assume parameters of a potential constant expression are usable in
3276 // constant expressions.
3277 if (!Info.checkingPotentialConstantExpression() ||
15
Assuming the condition is false
3278 !Info.CurrentCall->Callee ||
16
Access to field 'Callee' results in a dereference of a null pointer (loaded from field 'CurrentCall')
3279 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3280 if (Info.getLangOpts().CPlusPlus11) {
3281 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3282 << VD;
3283 NoteLValueLocation(Info, Base);
3284 } else {
3285 Info.FFDiag(E);
3286 }
3287 }
3288 return false;
3289 }
3290
3291 // Dig out the initializer, and use the declaration which it's attached to.
3292 // FIXME: We should eventually check whether the variable has a reachable
3293 // initializing declaration.
3294 const Expr *Init = VD->getAnyInitializer(VD);
3295 if (!Init) {
3296 // Don't diagnose during potential constant expression checking; an
3297 // initializer might be added later.
3298 if (!Info.checkingPotentialConstantExpression()) {
3299 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3300 << VD;
3301 NoteLValueLocation(Info, Base);
3302 }
3303 return false;
3304 }
3305
3306 if (Init->isValueDependent()) {
3307 // The DeclRefExpr is not value-dependent, but the variable it refers to
3308 // has a value-dependent initializer. This should only happen in
3309 // constant-folding cases, where the variable is not actually of a suitable
3310 // type for use in a constant expression (otherwise the DeclRefExpr would
3311 // have been value-dependent too), so diagnose that.
3312 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx))(static_cast <bool> (!VD->mightBeUsableInConstantExpressions
(Info.Ctx)) ? void (0) : __assert_fail ("!VD->mightBeUsableInConstantExpressions(Info.Ctx)"
, "clang/lib/AST/ExprConstant.cpp", 3312, __extension__ __PRETTY_FUNCTION__
))
;
3313 if (!Info.checkingPotentialConstantExpression()) {
3314 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3315 ? diag::note_constexpr_ltor_non_constexpr
3316 : diag::note_constexpr_ltor_non_integral, 1)
3317 << VD << VD->getType();
3318 NoteLValueLocation(Info, Base);
3319 }
3320 return false;
3321 }
3322
3323 // Check that we can fold the initializer. In C++, we will have already done
3324 // this in the cases where it matters for conformance.
3325 if (!VD->evaluateValue()) {
3326 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3327 NoteLValueLocation(Info, Base);
3328 return false;
3329 }
3330
3331 // Check that the variable is actually usable in constant expressions. For a
3332 // const integral variable or a reference, we might have a non-constant
3333 // initializer that we can nonetheless evaluate the initializer for. Such
3334 // variables are not usable in constant expressions. In C++98, the
3335 // initializer also syntactically needs to be an ICE.
3336 //
3337 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3338 // expressions here; doing so would regress diagnostics for things like
3339 // reading from a volatile constexpr variable.
3340 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3341 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3342 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3343 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3344 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3345 NoteLValueLocation(Info, Base);
3346 }
3347
3348 // Never use the initializer of a weak variable, not even for constant
3349 // folding. We can't be sure that this is the definition that will be used.
3350 if (VD->isWeak()) {
3351 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3352 NoteLValueLocation(Info, Base);
3353 return false;
3354 }
3355
3356 Result = VD->getEvaluatedValue();
3357 return true;
3358}
3359
3360/// Get the base index of the given base class within an APValue representing
3361/// the given derived class.
3362static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3363 const CXXRecordDecl *Base) {
3364 Base = Base->getCanonicalDecl();
3365 unsigned Index = 0;
3366 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3367 E = Derived->bases_end(); I != E; ++I, ++Index) {
3368 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3369 return Index;
3370 }
3371
3372 llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list"
, "clang/lib/AST/ExprConstant.cpp", 3372)
;
3373}
3374
3375/// Extract the value of a character from a string literal.
3376static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3377 uint64_t Index) {
3378 assert(!isa<SourceLocExpr>(Lit) &&(static_cast <bool> (!isa<SourceLocExpr>(Lit) &&
"SourceLocExpr should have already been converted to a StringLiteral"
) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\""
, "clang/lib/AST/ExprConstant.cpp", 3379, __extension__ __PRETTY_FUNCTION__
))
3379 "SourceLocExpr should have already been converted to a StringLiteral")(static_cast <bool> (!isa<SourceLocExpr>(Lit) &&
"SourceLocExpr should have already been converted to a StringLiteral"
) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\""
, "clang/lib/AST/ExprConstant.cpp", 3379, __extension__ __PRETTY_FUNCTION__
))
;
3380
3381 // FIXME: Support MakeStringConstant
3382 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3383 std::string Str;
3384 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3385 assert(Index <= Str.size() && "Index too large")(static_cast <bool> (Index <= Str.size() && "Index too large"
) ? void (0) : __assert_fail ("Index <= Str.size() && \"Index too large\""
, "clang/lib/AST/ExprConstant.cpp", 3385, __extension__ __PRETTY_FUNCTION__
))
;
3386 return APSInt::getUnsigned(Str.c_str()[Index]);
3387 }
3388
3389 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3390 Lit = PE->getFunctionName();
3391 const StringLiteral *S = cast<StringLiteral>(Lit);
3392 const ConstantArrayType *CAT =
3393 Info.Ctx.getAsConstantArrayType(S->getType());
3394 assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array"
) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "clang/lib/AST/ExprConstant.cpp", 3394, __extension__ __PRETTY_FUNCTION__
))
;
3395 QualType CharType = CAT->getElementType();
3396 assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() &&
"unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "clang/lib/AST/ExprConstant.cpp", 3396, __extension__ __PRETTY_FUNCTION__
))
;
3397
3398 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3399 CharType->isUnsignedIntegerType());
3400 if (Index < S->getLength())
3401 Value = S->getCodeUnit(Index);
3402 return Value;
3403}
3404
3405// Expand a string literal into an array of characters.
3406//
3407// FIXME: This is inefficient; we should probably introduce something similar
3408// to the LLVM ConstantDataArray to make this cheaper.
3409static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3410 APValue &Result,
3411 QualType AllocType = QualType()) {
3412 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3413 AllocType.isNull() ? S->getType() : AllocType);
3414 assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array"
) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "clang/lib/AST/ExprConstant.cpp", 3414, __extension__ __PRETTY_FUNCTION__
))
;
3415 QualType CharType = CAT->getElementType();
3416 assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() &&
"unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "clang/lib/AST/ExprConstant.cpp", 3416, __extension__ __PRETTY_FUNCTION__
))
;
3417
3418 unsigned Elts = CAT->getSize().getZExtValue();
3419 Result = APValue(APValue::UninitArray(),
3420 std::min(S->getLength(), Elts), Elts);
3421 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3422 CharType->isUnsignedIntegerType());
3423 if (Result.hasArrayFiller())
3424 Result.getArrayFiller() = APValue(Value);
3425 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3426 Value = S->getCodeUnit(I);
3427 Result.getArrayInitializedElt(I) = APValue(Value);
3428 }
3429}
3430
3431// Expand an array so that it has more than Index filled elements.
3432static void expandArray(APValue &Array, unsigned Index) {
3433 unsigned Size = Array.getArraySize();
3434 assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail
("Index < Size", "clang/lib/AST/ExprConstant.cpp", 3434, __extension__
__PRETTY_FUNCTION__))
;
3435
3436 // Always at least double the number of elements for which we store a value.
3437 unsigned OldElts = Array.getArrayInitializedElts();
3438 unsigned NewElts = std::max(Index+1, OldElts * 2);
3439 NewElts = std::min(Size, std::max(NewElts, 8u));
3440
3441 // Copy the data across.
3442 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3443 for (unsigned I = 0; I != OldElts; ++I)
3444 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3445 for (unsigned I = OldElts; I != NewElts; ++I)
3446 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3447 if (NewValue.hasArrayFiller())
3448 NewValue.getArrayFiller() = Array.getArrayFiller();
3449 Array.swap(NewValue);
3450}
3451
3452/// Determine whether a type would actually be read by an lvalue-to-rvalue
3453/// conversion. If it's of class type, we may assume that the copy operation
3454/// is trivial. Note that this is never true for a union type with fields
3455/// (because the copy always "reads" the active member) and always true for
3456/// a non-class type.
3457static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3458static bool isReadByLvalueToRvalueConversion(QualType T) {
3459 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3460 return !RD || isReadByLvalueToRvalueConversion(RD);
3461}
3462static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3463 // FIXME: A trivial copy of a union copies the object representation, even if
3464 // the union is empty.
3465 if (RD->isUnion())
3466 return !RD->field_empty();
3467 if (RD->isEmpty())
3468 return false;
3469
3470 for (auto *Field : RD->fields())
3471 if (!Field->isUnnamedBitfield() &&
3472 isReadByLvalueToRvalueConversion(Field->getType()))
3473 return true;
3474
3475 for (auto &BaseSpec : RD->bases())
3476 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3477 return true;
3478
3479 return false;
3480}
3481
3482/// Diagnose an attempt to read from any unreadable field within the specified
3483/// type, which might be a class type.
3484static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3485 QualType T) {
3486 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3487 if (!RD)
3488 return false;
3489
3490 if (!RD->hasMutableFields())
3491 return false;
3492
3493 for (auto *Field : RD->fields()) {
3494 // If we're actually going to read this field in some way, then it can't
3495 // be mutable. If we're in a union, then assigning to a mutable field
3496 // (even an empty one) can change the active member, so that's not OK.
3497 // FIXME: Add core issue number for the union case.
3498 if (Field->isMutable() &&
3499 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3500 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3501 Info.Note(Field->getLocation(), diag::note_declared_at);
3502 return true;
3503 }
3504
3505 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3506 return true;
3507 }
3508
3509 for (auto &BaseSpec : RD->bases())
3510 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3511 return true;
3512
3513 // All mutable fields were empty, and thus not actually read.
3514 return false;
3515}
3516
3517static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3518 APValue::LValueBase Base,
3519 bool MutableSubobject = false) {
3520 // A temporary or transient heap allocation we created.
3521 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3522 return true;
3523
3524 switch (Info.IsEvaluatingDecl) {
3525 case EvalInfo::EvaluatingDeclKind::None:
3526 return false;
3527
3528 case EvalInfo::EvaluatingDeclKind::Ctor:
3529 // The variable whose initializer we're evaluating.
3530 if (Info.EvaluatingDecl == Base)
3531 return true;
3532
3533 // A temporary lifetime-extended by the variable whose initializer we're
3534 // evaluating.
3535 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3536 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3537 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3538 return false;
3539
3540 case EvalInfo::EvaluatingDeclKind::Dtor:
3541 // C++2a [expr.const]p6:
3542 // [during constant destruction] the lifetime of a and its non-mutable
3543 // subobjects (but not its mutable subobjects) [are] considered to start
3544 // within e.
3545 if (MutableSubobject || Base != Info.EvaluatingDecl)
3546 return false;
3547 // FIXME: We can meaningfully extend this to cover non-const objects, but
3548 // we will need special handling: we should be able to access only
3549 // subobjects of such objects that are themselves declared const.
3550 QualType T = getType(Base);
3551 return T.isConstQualified() || T->isReferenceType();
3552 }
3553
3554 llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind"
, "clang/lib/AST/ExprConstant.cpp", 3554)
;
3555}
3556
3557namespace {
3558/// A handle to a complete object (an object that is not a subobject of
3559/// another object).
3560struct CompleteObject {
3561 /// The identity of the object.
3562 APValue::LValueBase Base;
3563 /// The value of the complete object.
3564 APValue *Value;
3565 /// The type of the complete object.
3566 QualType Type;
3567
3568 CompleteObject() : Value(nullptr) {}
3569 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3570 : Base(Base), Value(Value), Type(Type) {}
3571
3572 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3573 // If this isn't a "real" access (eg, if it's just accessing the type
3574 // info), allow it. We assume the type doesn't change dynamically for
3575 // subobjects of constexpr objects (even though we'd hit UB here if it
3576 // did). FIXME: Is this right?
3577 if (!isAnyAccess(AK))
3578 return true;
3579
3580 // In C++14 onwards, it is permitted to read a mutable member whose
3581 // lifetime began within the evaluation.
3582 // FIXME: Should we also allow this in C++11?
3583 if (!Info.getLangOpts().CPlusPlus14)
3584 return false;
3585 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3586 }
3587
3588 explicit operator bool() const { return !Type.isNull(); }
3589};
3590} // end anonymous namespace
3591
3592static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3593 bool IsMutable = false) {
3594 // C++ [basic.type.qualifier]p1:
3595 // - A const object is an object of type const T or a non-mutable subobject
3596 // of a const object.
3597 if (ObjType.isConstQualified() && !IsMutable)
3598 SubobjType.addConst();
3599 // - A volatile object is an object of type const T or a subobject of a
3600 // volatile object.
3601 if (ObjType.isVolatileQualified())
3602 SubobjType.addVolatile();
3603 return SubobjType;
3604}
3605
3606/// Find the designated sub-object of an rvalue.
3607template<typename SubobjectHandler>
3608typename SubobjectHandler::result_type
3609findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3610 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3611 if (Sub.Invalid)
3612 // A diagnostic will have already been produced.
3613 return handler.failed();
3614 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3615 if (Info.getLangOpts().CPlusPlus11)
3616 Info.FFDiag(E, Sub.isOnePastTheEnd()
3617 ? diag::note_constexpr_access_past_end
3618 : diag::note_constexpr_access_unsized_array)
3619 << handler.AccessKind;
3620 else
3621 Info.FFDiag(E);
3622 return handler.failed();
3623 }
3624
3625 APValue *O = Obj.Value;
3626 QualType ObjType = Obj.Type;
3627 const FieldDecl *LastField = nullptr;
3628 const FieldDecl *VolatileField = nullptr;
3629
3630 // Walk the designator's path to find the subobject.
3631 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3632 // Reading an indeterminate value is undefined, but assigning over one is OK.
3633 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3634 (O->isIndeterminate() &&
3635 !isValidIndeterminateAccess(handler.AccessKind))) {
3636 if (!Info.checkingPotentialConstantExpression())
3637 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3638 << handler.AccessKind << O->isIndeterminate();
3639 return handler.failed();
3640 }
3641
3642 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3643 // const and volatile semantics are not applied on an object under
3644 // {con,de}struction.
3645 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3646 ObjType->isRecordType() &&
3647 Info.isEvaluatingCtorDtor(
3648 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3649 Sub.Entries.begin() + I)) !=
3650 ConstructionPhase::None) {
3651 ObjType = Info.Ctx.getCanonicalType(ObjType);
3652 ObjType.removeLocalConst();
3653 ObjType.removeLocalVolatile();
3654 }
3655
3656 // If this is our last pass, check that the final object type is OK.
3657 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3658 // Accesses to volatile objects are prohibited.
3659 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3660 if (Info.getLangOpts().CPlusPlus) {
3661 int DiagKind;
3662 SourceLocation Loc;
3663 const NamedDecl *Decl = nullptr;
3664 if (VolatileField) {
3665 DiagKind = 2;
3666 Loc = VolatileField->getLocation();
3667 Decl = VolatileField;
3668 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3669 DiagKind = 1;
3670 Loc = VD->getLocation();
3671 Decl = VD;
3672 } else {
3673 DiagKind = 0;
3674 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3675 Loc = E->getExprLoc();
3676 }
3677 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3678 << handler.AccessKind << DiagKind << Decl;
3679 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3680 } else {
3681 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3682 }
3683 return handler.failed();
3684 }
3685
3686 // If we are reading an object of class type, there may still be more
3687 // things we need to check: if there are any mutable subobjects, we
3688 // cannot perform this read. (This only happens when performing a trivial
3689 // copy or assignment.)
3690 if (ObjType->isRecordType() &&
3691 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3692 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3693 return handler.failed();
3694 }
3695
3696 if (I == N) {
3697 if (!handler.found(*O, ObjType))
3698 return false;
3699
3700 // If we modified a bit-field, truncate it to the right width.
3701 if (isModification(handler.AccessKind) &&
3702 LastField && LastField->isBitField() &&
3703 !truncateBitfieldValue(Info, E, *O, LastField))
3704 return false;
3705
3706 return true;
3707 }
3708
3709 LastField = nullptr;
3710 if (ObjType->isArrayType()) {
3711 // Next subobject is an array element.
3712 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3713 assert(CAT && "vla in literal type?")(static_cast <bool> (CAT && "vla in literal type?"
) ? void (0) : __assert_fail ("CAT && \"vla in literal type?\""
, "clang/lib/AST/ExprConstant.cpp", 3713, __extension__ __PRETTY_FUNCTION__
))
;
3714 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3715 if (CAT->getSize().ule(Index)) {
3716 // Note, it should not be possible to form a pointer with a valid
3717 // designator which points more than one past the end of the array.
3718 if (Info.getLangOpts().CPlusPlus11)
3719 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3720 << handler.AccessKind;
3721 else
3722 Info.FFDiag(E);
3723 return handler.failed();
3724 }
3725
3726 ObjType = CAT->getElementType();
3727
3728 if (O->getArrayInitializedElts() > Index)
3729 O = &O->getArrayInitializedElt(Index);
3730 else if (!isRead(handler.AccessKind)) {
3731 expandArray(*O, Index);
3732 O = &O->getArrayInitializedElt(Index);
3733 } else
3734 O = &O->getArrayFiller();
3735 } else if (ObjType->isAnyComplexType()) {
3736 // Next subobject is a complex number.
3737 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3738 if (Index > 1) {
3739 if (Info.getLangOpts().CPlusPlus11)
3740 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3741 << handler.AccessKind;
3742 else
3743 Info.FFDiag(E);
3744 return handler.failed();
3745 }
3746
3747 ObjType = getSubobjectType(
3748 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3749
3750 assert(I == N - 1 && "extracting subobject of scalar?")(static_cast <bool> (I == N - 1 && "extracting subobject of scalar?"
) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\""
, "clang/lib/AST/ExprConstant.cpp", 3750, __extension__ __PRETTY_FUNCTION__
))
;
3751 if (O->isComplexInt()) {
3752 return handler.found(Index ? O->getComplexIntImag()
3753 : O->getComplexIntReal(), ObjType);
3754 } else {
3755 assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0)
: __assert_fail ("O->isComplexFloat()", "clang/lib/AST/ExprConstant.cpp"
, 3755, __extension__ __PRETTY_FUNCTION__))
;
3756 return handler.found(Index ? O->getComplexFloatImag()
3757 : O->getComplexFloatReal(), ObjType);
3758 }
3759 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3760 if (Field->isMutable() &&
3761 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3762 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3763 << handler.AccessKind << Field;
3764 Info.Note(Field->getLocation(), diag::note_declared_at);
3765 return handler.failed();
3766 }
3767
3768 // Next subobject is a class, struct or union field.
3769 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3770 if (RD->isUnion()) {
3771 const FieldDecl *UnionField = O->getUnionField();
3772 if (!UnionField ||
3773 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3774 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3775 // Placement new onto an inactive union member makes it active.
3776 O->setUnion(Field, APValue());
3777 } else {
3778 // FIXME: If O->getUnionValue() is absent, report that there's no
3779 // active union member rather than reporting the prior active union
3780 // member. We'll need to fix nullptr_t to not use APValue() as its
3781 // representation first.
3782 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3783 << handler.AccessKind << Field << !UnionField << UnionField;
3784 return handler.failed();
3785 }
3786 }
3787 O = &O->getUnionValue();
3788 } else
3789 O = &O->getStructField(Field->getFieldIndex());
3790
3791 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3792 LastField = Field;
3793 if (Field->getType().isVolatileQualified())
3794 VolatileField = Field;
3795 } else {
3796 // Next subobject is a base class.
3797 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3798 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3799 O = &O->getStructBase(getBaseIndex(Derived, Base));
3800
3801 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3802 }
3803 }
3804}
3805
3806namespace {
3807struct ExtractSubobjectHandler {
3808 EvalInfo &Info;
3809 const Expr *E;
3810 APValue &Result;
3811 const AccessKinds AccessKind;
3812
3813 typedef bool result_type;
3814 bool failed() { return false; }
3815 bool found(APValue &Subobj, QualType SubobjType) {
3816 Result = Subobj;
3817 if (AccessKind == AK_ReadObjectRepresentation)
3818 return true;
3819 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3820 }
3821 bool found(APSInt &Value, QualType SubobjType) {
3822 Result = APValue(Value);
3823 return true;
3824 }
3825 bool found(APFloat &Value, QualType SubobjType) {
3826 Result = APValue(Value);
3827 return true;
3828 }
3829};
3830} // end anonymous namespace
3831
3832/// Extract the designated sub-object of an rvalue.
3833static bool extractSubobject(EvalInfo &Info, const Expr *E,
3834 const CompleteObject &Obj,
3835 const SubobjectDesignator &Sub, APValue &Result,
3836 AccessKinds AK = AK_Read) {
3837 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)(static_cast <bool> (AK == AK_Read || AK == AK_ReadObjectRepresentation
) ? void (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation"
, "clang/lib/AST/ExprConstant.cpp", 3837, __extension__ __PRETTY_FUNCTION__
))
;
3838 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3839 return findSubobject(Info, E, Obj, Sub, Handler);
3840}
3841
3842namespace {
3843struct ModifySubobjectHandler {
3844 EvalInfo &Info;
3845 APValue &NewVal;
3846 const Expr *E;
3847
3848 typedef bool result_type;
3849 static const AccessKinds AccessKind = AK_Assign;
3850
3851 bool checkConst(QualType QT) {
3852 // Assigning to a const object has undefined behavior.
3853 if (QT.isConstQualified()) {
3854 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3855 return false;
3856 }
3857 return true;
3858 }
3859
3860 bool failed() { return false; }
3861 bool found(APValue &Subobj, QualType SubobjType) {
3862 if (!checkConst(SubobjType))
3863 return false;
3864 // We've been given ownership of NewVal, so just swap it in.
3865 Subobj.swap(NewVal);
3866 return true;
3867 }
3868 bool found(APSInt &Value, QualType SubobjType) {
3869 if (!checkConst(SubobjType))
3870 return false;
3871 if (!NewVal.isInt()) {
3872 // Maybe trying to write a cast pointer value into a complex?
3873 Info.FFDiag(E);
3874 return false;
3875 }
3876 Value = NewVal.getInt();
3877 return true;
3878 }
3879 bool found(APFloat &Value, QualType SubobjType) {
3880 if (!checkConst(SubobjType))
3881 return false;
3882 Value = NewVal.getFloat();
3883 return true;
3884 }
3885};
3886} // end anonymous namespace
3887
3888const AccessKinds ModifySubobjectHandler::AccessKind;
3889
3890/// Update the designated sub-object of an rvalue to the given value.
3891static bool modifySubobject(EvalInfo &Info, const Expr *E,
3892 const CompleteObject &Obj,
3893 const SubobjectDesignator &Sub,
3894 APValue &NewVal) {
3895 ModifySubobjectHandler Handler = { Info, NewVal, E };
3896 return findSubobject(Info, E, Obj, Sub, Handler);
3897}
3898
3899/// Find the position where two subobject designators diverge, or equivalently
3900/// the length of the common initial subsequence.
3901static unsigned FindDesignatorMismatch(QualType ObjType,
3902 const SubobjectDesignator &A,
3903 const SubobjectDesignator &B,
3904 bool &WasArrayIndex) {
3905 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3906 for (/**/; I != N; ++I) {
3907 if (!ObjType.isNull() &&
3908 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3909 // Next subobject is an array element.
3910 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3911 WasArrayIndex = true;
3912 return I;
3913 }
3914 if (ObjType->isAnyComplexType())
3915 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3916 else
3917 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3918 } else {
3919 if (A.Entries[I].getAsBaseOrMember() !=
3920 B.Entries[I].getAsBaseOrMember()) {
3921 WasArrayIndex = false;
3922 return I;
3923 }
3924 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3925 // Next subobject is a field.
3926 ObjType = FD->getType();
3927 else
3928 // Next subobject is a base class.
3929 ObjType = QualType();
3930 }
3931 }
3932 WasArrayIndex = false;
3933 return I;
3934}
3935
3936/// Determine whether the given subobject designators refer to elements of the
3937/// same array object.
3938static bool AreElementsOfSameArray(QualType ObjType,
3939 const SubobjectDesignator &A,
3940 const SubobjectDesignator &B) {
3941 if (A.Entries.size() != B.Entries.size())
3942 return false;
3943
3944 bool IsArray = A.MostDerivedIsArrayElement;
3945 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3946 // A is a subobject of the array element.
3947 return false;
3948
3949 // If A (and B) designates an array element, the last entry will be the array
3950 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3951 // of length 1' case, and the entire path must match.
3952 bool WasArrayIndex;
3953 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3954 return CommonLength >= A.Entries.size() - IsArray;
3955}
3956
3957/// Find the complete object to which an LValue refers.
3958static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3959 AccessKinds AK, const LValue &LVal,
3960 QualType LValType) {
3961 if (LVal.InvalidBase) {
3962 Info.FFDiag(E);
3963 return CompleteObject();
3964 }
3965
3966 if (!LVal.Base) {
3967 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3968 return CompleteObject();
3969 }
3970
3971 CallStackFrame *Frame = nullptr;
3972 unsigned Depth = 0;
3973 if (LVal.getLValueCallIndex()) {
3974 std::tie(Frame, Depth) =
3975 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3976 if (!Frame) {
3977 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3978 << AK << LVal.Base.is<const ValueDecl*>();
3979 NoteLValueLocation(Info, LVal.Base);
3980 return CompleteObject();
3981 }
3982 }
3983
3984 bool IsAccess = isAnyAccess(AK);
3985
3986 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3987 // is not a constant expression (even if the object is non-volatile). We also
3988 // apply this rule to C++98, in order to conform to the expected 'volatile'
3989 // semantics.
3990 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3991 if (Info.getLangOpts().CPlusPlus)
3992 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3993 << AK << LValType;
3994 else
3995 Info.FFDiag(E);
3996 return CompleteObject();
3997 }
3998
3999 // Compute value storage location and type of base object.
4000 APValue *BaseVal = nullptr;
4001 QualType BaseType = getType(LVal.Base);
4002
4003 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4004 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4005 // This is the object whose initializer we're evaluating, so its lifetime
4006 // started in the current evaluation.
4007 BaseVal = Info.EvaluatingDeclValue;
4008 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4009 // Allow reading from a GUID declaration.
4010 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4011 if (isModification(AK)) {
4012 // All the remaining cases do not permit modification of the object.
4013 Info.FFDiag(E, diag::note_constexpr_modify_global);
4014 return CompleteObject();
4015 }
4016 APValue &V = GD->getAsAPValue();
4017 if (V.isAbsent()) {
4018 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4019 << GD->getType();
4020 return CompleteObject();
4021 }
4022 return CompleteObject(LVal.Base, &V, GD->getType());
4023 }
4024
4025 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4026 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4027 if (isModification(AK)) {
4028 Info.FFDiag(E, diag::note_constexpr_modify_global);
4029 return CompleteObject();
4030 }
4031 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4032 GCD->getType());
4033 }
4034
4035 // Allow reading from template parameter objects.
4036 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4037 if (isModification(AK)) {
4038 Info.FFDiag(E, diag::note_constexpr_modify_global);
4039 return CompleteObject();
4040 }
4041 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4042 TPO->getType());
4043 }
4044
4045 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4046 // In C++11, constexpr, non-volatile variables initialized with constant
4047 // expressions are constant expressions too. Inside constexpr functions,
4048 // parameters are constant expressions even if they're non-const.
4049 // In C++1y, objects local to a constant expression (those with a Frame) are
4050 // both readable and writable inside constant expressions.
4051 // In C, such things can also be folded, although they are not ICEs.
4052 const VarDecl *VD = dyn_cast<VarDecl>(D);
4053 if (VD) {
4054 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4055 VD = VDef;
4056 }
4057 if (!VD || VD->isInvalidDecl()) {
4058 Info.FFDiag(E);
4059 return CompleteObject();
4060 }
4061
4062 bool IsConstant = BaseType.isConstant(Info.Ctx);
4063
4064 // Unless we're looking at a local variable or argument in a constexpr call,
4065 // the variable we're reading must be const.
4066 if (!Frame) {
4067 if (IsAccess && isa<ParmVarDecl>(VD)) {
4068 // Access of a parameter that's not associated with a frame isn't going
4069 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4070 // suitable diagnostic.
4071 } else if (Info.getLangOpts().CPlusPlus14 &&
4072 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4073 // OK, we can read and modify an object if we're in the process of
4074 // evaluating its initializer, because its lifetime began in this
4075 // evaluation.
4076 } else if (isModification(AK)) {
4077 // All the remaining cases do not permit modification of the object.
4078 Info.FFDiag(E, diag::note_constexpr_modify_global);
4079 return CompleteObject();
4080 } else if (VD->isConstexpr()) {
4081 // OK, we can read this variable.
4082 } else if (BaseType->isIntegralOrEnumerationType()) {
4083 if (!IsConstant) {
4084 if (!IsAccess)
4085 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4086 if (Info.getLangOpts().CPlusPlus) {
4087 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4088 Info.Note(VD->getLocation(), diag::note_declared_at);
4089 } else {
4090 Info.FFDiag(E);
4091 }
4092 return CompleteObject();
4093 }
4094 } else if (!IsAccess) {
4095 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4096 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4097 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4098 // This variable might end up being constexpr. Don't diagnose it yet.
4099 } else if (IsConstant) {
4100 // Keep evaluating to see what we can do. In particular, we support
4101 // folding of const floating-point types, in order to make static const
4102 // data members of such types (supported as an extension) more useful.
4103 if (Info.getLangOpts().CPlusPlus) {
4104 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4105 ? diag::note_constexpr_ltor_non_constexpr
4106 : diag::note_constexpr_ltor_non_integral, 1)
4107 << VD << BaseType;
4108 Info.Note(VD->getLocation(), diag::note_declared_at);
4109 } else {
4110 Info.CCEDiag(E);
4111 }
4112 } else {
4113 // Never allow reading a non-const value.
4114 if (Info.getLangOpts().CPlusPlus) {
4115 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4116 ? diag::note_constexpr_ltor_non_constexpr
4117 : diag::note_constexpr_ltor_non_integral, 1)
4118 << VD << BaseType;
4119 Info.Note(VD->getLocation(), diag::note_declared_at);
4120 } else {
4121 Info.FFDiag(E);
4122 }
4123 return CompleteObject();
4124 }
4125 }
4126
4127 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4128 return CompleteObject();
4129 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4130 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4131 if (!Alloc) {
4132 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4133 return CompleteObject();
4134 }
4135 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4136 LVal.Base.getDynamicAllocType());
4137 } else {
4138 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4139
4140 if (!Frame) {
4141 if (const MaterializeTemporaryExpr *MTE =
4142 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4143 assert(MTE->getStorageDuration() == SD_Static &&(static_cast <bool> (MTE->getStorageDuration() == SD_Static
&& "should have a frame for a non-global materialized temporary"
) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4144, __extension__ __PRETTY_FUNCTION__
))
4144 "should have a frame for a non-global materialized temporary")(static_cast <bool> (MTE->getStorageDuration() == SD_Static
&& "should have a frame for a non-global materialized temporary"
) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4144, __extension__ __PRETTY_FUNCTION__
))
;
4145
4146 // C++20 [expr.const]p4: [DR2126]
4147 // An object or reference is usable in constant expressions if it is
4148 // - a temporary object of non-volatile const-qualified literal type
4149 // whose lifetime is extended to that of a variable that is usable
4150 // in constant expressions
4151 //
4152 // C++20 [expr.const]p5:
4153 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4154 // - a non-volatile glvalue that refers to an object that is usable
4155 // in constant expressions, or
4156 // - a non-volatile glvalue of literal type that refers to a
4157 // non-volatile object whose lifetime began within the evaluation
4158 // of E;
4159 //
4160 // C++11 misses the 'began within the evaluation of e' check and
4161 // instead allows all temporaries, including things like:
4162 // int &&r = 1;
4163 // int x = ++r;
4164 // constexpr int k = r;
4165 // Therefore we use the C++14-onwards rules in C++11 too.
4166 //
4167 // Note that temporaries whose lifetimes began while evaluating a
4168 // variable's constructor are not usable while evaluating the
4169 // corresponding destructor, not even if they're of const-qualified
4170 // types.
4171 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4172 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4173 if (!IsAccess)
4174 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4175 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4176 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4177 return CompleteObject();
4178 }
4179
4180 BaseVal = MTE->getOrCreateValue(false);
4181 assert(BaseVal && "got reference to unevaluated temporary")(static_cast <bool> (BaseVal && "got reference to unevaluated temporary"
) ? void (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4181, __extension__ __PRETTY_FUNCTION__
))
;
4182 } else {
4183 if (!IsAccess)
4184 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4185 APValue Val;
4186 LVal.moveInto(Val);
4187 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4188 << AK
4189 << Val.getAsString(Info.Ctx,
4190 Info.Ctx.getLValueReferenceType(LValType));
4191 NoteLValueLocation(Info, LVal.Base);
4192 return CompleteObject();
4193 }
4194 } else {
4195 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4196 assert(BaseVal && "missing value for temporary")(static_cast <bool> (BaseVal && "missing value for temporary"
) ? void (0) : __assert_fail ("BaseVal && \"missing value for temporary\""
, "clang/lib/AST/ExprConstant.cpp", 4196, __extension__ __PRETTY_FUNCTION__
))
;
4197 }
4198 }
4199
4200 // In C++14, we can't safely access any mutable state when we might be
4201 // evaluating after an unmodeled side effect. Parameters are modeled as state
4202 // in the caller, but aren't visible once the call returns, so they can be
4203 // modified in a speculatively-evaluated call.
4204 //
4205 // FIXME: Not all local state is mutable. Allow local constant subobjects
4206 // to be read here (but take care with 'mutable' fields).
4207 unsigned VisibleDepth = Depth;
4208 if (llvm::isa_and_nonnull<ParmVarDecl>(
4209 LVal.Base.dyn_cast<const ValueDecl *>()))
4210 ++VisibleDepth;
4211 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4212 Info.EvalStatus.HasSideEffects) ||
4213 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4214 return CompleteObject();
4215
4216 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4217}
4218
4219/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4220/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4221/// glvalue referred to by an entity of reference type.
4222///
4223/// \param Info - Information about the ongoing evaluation.
4224/// \param Conv - The expression for which we are performing the conversion.
4225/// Used for diagnostics.
4226/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4227/// case of a non-class type).
4228/// \param LVal - The glvalue on which we are attempting to perform this action.
4229/// \param RVal - The produced value will be placed here.
4230/// \param WantObjectRepresentation - If true, we're looking for the object
4231/// representation rather than the value, and in particular,
4232/// there is no requirement that the result be fully initialized.
4233static bool
4234handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4235 const LValue &LVal, APValue &RVal,
4236 bool WantObjectRepresentation = false) {
4237 if (LVal.Designator.Invalid)
4238 return false;
4239
4240 // Check for special cases where there is no existing APValue to look at.
4241 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4242
4243 AccessKinds AK =
4244 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4245
4246 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4247 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4248 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4249 // initializer until now for such expressions. Such an expression can't be
4250 // an ICE in C, so this only matters for fold.
4251 if (Type.isVolatileQualified()) {
4252 Info.FFDiag(Conv);
4253 return false;
4254 }
4255
4256 APValue Lit;
4257 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4258 return false;
4259
4260 // According to GCC info page:
4261 //
4262 // 6.28 Compound Literals
4263 //
4264 // As an optimization, G++ sometimes gives array compound literals longer
4265 // lifetimes: when the array either appears outside a function or has a
4266 // const-qualified type. If foo and its initializer had elements of type
4267 // char *const rather than char *, or if foo were a global variable, the
4268 // array would have static storage duration. But it is probably safest
4269 // just to avoid the use of array compound literals in C++ code.
4270 //
4271 // Obey that rule by checking constness for converted array types.
4272
4273 QualType CLETy = CLE->getType();
4274 if (CLETy->isArrayType() && !Type->isArrayType()) {
4275 if (!CLETy.isConstant(Info.Ctx)) {
4276 Info.FFDiag(Conv);
4277 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4278 return false;
4279 }
4280 }
4281
4282 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4283 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4284 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4285 // Special-case character extraction so we don't have to construct an
4286 // APValue for the whole string.
4287 assert(LVal.Designator.Entries.size() <= 1 &&(static_cast <bool> (LVal.Designator.Entries.size() <=
1 && "Can only read characters from string literals"
) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\""
, "clang/lib/AST/ExprConstant.cpp", 4288, __extension__ __PRETTY_FUNCTION__
))
4288 "Can only read characters from string literals")(static_cast <bool> (LVal.Designator.Entries.size() <=
1 && "Can only read characters from string literals"
) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\""
, "clang/lib/AST/ExprConstant.cpp", 4288, __extension__ __PRETTY_FUNCTION__
))
;
4289 if (LVal.Designator.Entries.empty()) {
4290 // Fail for now for LValue to RValue conversion of an array.
4291 // (This shouldn't show up in C/C++, but it could be triggered by a
4292 // weird EvaluateAsRValue call from a tool.)
4293 Info.FFDiag(Conv);
4294 return false;
4295 }
4296 if (LVal.Designator.isOnePastTheEnd()) {
4297 if (Info.getLangOpts().CPlusPlus11)
4298 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4299 else
4300 Info.FFDiag(Conv);
4301 return false;
4302 }
4303 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4304 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4305 return true;
4306 }
4307 }
4308
4309 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4310 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4311}
4312
4313/// Perform an assignment of Val to LVal. Takes ownership of Val.
4314static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4315 QualType LValType, APValue &Val) {
4316 if (LVal.Designator.Invalid)
4317 return false;
4318
4319 if (!Info.getLangOpts().CPlusPlus14) {
4320 Info.FFDiag(E);
4321 return false;
4322 }
4323
4324 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4325 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4326}
4327
4328namespace {
4329struct CompoundAssignSubobjectHandler {
4330 EvalInfo &Info;
4331 const CompoundAssignOperator *E;
4332 QualType PromotedLHSType;
4333 BinaryOperatorKind Opcode;
4334 const APValue &RHS;
4335
4336 static const AccessKinds AccessKind = AK_Assign;
4337
4338 typedef bool result_type;
4339
4340 bool checkConst(QualType QT) {
4341 // Assigning to a const object has undefined behavior.
4342 if (QT.isConstQualified()) {
4343 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4344 return false;
4345 }
4346 return true;
4347 }
4348
4349 bool failed() { return false; }
4350 bool found(APValue &Subobj, QualType SubobjType) {
4351 switch (Subobj.getKind()) {
4352 case APValue::Int:
4353 return found(Subobj.getInt(), SubobjType);
4354 case APValue::Float:
4355 return found(Subobj.getFloat(), SubobjType);
4356 case APValue::ComplexInt:
4357 case APValue::ComplexFloat:
4358 // FIXME: Implement complex compound assignment.
4359 Info.FFDiag(E);
4360 return false;
4361 case APValue::LValue:
4362 return foundPointer(Subobj, SubobjType);
4363 case APValue::Vector:
4364 return foundVector(Subobj, SubobjType);
4365 default:
4366 // FIXME: can this happen?
4367 Info.FFDiag(E);
4368 return false;
4369 }
4370 }
4371
4372 bool foundVector(APValue &Value, QualType SubobjType) {
4373 if (!checkConst(SubobjType))
4374 return false;
4375
4376 if (!SubobjType->isVectorType()) {
4377 Info.FFDiag(E);
4378 return false;
4379 }
4380 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4381 }
4382
4383 bool found(APSInt &Value, QualType SubobjType) {
4384 if (!checkConst(SubobjType))
4385 return false;
4386
4387 if (!SubobjType->isIntegerType()) {
4388 // We don't support compound assignment on integer-cast-to-pointer
4389 // values.
4390 Info.FFDiag(E);
4391 return false;
4392 }
4393
4394 if (RHS.isInt()) {
4395 APSInt LHS =
4396 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4397 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4398 return false;
4399 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4400 return true;
4401 } else if (RHS.isFloat()) {
4402 const FPOptions FPO = E->getFPFeaturesInEffect(
4403 Info.Ctx.getLangOpts());
4404 APFloat FValue(0.0);
4405 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4406 PromotedLHSType, FValue) &&
4407 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4408 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4409 Value);
4410 }
4411
4412 Info.FFDiag(E);
4413 return false;
4414 }
4415 bool found(APFloat &Value, QualType SubobjType) {
4416 return checkConst(SubobjType) &&
4417 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4418 Value) &&
4419 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4420 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4421 }
4422 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4423 if (!checkConst(SubobjType))
4424 return false;
4425
4426 QualType PointeeType;
4427 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4428 PointeeType = PT->getPointeeType();
4429
4430 if (PointeeType.isNull() || !RHS.isInt() ||
4431 (Opcode != BO_Add && Opcode != BO_Sub)) {
4432 Info.FFDiag(E);
4433 return false;
4434 }
4435
4436 APSInt Offset = RHS.getInt();
4437 if (Opcode == BO_Sub)
4438 negateAsSigned(Offset);
4439
4440 LValue LVal;
4441 LVal.setFrom(Info.Ctx, Subobj);
4442 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4443 return false;
4444 LVal.moveInto(Subobj);
4445 return true;
4446 }
4447};
4448} // end anonymous namespace
4449
4450const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4451
4452/// Perform a compound assignment of LVal <op>= RVal.
4453static bool handleCompoundAssignment(EvalInfo &Info,
4454 const CompoundAssignOperator *E,
4455 const LValue &LVal, QualType LValType,
4456 QualType PromotedLValType,
4457 BinaryOperatorKind Opcode,
4458 const APValue &RVal) {
4459 if (LVal.Designator.Invalid)
4460 return false;
4461
4462 if (!Info.getLangOpts().CPlusPlus14) {
4463 Info.FFDiag(E);
4464 return false;
4465 }
4466
4467 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4468 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4469 RVal };
4470 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4471}
4472
4473namespace {
4474struct IncDecSubobjectHandler {
4475 EvalInfo &Info;
4476 const UnaryOperator *E;
4477 AccessKinds AccessKind;
4478 APValue *Old;
4479
4480 typedef bool result_type;
4481
4482 bool checkConst(QualType QT) {
4483 // Assigning to a const object has undefined behavior.
4484 if (QT.isConstQualified()) {
4485 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4486 return false;
4487 }
4488 return true;
4489 }
4490
4491 bool failed() { return false; }
4492 bool found(APValue &Subobj, QualType SubobjType) {
4493 // Stash the old value. Also clear Old, so we don't clobber it later
4494 // if we're post-incrementing a complex.
4495 if (Old) {
4496 *Old = Subobj;
4497 Old = nullptr;
4498 }
4499
4500 switch (Subobj.getKind()) {
4501 case APValue::Int:
4502 return found(Subobj.getInt(), SubobjType);
4503 case APValue::Float:
4504 return found(Subobj.getFloat(), SubobjType);
4505 case APValue::ComplexInt:
4506 return found(Subobj.getComplexIntReal(),
4507 SubobjType->castAs<ComplexType>()->getElementType()
4508 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4509 case APValue::ComplexFloat:
4510 return found(Subobj.getComplexFloatReal(),
4511 SubobjType->castAs<ComplexType>()->getElementType()
4512 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4513 case APValue::LValue:
4514 return foundPointer(Subobj, SubobjType);
4515 default:
4516 // FIXME: can this happen?
4517 Info.FFDiag(E);
4518 return false;
4519 }
4520 }
4521 bool found(APSInt &Value, QualType SubobjType) {
4522 if (!checkConst(SubobjType))
4523 return false;
4524
4525 if (!SubobjType->isIntegerType()) {
4526 // We don't support increment / decrement on integer-cast-to-pointer
4527 // values.
4528 Info.FFDiag(E);
4529 return false;
4530 }
4531
4532 if (Old) *Old = APValue(Value);
4533
4534 // bool arithmetic promotes to int, and the conversion back to bool
4535 // doesn't reduce mod 2^n, so special-case it.
4536 if (SubobjType->isBooleanType()) {
4537 if (AccessKind == AK_Increment)
4538 Value = 1;
4539 else
4540 Value = !Value;
4541 return true;
4542 }
4543
4544 bool WasNegative = Value.isNegative();
4545 if (AccessKind == AK_Increment) {
4546 ++Value;
4547
4548 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4549 APSInt ActualValue(Value, /*IsUnsigned*/true);
4550 return HandleOverflow(Info, E, ActualValue, SubobjType);
4551 }
4552 } else {
4553 --Value;
4554
4555 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4556 unsigned BitWidth = Value.getBitWidth();
4557 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4558 ActualValue.setBit(BitWidth);
4559 return HandleOverflow(Info, E, ActualValue, SubobjType);
4560 }
4561 }
4562 return true;
4563 }
4564 bool found(APFloat &Value, QualType SubobjType) {
4565 if (!checkConst(SubobjType))
4566 return false;
4567
4568 if (Old) *Old = APValue(Value);
4569
4570 APFloat One(Value.getSemantics(), 1);
4571 if (AccessKind == AK_Increment)
4572 Value.add(One, APFloat::rmNearestTiesToEven);
4573 else
4574 Value.subtract(One, APFloat::rmNearestTiesToEven);
4575 return true;
4576 }
4577 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4578 if (!checkConst(SubobjType))
4579 return false;
4580
4581 QualType PointeeType;
4582 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4583 PointeeType = PT->getPointeeType();
4584 else {
4585 Info.FFDiag(E);
4586 return false;
4587 }
4588
4589 LValue LVal;
4590 LVal.setFrom(Info.Ctx, Subobj);
4591 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4592 AccessKind == AK_Increment ? 1 : -1))
4593 return false;
4594 LVal.moveInto(Subobj);
4595 return true;
4596 }
4597};
4598} // end anonymous namespace
4599
4600/// Perform an increment or decrement on LVal.
4601static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4602 QualType LValType, bool IsIncrement, APValue *Old) {
4603 if (LVal.Designator.Invalid)
4604 return false;
4605
4606 if (!Info.getLangOpts().CPlusPlus14) {
4607 Info.FFDiag(E);
4608 return false;
4609 }
4610
4611 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4612 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4613 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4614 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4615}
4616
4617/// Build an lvalue for the object argument of a member function call.
4618static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4619 LValue &This) {
4620 if (Object->getType()->isPointerType() && Object->isPRValue())
4621 return EvaluatePointer(Object, This, Info);
4622
4623 if (Object->isGLValue())
4624 return EvaluateLValue(Object, This, Info);
4625
4626 if (Object->getType()->isLiteralType(Info.Ctx))
4627 return EvaluateTemporary(Object, This, Info);
4628
4629 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4630 return false;
4631}
4632
4633/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4634/// lvalue referring to the result.
4635///
4636/// \param Info - Information about the ongoing evaluation.
4637/// \param LV - An lvalue referring to the base of the member pointer.
4638/// \param RHS - The member pointer expression.
4639/// \param IncludeMember - Specifies whether the member itself is included in
4640/// the resulting LValue subobject designator. This is not possible when
4641/// creating a bound member function.
4642/// \return The field or method declaration to which the member pointer refers,
4643/// or 0 if evaluation fails.
4644static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4645 QualType LVType,
4646 LValue &LV,
4647 const Expr *RHS,
4648 bool IncludeMember = true) {
4649 MemberPtr MemPtr;
4650 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4651 return nullptr;
4652
4653 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4654 // member value, the behavior is undefined.
4655 if (!MemPtr.getDecl()) {
4656 // FIXME: Specific diagnostic.
4657 Info.FFDiag(RHS);
4658 return nullptr;
4659 }
4660
4661 if (MemPtr.isDerivedMember()) {
4662 // This is a member of some derived class. Truncate LV appropriately.
4663 // The end of the derived-to-base path for the base object must match the
4664 // derived-to-base path for the member pointer.
4665 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4666 LV.Designator.Entries.size()) {
4667 Info.FFDiag(RHS);
4668 return nullptr;
4669 }
4670 unsigned PathLengthToMember =
4671 LV.Designator.Entries.size() - MemPtr.Path.size();
4672 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4673 const CXXRecordDecl *LVDecl = getAsBaseClass(
4674 LV.Designator.Entries[PathLengthToMember + I]);
4675 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4676 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4677 Info.FFDiag(RHS);
4678 return nullptr;
4679 }
4680 }
4681
4682 // Truncate the lvalue to the appropriate derived class.
4683 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4684 PathLengthToMember))
4685 return nullptr;
4686 } else if (!MemPtr.Path.empty()) {
4687 // Extend the LValue path with the member pointer's path.
4688 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4689 MemPtr.Path.size() + IncludeMember);
4690
4691 // Walk down to the appropriate base class.
4692 if (const PointerType *PT = LVType->getAs<PointerType>())
4693 LVType = PT->getPointeeType();
4694 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4695 assert(RD && "member pointer access on non-class-type expression")(static_cast <bool> (RD && "member pointer access on non-class-type expression"
) ? void (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\""
, "clang/lib/AST/ExprConstant.cpp", 4695, __extension__ __PRETTY_FUNCTION__
))
;
4696 // The first class in the path is that of the lvalue.
4697 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4698 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4699 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4700 return nullptr;
4701 RD = Base;
4702 }
4703 // Finally cast to the class containing the member.
4704 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4705 MemPtr.getContainingRecord()))
4706 return nullptr;
4707 }
4708
4709 // Add the member. Note that we cannot build bound member functions here.
4710 if (IncludeMember) {
4711 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4712 if (!HandleLValueMember(Info, RHS, LV, FD))
4713 return nullptr;
4714 } else if (const IndirectFieldDecl *IFD =
4715 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4716 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4717 return nullptr;
4718 } else {
4719 llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function"
, "clang/lib/AST/ExprConstant.cpp", 4719)
;
4720 }
4721 }
4722
4723 return MemPtr.getDecl();
4724}
4725
4726static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4727 const BinaryOperator *BO,
4728 LValue &LV,
4729 bool IncludeMember = true) {
4730 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)(static_cast <bool> (BO->getOpcode() == BO_PtrMemD ||
BO->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail
("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI"
, "clang/lib/AST/ExprConstant.cpp", 4730, __extension__ __PRETTY_FUNCTION__
))
;
4731
4732 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4733 if (Info.noteFailure()) {
4734 MemberPtr MemPtr;
4735 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4736 }
4737 return nullptr;
4738 }
4739
4740 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4741 BO->getRHS(), IncludeMember);
4742}
4743
4744/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4745/// the provided lvalue, which currently refers to the base object.
4746static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4747 LValue &Result) {
4748 SubobjectDesignator &D = Result.Designator;
4749 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4750 return false;
4751
4752 QualType TargetQT = E->getType();
4753 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4754 TargetQT = PT->getPointeeType();
4755
4756 // Check this cast lands within the final derived-to-base subobject path.
4757 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4758 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4759 << D.MostDerivedType << TargetQT;
4760 return false;
4761 }
4762
4763 // Check the type of the final cast. We don't need to check the path,
4764 // since a cast can only be formed if the path is unique.
4765 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4766 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4767 const CXXRecordDecl *FinalType;
4768 if (NewEntriesSize == D.MostDerivedPathLength)
4769 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4770 else
4771 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4772 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4773 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4774 << D.MostDerivedType << TargetQT;
4775 return false;
4776 }
4777
4778 // Truncate the lvalue to the appropriate derived class.
4779 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4780}
4781
4782/// Get the value to use for a default-initialized object of type T.
4783/// Return false if it encounters something invalid.
4784static bool getDefaultInitValue(QualType T, APValue &Result) {
4785 bool Success = true;
4786 if (auto *RD = T->getAsCXXRecordDecl()) {
4787 if (RD->isInvalidDecl()) {
4788 Result = APValue();
4789 return false;
4790 }
4791 if (RD->isUnion()) {
4792 Result = APValue((const FieldDecl *)nullptr);
4793 return true;
4794 }
4795 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4796 std::distance(RD->field_begin(), RD->field_end()));
4797
4798 unsigned Index = 0;
4799 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4800 End = RD->bases_end();
4801 I != End; ++I, ++Index)
4802 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4803
4804 for (const auto *I : RD->fields()) {
4805 if (I->isUnnamedBitfield())
4806 continue;
4807 Success &= getDefaultInitValue(I->getType(),
4808 Result.getStructField(I->getFieldIndex()));
4809 }
4810 return Success;
4811 }
4812
4813 if (auto *AT =
4814 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4815 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4816 if (Result.hasArrayFiller())
4817 Success &=
4818 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4819
4820 return Success;
4821 }
4822
4823 Result = APValue::IndeterminateValue();
4824 return true;
4825}
4826
4827namespace {
4828enum EvalStmtResult {
4829 /// Evaluation failed.
4830 ESR_Failed,
4831 /// Hit a 'return' statement.
4832 ESR_Returned,
4833 /// Evaluation succeeded.
4834 ESR_Succeeded,
4835 /// Hit a 'continue' statement.
4836 ESR_Continue,
4837 /// Hit a 'break' statement.
4838 ESR_Break,
4839 /// Still scanning for 'case' or 'default' statement.
4840 ESR_CaseNotFound
4841};
4842}
4843
4844static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4845 if (VD->isInvalidDecl())
4846 return false;
4847 // We don't need to evaluate the initializer for a static local.
4848 if (!VD->hasLocalStorage())
4849 return true;
4850
4851 LValue Result;
4852 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4853 ScopeKind::Block, Result);
4854
4855 const Expr *InitE = VD->getInit();
4856 if (!InitE) {
4857 if (VD->getType()->isDependentType())
4858 return Info.noteSideEffect();
4859 return getDefaultInitValue(VD->getType(), Val);
4860 }
4861 if (InitE->isValueDependent())
4862 return false;
4863
4864 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4865 // Wipe out any partially-computed value, to allow tracking that this
4866 // evaluation failed.
4867 Val = APValue();
4868 return false;
4869 }
4870
4871 return true;
4872}
4873
4874static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4875 bool OK = true;
4876
4877 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4878 OK &= EvaluateVarDecl(Info, VD);
4879
4880 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4881 for (auto *BD : DD->bindings())
4882 if (auto *VD = BD->getHoldingVar())
4883 OK &= EvaluateDecl(Info, VD);
4884
4885 return OK;
4886}
4887
4888static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4889 assert(E->isValueDependent())(static_cast <bool> (E->isValueDependent()) ? void (
0) : __assert_fail ("E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp"
, 4889, __extension__ __PRETTY_FUNCTION__))
;
4890 if (Info.noteSideEffect())
4891 return true;
4892 assert(E->containsErrors() && "valid value-dependent expression should never "(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never "
"reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\""
, "clang/lib/AST/ExprConstant.cpp", 4893, __extension__ __PRETTY_FUNCTION__
))
4893 "reach invalid code path.")(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never "
"reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\""
, "clang/lib/AST/ExprConstant.cpp", 4893, __extension__ __PRETTY_FUNCTION__
))
;
4894 return false;
4895}
4896
4897/// Evaluate a condition (either a variable declaration or an expression).
4898static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4899 const Expr *Cond, bool &Result) {
4900 if (Cond->isValueDependent())
4901 return false;
4902 FullExpressionRAII Scope(Info);
4903 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4904 return false;
4905 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4906 return false;
4907 return Scope.destroy();
4908}
4909
4910namespace {
4911/// A location where the result (returned value) of evaluating a
4912/// statement should be stored.
4913struct StmtResult {
4914 /// The APValue that should be filled in with the returned value.
4915 APValue &Value;
4916 /// The location containing the result, if any (used to support RVO).
4917 const LValue *Slot;
4918};
4919
4920struct TempVersionRAII {
4921 CallStackFrame &Frame;
4922
4923 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4924 Frame.pushTempVersion();
4925 }
4926
4927 ~TempVersionRAII() {
4928 Frame.popTempVersion();
4929 }
4930};
4931
4932}
4933
4934static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4935 const Stmt *S,
4936 const SwitchCase *SC = nullptr);
4937
4938/// Evaluate the body of a loop, and translate the result as appropriate.
4939static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4940 const Stmt *Body,
4941 const SwitchCase *Case = nullptr) {
4942 BlockScopeRAII Scope(Info);
4943
4944 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4945 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4946 ESR = ESR_Failed;
4947
4948 switch (ESR) {
4949 case ESR_Break:
4950 return ESR_Succeeded;
4951 case ESR_Succeeded:
4952 case ESR_Continue:
4953 return ESR_Continue;
4954 case ESR_Failed:
4955 case ESR_Returned:
4956 case ESR_CaseNotFound:
4957 return ESR;
4958 }
4959 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp"
, 4959)
;
4960}
4961
4962/// Evaluate a switch statement.
4963static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4964 const SwitchStmt *SS) {
4965 BlockScopeRAII Scope(Info);
4966
4967 // Evaluate the switch condition.
4968 APSInt Value;
4969 {
4970 if (const Stmt *Init = SS->getInit()) {
4971 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4972 if (ESR != ESR_Succeeded) {
4973 if (ESR != ESR_Failed && !Scope.destroy())
4974 ESR = ESR_Failed;
4975 return ESR;
4976 }
4977 }
4978
4979 FullExpressionRAII CondScope(Info);
4980 if (SS->getConditionVariable() &&
4981 !EvaluateDecl(Info, SS->getConditionVariable()))
4982 return ESR_Failed;
4983 if (SS->getCond()->isValueDependent()) {
4984 if (!EvaluateDependentExpr(SS->getCond(), Info))
4985 return ESR_Failed;
4986 } else {
4987 if (!EvaluateInteger(SS->getCond(), Value, Info))
4988 return ESR_Failed;
4989 }
4990 if (!CondScope.destroy())
4991 return ESR_Failed;
4992 }
4993
4994 // Find the switch case corresponding to the value of the condition.
4995 // FIXME: Cache this lookup.
4996 const SwitchCase *Found = nullptr;
4997 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4998 SC = SC->getNextSwitchCase()) {
4999 if (isa<DefaultStmt>(SC)) {
5000 Found = SC;
5001 continue;
5002 }
5003
5004 const CaseStmt *CS = cast<CaseStmt>(SC);
5005 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5006 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5007 : LHS;
5008 if (LHS <= Value && Value <= RHS) {
5009 Found = SC;
5010 break;
5011 }
5012 }
5013
5014 if (!Found)
5015 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5016
5017 // Search the switch body for the switch case and evaluate it from there.
5018 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5019 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5020 return ESR_Failed;
5021
5022 switch (ESR) {
5023 case ESR_Break:
5024 return ESR_Succeeded;
5025 case ESR_Succeeded:
5026 case ESR_Continue:
5027 case ESR_Failed:
5028 case ESR_Returned:
5029 return ESR;
5030 case ESR_CaseNotFound:
5031 // This can only happen if the switch case is nested within a statement
5032 // expression. We have no intention of supporting that.
5033 Info.FFDiag(Found->getBeginLoc(),
5034 diag::note_constexpr_stmt_expr_unsupported);
5035 return ESR_Failed;
5036 }
5037 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp"
, 5037)
;
5038}
5039
5040static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5041 // An expression E is a core constant expression unless the evaluation of E
5042 // would evaluate one of the following: [C++2b] - a control flow that passes
5043 // through a declaration of a variable with static or thread storage duration.
5044 if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5045 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5046 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5047 return false;
5048 }
5049 return true;
5050}
5051
5052// Evaluate a statement.
5053static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5054 const Stmt *S, const SwitchCase *Case) {
5055 if (!Info.nextStep(S))
5056 return ESR_Failed;
5057
5058 // If we're hunting down a 'case' or 'default' label, recurse through
5059 // substatements until we hit the label.
5060 if (Case) {
5061 switch (S->getStmtClass()) {
5062 case Stmt::CompoundStmtClass:
5063 // FIXME: Precompute which substatement of a compound statement we
5064 // would jump to, and go straight there rather than performing a
5065 // linear scan each time.
5066 case Stmt::LabelStmtClass:
5067 case Stmt::AttributedStmtClass:
5068 case Stmt::DoStmtClass:
5069 break;
5070
5071 case Stmt::CaseStmtClass:
5072 case Stmt::DefaultStmtClass:
5073 if (Case == S)
5074 Case = nullptr;
5075 break;
5076
5077 case Stmt::IfStmtClass: {
5078 // FIXME: Precompute which side of an 'if' we would jump to, and go
5079 // straight there rather than scanning both sides.
5080 const IfStmt *IS = cast<IfStmt>(S);
5081
5082 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5083 // preceded by our switch label.
5084 BlockScopeRAII Scope(Info);
5085
5086 // Step into the init statement in case it brings an (uninitialized)
5087 // variable into scope.
5088 if (const Stmt *Init = IS->getInit()) {
5089 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5090 if (ESR != ESR_CaseNotFound) {
5091 assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) :
__assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp"
, 5091, __extension__ __PRETTY_FUNCTION__))
;
5092 return ESR;
5093 }
5094 }
5095
5096 // Condition variable must be initialized if it exists.
5097 // FIXME: We can skip evaluating the body if there's a condition
5098 // variable, as there can't be any case labels within it.
5099 // (The same is true for 'for' statements.)
5100
5101 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5102 if (ESR == ESR_Failed)
5103 return ESR;
5104 if (ESR != ESR_CaseNotFound)
5105 return Scope.destroy() ? ESR : ESR_Failed;
5106 if (!IS->getElse())
5107 return ESR_CaseNotFound;
5108
5109 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5110 if (ESR == ESR_Failed)
5111 return ESR;
5112 if (ESR != ESR_CaseNotFound)
5113 return Scope.destroy() ? ESR : ESR_Failed;
5114 return ESR_CaseNotFound;
5115 }
5116
5117 case Stmt::WhileStmtClass: {
5118 EvalStmtResult ESR =
5119 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5120 if (ESR != ESR_Continue)
5121 return ESR;
5122 break;
5123 }
5124
5125 case Stmt::ForStmtClass: {
5126 const ForStmt *FS = cast<ForStmt>(S);
5127 BlockScopeRAII Scope(Info);
5128
5129 // Step into the init statement in case it brings an (uninitialized)
5130 // variable into scope.
5131 if (const Stmt *Init = FS->getInit()) {
5132 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5133 if (ESR != ESR_CaseNotFound) {
5134 assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) :
__assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp"
, 5134, __extension__ __PRETTY_FUNCTION__))
;
5135 return ESR;
5136 }
5137 }
5138
5139 EvalStmtResult ESR =
5140 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5141 if (ESR != ESR_Continue)
5142 return ESR;
5143 if (const auto *Inc = FS->getInc()) {
5144 if (Inc->isValueDependent()) {
5145 if (!EvaluateDependentExpr(Inc, Info))
5146 return ESR_Failed;
5147 } else {
5148 FullExpressionRAII IncScope(Info);
5149 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5150 return ESR_Failed;
5151 }
5152 }
5153 break;
5154 }
5155
5156 case Stmt::DeclStmtClass: {
5157 // Start the lifetime of any uninitialized variables we encounter. They
5158 // might be used by the selected branch of the switch.
5159 const DeclStmt *DS = cast<DeclStmt>(S);
5160 for (const auto *D : DS->decls()) {
5161 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5162 if (!CheckLocalVariableDeclaration(Info, VD))
5163 return ESR_Failed;
5164 if (VD->hasLocalStorage() && !VD->getInit())
5165 if (!EvaluateVarDecl(Info, VD))
5166 return ESR_Failed;
5167 // FIXME: If the variable has initialization that can't be jumped
5168 // over, bail out of any immediately-surrounding compound-statement
5169 // too. There can't be any case labels here.
5170 }
5171 }
5172 return ESR_CaseNotFound;
5173 }
5174
5175 default:
5176 return ESR_CaseNotFound;
5177 }
5178 }
5179
5180 switch (S->getStmtClass()) {
5181 default:
5182 if (const Expr *E = dyn_cast<Expr>(S)) {
5183 if (E->isValueDependent()) {
5184 if (!EvaluateDependentExpr(E, Info))
5185 return ESR_Failed;
5186 } else {
5187 // Don't bother evaluating beyond an expression-statement which couldn't
5188 // be evaluated.
5189 // FIXME: Do we need the FullExpressionRAII object here?
5190 // VisitExprWithCleanups should create one when necessary.
5191 FullExpressionRAII Scope(Info);
5192 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5193 return ESR_Failed;
5194 }
5195 return ESR_Succeeded;
5196 }
5197
5198 Info.FFDiag(S->getBeginLoc());
5199 return ESR_Failed;
5200
5201 case Stmt::NullStmtClass:
5202 return ESR_Succeeded;
5203
5204 case Stmt::DeclStmtClass: {
5205 const DeclStmt *DS = cast<DeclStmt>(S);
5206 for (const auto *D : DS->decls()) {
5207 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5208 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5209 return ESR_Failed;
5210 // Each declaration initialization is its own full-expression.
5211 FullExpressionRAII Scope(Info);
5212 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5213 return ESR_Failed;
5214 if (!Scope.destroy())
5215 return ESR_Failed;
5216 }
5217 return ESR_Succeeded;
5218 }
5219
5220 case Stmt::ReturnStmtClass: {
5221 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5222 FullExpressionRAII Scope(Info);
5223 if (RetExpr && RetExpr->isValueDependent()) {
5224 EvaluateDependentExpr(RetExpr, Info);
5225 // We know we returned, but we don't know what the value is.
5226 return ESR_Failed;
5227 }
5228 if (RetExpr &&
5229 !(Result.Slot
5230 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5231 : Evaluate(Result.Value, Info, RetExpr)))
5232 return ESR_Failed;
5233 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5234 }
5235
5236 case Stmt::CompoundStmtClass: {
5237 BlockScopeRAII Scope(Info);
5238
5239 const CompoundStmt *CS = cast<CompoundStmt>(S);
5240 for (const auto *BI : CS->body()) {
5241 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5242 if (ESR == ESR_Succeeded)
5243 Case = nullptr;
5244 else if (ESR != ESR_CaseNotFound) {
5245 if (ESR != ESR_Failed && !Scope.destroy())
5246 return ESR_Failed;
5247 return ESR;
5248 }
5249 }
5250 if (Case)
5251 return ESR_CaseNotFound;
5252 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5253 }
5254
5255 case Stmt::IfStmtClass: {
5256 const IfStmt *IS = cast<IfStmt>(S);
5257
5258 // Evaluate the condition, as either a var decl or as an expression.
5259 BlockScopeRAII Scope(Info);
5260 if (const Stmt *Init = IS->getInit()) {
5261 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5262 if (ESR != ESR_Succeeded) {
5263 if (ESR != ESR_Failed && !Scope.destroy())
5264 return ESR_Failed;
5265 return ESR;
5266 }
5267 }
5268 bool Cond;
5269 if (IS->isConsteval()) {
5270 Cond = IS->isNonNegatedConsteval();
5271 // If we are not in a constant context, if consteval should not evaluate
5272 // to true.
5273 if (!Info.InConstantContext)
5274 Cond = !Cond;
5275 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5276 Cond))
5277 return ESR_Failed;
5278
5279 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5280 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5281 if (ESR != ESR_Succeeded) {
5282 if (ESR != ESR_Failed && !Scope.destroy())
5283 return ESR_Failed;
5284 return ESR;
5285 }
5286 }
5287 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5288 }
5289
5290 case Stmt::WhileStmtClass: {
5291 const WhileStmt *WS = cast<WhileStmt>(S);
5292 while (true) {
5293 BlockScopeRAII Scope(Info);
5294 bool Continue;
5295 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5296 Continue))
5297 return ESR_Failed;
5298 if (!Continue)
5299 break;
5300
5301 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5302 if (ESR != ESR_Continue) {
5303 if (ESR != ESR_Failed && !Scope.destroy())
5304 return ESR_Failed;
5305 return ESR;
5306 }
5307 if (!Scope.destroy())
5308 return ESR_Failed;
5309 }
5310 return ESR_Succeeded;
5311 }
5312
5313 case Stmt::DoStmtClass: {
5314 const DoStmt *DS = cast<DoStmt>(S);
5315 bool Continue;
5316 do {
5317 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5318 if (ESR != ESR_Continue)
5319 return ESR;
5320 Case = nullptr;
5321
5322 if (DS->getCond()->isValueDependent()) {
5323 EvaluateDependentExpr(DS->getCond(), Info);
5324 // Bailout as we don't know whether to keep going or terminate the loop.
5325 return ESR_Failed;
5326 }
5327 FullExpressionRAII CondScope(Info);
5328 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5329 !CondScope.destroy())
5330 return ESR_Failed;
5331 } while (Continue);
5332 return ESR_Succeeded;
5333 }
5334
5335 case Stmt::ForStmtClass: {
5336 const ForStmt *FS = cast<ForStmt>(S);
5337 BlockScopeRAII ForScope(Info);
5338 if (FS->getInit()) {
5339 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5340 if (ESR != ESR_Succeeded) {
5341 if (ESR != ESR_Failed && !ForScope.destroy())
5342 return ESR_Failed;
5343 return ESR;
5344 }
5345 }
5346 while (true) {
5347 BlockScopeRAII IterScope(Info);
5348 bool Continue = true;
5349 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5350 FS->getCond(), Continue))
5351 return ESR_Failed;
5352 if (!Continue)
5353 break;
5354
5355 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5356 if (ESR != ESR_Continue) {
5357 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5358 return ESR_Failed;
5359 return ESR;
5360 }
5361
5362 if (const auto *Inc = FS->getInc()) {
5363 if (Inc->isValueDependent()) {
5364 if (!EvaluateDependentExpr(Inc, Info))
5365 return ESR_Failed;
5366 } else {
5367 FullExpressionRAII IncScope(Info);
5368 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5369 return ESR_Failed;
5370 }
5371 }
5372
5373 if (!IterScope.destroy())
5374 return ESR_Failed;
5375 }
5376 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5377 }
5378
5379 case Stmt::CXXForRangeStmtClass: {
5380 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5381 BlockScopeRAII Scope(Info);
5382
5383 // Evaluate the init-statement if present.
5384 if (FS->getInit()) {
5385 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5386 if (ESR != ESR_Succeeded) {
5387 if (ESR != ESR_Failed && !Scope.destroy())
5388 return ESR_Failed;
5389 return ESR;
5390 }
5391 }
5392
5393 // Initialize the __range variable.
5394 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5395 if (ESR != ESR_Succeeded) {
5396 if (ESR != ESR_Failed && !Scope.destroy())
5397 return ESR_Failed;
5398 return ESR;
5399 }
5400
5401 // In error-recovery cases it's possible to get here even if we failed to
5402 // synthesize the __begin and __end variables.
5403 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5404 return ESR_Failed;
5405
5406 // Create the __begin and __end iterators.
5407 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5408 if (ESR != ESR_Succeeded) {
5409 if (ESR != ESR_Failed && !Scope.destroy())
5410 return ESR_Failed;
5411 return ESR;
5412 }
5413 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5414 if (ESR != ESR_Succeeded) {
5415 if (ESR != ESR_Failed && !Scope.destroy())
5416 return ESR_Failed;
5417 return ESR;
5418 }
5419
5420 while (true) {
5421 // Condition: __begin != __end.
5422 {
5423 if (FS->getCond()->isValueDependent()) {
5424 EvaluateDependentExpr(FS->getCond(), Info);
5425 // We don't know whether to keep going or terminate the loop.
5426 return ESR_Failed;
5427 }
5428 bool Continue = true;
5429 FullExpressionRAII CondExpr(Info);
5430 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5431 return ESR_Failed;
5432 if (!Continue)
5433 break;
5434 }
5435
5436 // User's variable declaration, initialized by *__begin.
5437 BlockScopeRAII InnerScope(Info);
5438 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5439 if (ESR != ESR_Succeeded) {
5440 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5441 return ESR_Failed;
5442 return ESR;
5443 }
5444
5445 // Loop body.
5446 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5447 if (ESR != ESR_Continue) {
5448 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5449 return ESR_Failed;
5450 return ESR;
5451 }
5452 if (FS->getInc()->isValueDependent()) {
5453 if (!EvaluateDependentExpr(FS->getInc(), Info))
5454 return ESR_Failed;
5455 } else {
5456 // Increment: ++__begin
5457 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5458 return ESR_Failed;
5459 }
5460
5461 if (!InnerScope.destroy())
5462 return ESR_Failed;
5463 }
5464
5465 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5466 }
5467
5468 case Stmt::SwitchStmtClass:
5469 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5470
5471 case Stmt::ContinueStmtClass:
5472 return ESR_Continue;
5473
5474 case Stmt::BreakStmtClass:
5475 return ESR_Break;
5476
5477 case Stmt::LabelStmtClass:
5478 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5479
5480 case Stmt::AttributedStmtClass:
5481 // As a general principle, C++11 attributes can be ignored without
5482 // any semantic impact.
5483 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5484 Case);
5485
5486 case Stmt::CaseStmtClass:
5487 case Stmt::DefaultStmtClass:
5488 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5489 case Stmt::CXXTryStmtClass:
5490 // Evaluate try blocks by evaluating all sub statements.
5491 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5492 }
5493}
5494
5495/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5496/// default constructor. If so, we'll fold it whether or not it's marked as
5497/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5498/// so we need special handling.
5499static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5500 const CXXConstructorDecl *CD,
5501 bool IsValueInitialization) {
5502 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5503 return false;
5504
5505 // Value-initialization does not call a trivial default constructor, so such a
5506 // call is a core constant expression whether or not the constructor is
5507 // constexpr.
5508 if (!CD->isConstexpr() && !IsValueInitialization) {
5509 if (Info.getLangOpts().CPlusPlus11) {
5510 // FIXME: If DiagDecl is an implicitly-declared special member function,
5511 // we should be much more explicit about why it's not constexpr.
5512 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5513 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5514 Info.Note(CD->getLocation(), diag::note_declared_at);
5515 } else {
5516 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5517 }
5518 }
5519 return true;
5520}
5521
5522/// CheckConstexprFunction - Check that a function can be called in a constant
5523/// expression.
5524static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5525 const FunctionDecl *Declaration,
5526 const FunctionDecl *Definition,
5527 const Stmt *Body) {
5528 // Potential constant expressions can contain calls to declared, but not yet
5529 // defined, constexpr functions.
5530 if (Info.checkingPotentialConstantExpression() && !Definition &&
5531 Declaration->isConstexpr())
5532 return false;
5533
5534 // Bail out if the function declaration itself is invalid. We will
5535 // have produced a relevant diagnostic while parsing it, so just
5536 // note the problematic sub-expression.
5537 if (Declaration->isInvalidDecl()) {
5538 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5539 return false;
5540 }
5541
5542 // DR1872: An instantiated virtual constexpr function can't be called in a
5543 // constant expression (prior to C++20). We can still constant-fold such a
5544 // call.
5545 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5546 cast<CXXMethodDecl>(Declaration)->isVirtual())
5547 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5548
5549 if (Definition && Definition->isInvalidDecl()) {
5550 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5551 return false;
5552 }
5553
5554 // Can we evaluate this function call?
5555 if (Definition && Definition->isConstexpr() && Body)
5556 return true;
5557
5558 if (Info.getLangOpts().CPlusPlus11) {
5559 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5560
5561 // If this function is not constexpr because it is an inherited
5562 // non-constexpr constructor, diagnose that directly.
5563 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5564 if (CD && CD->isInheritingConstructor()) {
5565 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5566 if (!Inherited->isConstexpr())
5567 DiagDecl = CD = Inherited;
5568 }
5569
5570 // FIXME: If DiagDecl is an implicitly-declared special member function
5571 // or an inheriting constructor, we should be much more explicit about why
5572 // it's not constexpr.
5573 if (CD && CD->isInheritingConstructor())
5574 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5575 << CD->getInheritedConstructor().getConstructor()->getParent();
5576 else
5577 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5578 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5579 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5580 } else {
5581 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5582 }
5583 return false;
5584}
5585
5586namespace {
5587struct CheckDynamicTypeHandler {
5588 AccessKinds AccessKind;
5589 typedef bool result_type;
5590 bool failed() { return false; }
5591 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5592 bool found(APSInt &Value, QualType SubobjType) { return true; }
5593 bool found(APFloat &Value, QualType SubobjType) { return true; }
5594};
5595} // end anonymous namespace
5596
5597/// Check that we can access the notional vptr of an object / determine its
5598/// dynamic type.
5599static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5600 AccessKinds AK, bool Polymorphic) {
5601 if (This.Designator.Invalid)
5602 return false;
5603
5604 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5605
5606 if (!Obj)
5607 return false;
5608
5609 if (!Obj.Value) {
5610 // The object is not usable in constant expressions, so we can't inspect
5611 // its value to see if it's in-lifetime or what the active union members
5612 // are. We can still check for a one-past-the-end lvalue.
5613 if (This.Designator.isOnePastTheEnd() ||
5614 This.Designator.isMostDerivedAnUnsizedArray()) {
5615 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5616 ? diag::note_constexpr_access_past_end
5617 : diag::note_constexpr_access_unsized_array)
5618 << AK;
5619 return false;
5620 } else if (Polymorphic) {
5621 // Conservatively refuse to perform a polymorphic operation if we would
5622 // not be able to read a notional 'vptr' value.
5623 APValue Val;
5624 This.moveInto(Val);
5625 QualType StarThisType =
5626 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5627 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5628 << AK << Val.getAsString(Info.Ctx, StarThisType);
5629 return false;
5630 }
5631 return true;
5632 }
5633
5634 CheckDynamicTypeHandler Handler{AK};
5635 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5636}
5637
5638/// Check that the pointee of the 'this' pointer in a member function call is
5639/// either within its lifetime or in its period of construction or destruction.
5640static bool
5641checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5642 const LValue &This,
5643 const CXXMethodDecl *NamedMember) {
5644 return checkDynamicType(
5645 Info, E, This,
5646 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5647}
5648
5649struct DynamicType {
5650 /// The dynamic class type of the object.
5651 const CXXRecordDecl *Type;
5652 /// The corresponding path length in the lvalue.
5653 unsigned PathLength;
5654};
5655
5656static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5657 unsigned PathLength) {
5658 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength
&& PathLength <= Designator.Entries.size() &&
"invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\""
, "clang/lib/AST/ExprConstant.cpp", 5659, __extension__ __PRETTY_FUNCTION__
))
5659 Designator.Entries.size() && "invalid path length")(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength
&& PathLength <= Designator.Entries.size() &&
"invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\""
, "clang/lib/AST/ExprConstant.cpp", 5659, __extension__ __PRETTY_FUNCTION__
))
;
5660 return (PathLength == Designator.MostDerivedPathLength)
5661 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5662 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5663}
5664
5665/// Determine the dynamic type of an object.
5666static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5667 LValue &This, AccessKinds AK) {
5668 // If we don't have an lvalue denoting an object of class type, there is no
5669 // meaningful dynamic type. (We consider objects of non-class type to have no
5670 // dynamic type.)
5671 if (!checkDynamicType(Info, E, This, AK, true))
5672 return None;
5673
5674 // Refuse to compute a dynamic type in the presence of virtual bases. This
5675 // shouldn't happen other than in constant-folding situations, since literal
5676 // types can't have virtual bases.
5677 //
5678 // Note that consumers of DynamicType assume that the type has no virtual
5679 // bases, and will need modifications if this restriction is relaxed.
5680 const CXXRecordDecl *Class =
5681 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5682 if (!Class || Class->getNumVBases()) {
5683 Info.FFDiag(E);
5684 return None;
5685 }
5686
5687 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5688 // binary search here instead. But the overwhelmingly common case is that
5689 // we're not in the middle of a constructor, so it probably doesn't matter
5690 // in practice.
5691 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5692 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5693 PathLength <= Path.size(); ++PathLength) {
5694 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5695 Path.slice(0, PathLength))) {
5696 case ConstructionPhase::Bases:
5697 case ConstructionPhase::DestroyingBases:
5698 // We're constructing or destroying a base class. This is not the dynamic
5699 // type.
5700 break;
5701
5702 case ConstructionPhase::None:
5703 case ConstructionPhase::AfterBases:
5704 case ConstructionPhase::AfterFields:
5705 case ConstructionPhase::Destroying:
5706 // We've finished constructing the base classes and not yet started
5707 // destroying them again, so this is the dynamic type.
5708 return DynamicType{getBaseClassType(This.Designator, PathLength),
5709 PathLength};
5710 }
5711 }
5712
5713 // CWG issue 1517: we're constructing a base class of the object described by
5714 // 'This', so that object has not yet begun its period of construction and
5715 // any polymorphic operation on it results in undefined behavior.
5716 Info.FFDiag(E);
5717 return None;
5718}
5719
5720/// Perform virtual dispatch.
5721static const CXXMethodDecl *HandleVirtualDispatch(
5722 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5723 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5724 Optional<DynamicType> DynType = ComputeDynamicType(
5725 Info, E, This,
5726 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5727 if (!DynType)
5728 return nullptr;
5729
5730 // Find the final overrider. It must be declared in one of the classes on the
5731 // path from the dynamic type to the static type.
5732 // FIXME: If we ever allow literal types to have virtual base classes, that
5733 // won't be true.
5734 const CXXMethodDecl *Callee = Found;
5735 unsigned PathLength = DynType->PathLength;
5736 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5737 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5738 const CXXMethodDecl *Overrider =
5739 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5740 if (Overrider) {
5741 Callee = Overrider;
5742 break;
5743 }
5744 }
5745
5746 // C++2a [class.abstract]p6:
5747 // the effect of making a virtual call to a pure virtual function [...] is
5748 // undefined
5749 if (Callee->isPure()) {
5750 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5751 Info.Note(Callee->getLocation(), diag::note_declared_at);
5752 return nullptr;
5753 }
5754
5755 // If necessary, walk the rest of the path to determine the sequence of
5756 // covariant adjustment steps to apply.
5757 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5758 Found->getReturnType())) {
5759 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5760 for (unsigned CovariantPathLength = PathLength + 1;
5761 CovariantPathLength != This.Designator.Entries.size();
5762 ++CovariantPathLength) {
5763 const CXXRecordDecl *NextClass =
5764 getBaseClassType(This.Designator, CovariantPathLength);
5765 const CXXMethodDecl *Next =
5766 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5767 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5768 Next->getReturnType(), CovariantAdjustmentPath.back()))
5769 CovariantAdjustmentPath.push_back(Next->getReturnType());
5770 }
5771 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5772 CovariantAdjustmentPath.back()))
5773 CovariantAdjustmentPath.push_back(Found->getReturnType());
5774 }
5775
5776 // Perform 'this' adjustment.
5777 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5778 return nullptr;
5779
5780 return Callee;
5781}
5782
5783/// Perform the adjustment from a value returned by a virtual function to
5784/// a value of the statically expected type, which may be a pointer or
5785/// reference to a base class of the returned type.
5786static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5787 APValue &Result,
5788 ArrayRef<QualType> Path) {
5789 assert(Result.isLValue() &&(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return"
) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\""
, "clang/lib/AST/ExprConstant.cpp", 5790, __extension__ __PRETTY_FUNCTION__
))
5790 "unexpected kind of APValue for covariant return")(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return"
) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\""
, "clang/lib/AST/ExprConstant.cpp", 5790, __extension__ __PRETTY_FUNCTION__
))
;
5791 if (Result.isNullPointer())
5792 return true;
5793
5794 LValue LVal;
5795 LVal.setFrom(Info.Ctx, Result);
5796
5797 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5798 for (unsigned I = 1; I != Path.size(); ++I) {
5799 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5800 assert(OldClass && NewClass && "unexpected kind of covariant return")(static_cast <bool> (OldClass && NewClass &&
"unexpected kind of covariant return") ? void (0) : __assert_fail
("OldClass && NewClass && \"unexpected kind of covariant return\""
, "clang/lib/AST/ExprConstant.cpp", 5800, __extension__ __PRETTY_FUNCTION__
))
;
5801 if (OldClass != NewClass &&
5802 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5803 return false;
5804 OldClass = NewClass;
5805 }
5806
5807 LVal.moveInto(Result);
5808 return true;
5809}
5810
5811/// Determine whether \p Base, which is known to be a direct base class of
5812/// \p Derived, is a public base class.
5813static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5814 const CXXRecordDecl *Base) {
5815 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5816 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5817 if (BaseClass && declaresSameEntity(BaseClass, Base))
5818 return BaseSpec.getAccessSpecifier() == AS_public;
5819 }
5820 llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived"
, "clang/lib/AST/ExprConstant.cpp", 5820)
;
5821}
5822
5823/// Apply the given dynamic cast operation on the provided lvalue.
5824///
5825/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5826/// to find a suitable target subobject.
5827static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5828 LValue &Ptr) {
5829 // We can't do anything with a non-symbolic pointer value.
5830 SubobjectDesignator &D = Ptr.Designator;
5831 if (D.Invalid)
5832 return false;
5833
5834 // C++ [expr.dynamic.cast]p6:
5835 // If v is a null pointer value, the result is a null pointer value.
5836 if (Ptr.isNullPointer() && !E->isGLValue())
5837 return true;
5838
5839 // For all the other cases, we need the pointer to point to an object within
5840 // its lifetime / period of construction / destruction, and we need to know
5841 // its dynamic type.
5842 Optional<DynamicType> DynType =
5843 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5844 if (!DynType)
5845 return false;
5846
5847 // C++ [expr.dynamic.cast]p7:
5848 // If T is "pointer to cv void", then the result is a pointer to the most
5849 // derived object
5850 if (E->getType()->isVoidPointerType())
5851 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5852
5853 const CXXRecordDecl *C = E->getTypeA