Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 5983, column 57
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-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/AST/ExprConstant.cpp

/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/AST/ExprConstant.cpp

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