Bug Summary

File:tools/clang/lib/AST/ExprConstant.cpp
Warning:line 5194, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp

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