Bug Summary

File:build/source/clang/lib/AST/ExprConstant.cpp
Warning:line 3206, column 27
Called C++ object pointer is null

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