Bug Summary

File:tools/clang/lib/AST/ExprConstant.cpp
Warning:line 5315, column 57
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~svn373253/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373253/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373253/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373253/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~svn373253/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373253=. -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-01-025250-28041-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp

/build/llvm-toolchain-snapshot-10~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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)
35
Assuming the condition is false
925 return false;
926 if (NextCallIndex == 0) {
36
Assuming field 'NextCallIndex' is not equal to 0
37
Taking false branch
927 // NextCallIndex has wrapped around.
928 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
929 return false;
930 }
931 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
38
Assuming field 'CallStackDepth' is <= field 'ConstexprCallDepth'
39
Taking true branch
932 return true;
40
Returning the value 1, which participates in a condition later
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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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())
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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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~svn373253/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 &&
16
Assuming the condition is false
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()) {
17
Assuming the condition is false
18
Taking false branch
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) &&
19
Assuming field 'CPlusPlus2a' is not equal to 0
4835 cast<CXXMethodDecl>(Declaration)->isVirtual())
4836 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4837
4838 if (Definition && Definition->isInvalidDecl()) {
20
Assuming 'Definition' is non-null
21
Assuming the condition is false
22
Taking false branch
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
22.1
'Definition' is non-null
22.1
'Definition' is non-null
22.1
'Definition' is non-null
&& Definition->isConstexpr() && Body)
23
Assuming 'Body' is non-null
24
Taking true branch
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~svn373253/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~svn373253/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))
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()) {
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;
4982 PathLength <= Path.size(); ++PathLength) {
4983 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
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;
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),
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~svn373253/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~svn373253/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~svn373253/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~svn373253/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)
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())
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);
5132 if (!DynType)
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())
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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5142, __PRETTY_FUNCTION__))
;
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~svn373253/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();
5179 PathLength >= (int)DynType->PathLength; --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) &&
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~svn373253/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~svn373253/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~svn373253/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)
61
Assuming field 'InvalidBase' is false
62
Assuming field 'Invalid' is 0
63
Taking false branch
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;) {
64
Assuming the condition is false
65
Assuming pointer value is null
66
Loop condition is false. Execution continues on line 5309
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 if (!FD)
5262 break;
5263
5264 // ... and also contains A.B if B names a union member
5265 if (FD->getParent()->isUnion())
5266 UnionPathLengths.push_back({PathLength - 1, FD});
5267
5268 E = ME->getBase();
5269 --PathLength;
5270 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5272, __PRETTY_FUNCTION__))
5271 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5272, __PRETTY_FUNCTION__))
5272 .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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5272, __PRETTY_FUNCTION__))
;
5273
5274 // -- If E is of the form A[B] and is interpreted as a built-in array
5275 // subscripting operator, S(E) is [S(the array operand, if any)].
5276 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5277 // Step over an ArrayToPointerDecay implicit cast.
5278 auto *Base = ASE->getBase()->IgnoreImplicit();
5279 if (!Base->getType()->isArrayType())
5280 break;
5281
5282 E = Base;
5283 --PathLength;
5284
5285 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5286 // Step over a derived-to-base conversion.
5287 E = ICE->getSubExpr();
5288 if (ICE->getCastKind() == CK_NoOp)
5289 continue;
5290 if (ICE->getCastKind() != CK_DerivedToBase &&
5291 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5292 break;
5293 // Walk path backwards as we walk up from the base to the derived class.
5294 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5295 --PathLength;
5296 (void)Elt;
5297 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5299, __PRETTY_FUNCTION__))
5298 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5299, __PRETTY_FUNCTION__))
5299 .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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5299, __PRETTY_FUNCTION__))
;
5300 }
5301
5302 // -- Otherwise, S(E) is empty.
5303 } else {
5304 break;
5305 }
5306 }
5307
5308 // Common case: no unions' lifetimes are started.
5309 if (UnionPathLengths.empty())
67
Calling 'SmallVectorBase::empty'
70
Returning from 'SmallVectorBase::empty'
71
Taking false branch
5310 return true;
5311
5312 // if modification of X [would access an inactive union member], an object
5313 // of the type of X is implicitly created
5314 CompleteObject Obj =
5315 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
72
Called C++ object pointer is null
5316 if (!Obj)
5317 return false;
5318 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5319 llvm::reverse(UnionPathLengths)) {
5320 // Form a designator for the union object.
5321 SubobjectDesignator D = LHS.Designator;
5322 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5323
5324 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5325 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5326 return false;
5327 }
5328
5329 return true;
5330}
5331
5332/// Determine if a class has any fields that might need to be copied by a
5333/// trivial copy or move operation.
5334static bool hasFields(const CXXRecordDecl *RD) {
5335 if (!RD || RD->isEmpty())
5336 return false;
5337 for (auto *FD : RD->fields()) {
5338 if (FD->isUnnamedBitfield())
5339 continue;
5340 return true;
5341 }
5342 for (auto &Base : RD->bases())
5343 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5344 return true;
5345 return false;
5346}
5347
5348namespace {
5349typedef SmallVector<APValue, 8> ArgVector;
5350}
5351
5352/// EvaluateArgs - Evaluate the arguments to a function call.
5353static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5354 EvalInfo &Info, const FunctionDecl *Callee) {
5355 bool Success = true;
5356 llvm::SmallBitVector ForbiddenNullArgs;
5357 if (Callee->hasAttr<NonNullAttr>()) {
28
Taking false branch
5358 ForbiddenNullArgs.resize(Args.size());
5359 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5360 if (!Attr->args_size()) {
5361 ForbiddenNullArgs.set();
5362 break;
5363 } else
5364 for (auto Idx : Attr->args()) {
5365 unsigned ASTIdx = Idx.getASTIndex();
5366 if (ASTIdx >= Args.size())
5367 continue;
5368 ForbiddenNullArgs[ASTIdx] = 1;
5369 }
5370 }
5371 }
5372 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
30
Loop condition is false. Execution continues on line 5389
5373 I != E; ++I) {
29
Assuming 'I' is equal to 'E'
5374 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5375 // If we're checking for a potential constant expression, evaluate all
5376 // initializers even if some of them fail.
5377 if (!Info.noteFailure())
5378 return false;
5379 Success = false;
5380 } else if (!ForbiddenNullArgs.empty() &&
5381 ForbiddenNullArgs[I - Args.begin()] &&
5382 ArgValues[I - Args.begin()].isNullPointer()) {
5383 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5384 if (!Info.noteFailure())
5385 return false;
5386 Success = false;
5387 }
5388 }
5389 return Success;
31
Returning the value 1 (loaded from 'Success'), which participates in a condition later
5390}
5391
5392/// Evaluate a function call.
5393static bool HandleFunctionCall(SourceLocation CallLoc,
5394 const FunctionDecl *Callee, const LValue *This,
5395 ArrayRef<const Expr*> Args, const Stmt *Body,
5396 EvalInfo &Info, APValue &Result,
5397 const LValue *ResultSlot) {
5398 ArgVector ArgValues(Args.size());
5399 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
27
Calling 'EvaluateArgs'
32
Returning from 'EvaluateArgs'
33
Taking false branch
5400 return false;
5401
5402 if (!Info.CheckCallLimit(CallLoc))
34
Calling 'EvalInfo::CheckCallLimit'
41
Returning from 'EvalInfo::CheckCallLimit'
42
Taking false branch
5403 return false;
5404
5405 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5406
5407 // For a trivial copy or move assignment, perform an APValue copy. This is
5408 // essential for unions, where the operations performed by the assignment
5409 // operator cannot be represented as statements.
5410 //
5411 // Skip this for non-union classes with no fields; in that case, the defaulted
5412 // copy/move does not actually read the object.
5413 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
43
Assuming 'Callee' is a 'CXXMethodDecl'
5414 if (MD
43.1
'MD' is non-null
43.1
'MD' is non-null
43.1
'MD' is non-null
&& MD->isDefaulted() &&
44
Assuming the condition is true
51
Taking true branch
5415 (MD->getParent()->isUnion() ||
45
Calling 'TagDecl::isUnion'
48
Returning from 'TagDecl::isUnion'
5416 (MD->isTrivial() && hasFields(MD->getParent())))) {
49
Assuming the condition is true
50
Assuming the condition is true
5417 assert
51.1
'This' is non-null
51.1
'This' is non-null
51.1
'This' is non-null
(This &&((This && (MD->isCopyAssignmentOperator() || MD->
isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5418, __PRETTY_FUNCTION__))
52
Assuming the condition is false
53
Assuming the condition is true
54
'?' condition is true
5418 (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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5418, __PRETTY_FUNCTION__))
;
5419 LValue RHS;
5420 RHS.setFrom(Info.Ctx, ArgValues[0]);
5421 APValue RHSValue;
5422 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
55
Assuming the condition is false
56
Taking false branch
5423 RHSValue, MD->getParent()->isUnion()))
5424 return false;
5425 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
57
Assuming field 'CPlusPlus2a' is not equal to 0
58
Assuming the condition is true
5426 !HandleUnionActiveMemberChange(Info, Args[0], *This))
59
Passing value via 2nd parameter 'LHSExpr'
60
Calling 'HandleUnionActiveMemberChange'
5427 return false;
5428 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5429 RHSValue))
5430 return false;
5431 This->moveInto(Result);
5432 return true;
5433 } else if (MD && isLambdaCallOperator(MD)) {
5434 // We're in a lambda; determine the lambda capture field maps unless we're
5435 // just constexpr checking a lambda's call operator. constexpr checking is
5436 // done before the captures have been added to the closure object (unless
5437 // we're inferring constexpr-ness), so we don't have access to them in this
5438 // case. But since we don't need the captures to constexpr check, we can
5439 // just ignore them.
5440 if (!Info.checkingPotentialConstantExpression())
5441 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5442 Frame.LambdaThisCaptureField);
5443 }
5444
5445 StmtResult Ret = {Result, ResultSlot};
5446 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5447 if (ESR == ESR_Succeeded) {
5448 if (Callee->getReturnType()->isVoidType())
5449 return true;
5450 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5451 }
5452 return ESR == ESR_Returned;
5453}
5454
5455/// Evaluate a constructor call.
5456static bool HandleConstructorCall(const Expr *E, const LValue &This,
5457 APValue *ArgValues,
5458 const CXXConstructorDecl *Definition,
5459 EvalInfo &Info, APValue &Result) {
5460 SourceLocation CallLoc = E->getExprLoc();
5461 if (!Info.CheckCallLimit(CallLoc))
5462 return false;
5463
5464 const CXXRecordDecl *RD = Definition->getParent();
5465 if (RD->getNumVBases()) {
5466 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5467 return false;
5468 }
5469
5470 EvalInfo::EvaluatingConstructorRAII EvalObj(
5471 Info,
5472 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5473 RD->getNumBases());
5474 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5475
5476 // FIXME: Creating an APValue just to hold a nonexistent return value is
5477 // wasteful.
5478 APValue RetVal;
5479 StmtResult Ret = {RetVal, nullptr};
5480
5481 // If it's a delegating constructor, delegate.
5482 if (Definition->isDelegatingConstructor()) {
5483 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5484 {
5485 FullExpressionRAII InitScope(Info);
5486 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5487 !InitScope.destroy())
5488 return false;
5489 }
5490 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5491 }
5492
5493 // For a trivial copy or move constructor, perform an APValue copy. This is
5494 // essential for unions (or classes with anonymous union members), where the
5495 // operations performed by the constructor cannot be represented by
5496 // ctor-initializers.
5497 //
5498 // Skip this for empty non-union classes; we should not perform an
5499 // lvalue-to-rvalue conversion on them because their copy constructor does not
5500 // actually read them.
5501 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5502 (Definition->getParent()->isUnion() ||
5503 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5504 LValue RHS;
5505 RHS.setFrom(Info.Ctx, ArgValues[0]);
5506 return handleLValueToRValueConversion(
5507 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5508 RHS, Result, Definition->getParent()->isUnion());
5509 }
5510
5511 // Reserve space for the struct members.
5512 if (!RD->isUnion() && !Result.hasValue())
5513 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5514 std::distance(RD->field_begin(), RD->field_end()));
5515
5516 if (RD->isInvalidDecl()) return false;
5517 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5518
5519 // A scope for temporaries lifetime-extended by reference members.
5520 BlockScopeRAII LifetimeExtendedScope(Info);
5521
5522 bool Success = true;
5523 unsigned BasesSeen = 0;
5524#ifndef NDEBUG
5525 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5526#endif
5527 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5528 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5529 // We might be initializing the same field again if this is an indirect
5530 // field initialization.
5531 if (FieldIt == RD->field_end() ||
5532 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5533 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5533, __PRETTY_FUNCTION__))
;
5534 return;
5535 }
5536
5537 // Default-initialize any fields with no explicit initializer.
5538 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5539 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5539, __PRETTY_FUNCTION__))
;
5540 if (!FieldIt->isUnnamedBitfield())
5541 Result.getStructField(FieldIt->getFieldIndex()) =
5542 getDefaultInitValue(FieldIt->getType());
5543 }
5544 ++FieldIt;
5545 };
5546 for (const auto *I : Definition->inits()) {
5547 LValue Subobject = This;
5548 LValue SubobjectParent = This;
5549 APValue *Value = &Result;
5550
5551 // Determine the subobject to initialize.
5552 FieldDecl *FD = nullptr;
5553 if (I->isBaseInitializer()) {
5554 QualType BaseType(I->getBaseClass(), 0);
5555#ifndef NDEBUG
5556 // Non-virtual base classes are initialized in the order in the class
5557 // definition. We have already checked for virtual base classes.
5558 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5558, __PRETTY_FUNCTION__))
;
5559 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5560, __PRETTY_FUNCTION__))
5560 "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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5560, __PRETTY_FUNCTION__))
;
5561 ++BaseIt;
5562#endif
5563 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5564 BaseType->getAsCXXRecordDecl(), &Layout))
5565 return false;
5566 Value = &Result.getStructBase(BasesSeen++);
5567 } else if ((FD = I->getMember())) {
5568 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5569 return false;
5570 if (RD->isUnion()) {
5571 Result = APValue(FD);
5572 Value = &Result.getUnionValue();
5573 } else {
5574 SkipToField(FD, false);
5575 Value = &Result.getStructField(FD->getFieldIndex());
5576 }
5577 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5578 // Walk the indirect field decl's chain to find the object to initialize,
5579 // and make sure we've initialized every step along it.
5580 auto IndirectFieldChain = IFD->chain();
5581 for (auto *C : IndirectFieldChain) {
5582 FD = cast<FieldDecl>(C);
5583 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5584 // Switch the union field if it differs. This happens if we had
5585 // preceding zero-initialization, and we're now initializing a union
5586 // subobject other than the first.
5587 // FIXME: In this case, the values of the other subobjects are
5588 // specified, since zero-initialization sets all padding bits to zero.
5589 if (!Value->hasValue() ||
5590 (Value->isUnion() && Value->getUnionField() != FD)) {
5591 if (CD->isUnion())
5592 *Value = APValue(FD);
5593 else
5594 // FIXME: This immediately starts the lifetime of all members of an
5595 // anonymous struct. It would be preferable to strictly start member
5596 // lifetime in initialization order.
5597 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5598 }
5599 // Store Subobject as its parent before updating it for the last element
5600 // in the chain.
5601 if (C == IndirectFieldChain.back())
5602 SubobjectParent = Subobject;
5603 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5604 return false;
5605 if (CD->isUnion())
5606 Value = &Value->getUnionValue();
5607 else {
5608 if (C == IndirectFieldChain.front() && !RD->isUnion())
5609 SkipToField(FD, true);
5610 Value = &Value->getStructField(FD->getFieldIndex());
5611 }
5612 }
5613 } else {
5614 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5614)
;
5615 }
5616
5617 // Need to override This for implicit field initializers as in this case
5618 // This refers to innermost anonymous struct/union containing initializer,
5619 // not to currently constructed class.
5620 const Expr *Init = I->getInit();
5621 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5622 isa<CXXDefaultInitExpr>(Init));
5623 FullExpressionRAII InitScope(Info);
5624 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5625 (FD && FD->isBitField() &&
5626 !truncateBitfieldValue(Info, Init, *Value, FD))) {
5627 // If we're checking for a potential constant expression, evaluate all
5628 // initializers even if some of them fail.
5629 if (!Info.noteFailure())
5630 return false;
5631 Success = false;
5632 }
5633
5634 // This is the point at which the dynamic type of the object becomes this
5635 // class type.
5636 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5637 EvalObj.finishedConstructingBases();
5638 }
5639
5640 // Default-initialize any remaining fields.
5641 if (!RD->isUnion()) {
5642 for (; FieldIt != RD->field_end(); ++FieldIt) {
5643 if (!FieldIt->isUnnamedBitfield())
5644 Result.getStructField(FieldIt->getFieldIndex()) =
5645 getDefaultInitValue(FieldIt->getType());
5646 }
5647 }
5648
5649 return Success &&
5650 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5651 LifetimeExtendedScope.destroy();
5652}
5653
5654static bool HandleConstructorCall(const Expr *E, const LValue &This,
5655 ArrayRef<const Expr*> Args,
5656 const CXXConstructorDecl *Definition,
5657 EvalInfo &Info, APValue &Result) {
5658 ArgVector ArgValues(Args.size());
5659 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5660 return false;
5661
5662 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5663 Info, Result);
5664}
5665
5666static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5667 const LValue &This, APValue &Value,
5668 QualType T) {
5669 // Objects can only be destroyed while they're within their lifetimes.
5670 // FIXME: We have no representation for whether an object of type nullptr_t
5671 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5672 // as indeterminate instead?
5673 if (Value.isAbsent() && !T->isNullPtrType()) {
5674 APValue Printable;
5675 This.moveInto(Printable);
5676 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5677 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5678 return false;
5679 }
5680
5681 // Invent an expression for location purposes.
5682 // FIXME: We shouldn't need to do this.
5683 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5684
5685 // For arrays, destroy elements right-to-left.
5686 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5687 uint64_t Size = CAT->getSize().getZExtValue();
5688 QualType ElemT = CAT->getElementType();
5689
5690 LValue ElemLV = This;
5691 ElemLV.addArray(Info, &LocE, CAT);
5692 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5693 return false;
5694
5695 // Ensure that we have actual array elements available to destroy; the
5696 // destructors might mutate the value, so we can't run them on the array
5697 // filler.
5698 if (Size && Size > Value.getArrayInitializedElts())
5699 expandArray(Value, Value.getArraySize() - 1);
5700
5701 for (; Size != 0; --Size) {
5702 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5703 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5704 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5705 return false;
5706 }
5707
5708 // End the lifetime of this array now.
5709 Value = APValue();
5710 return true;
5711 }
5712
5713 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5714 if (!RD) {
5715 if (T.isDestructedType()) {
5716 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5717 return false;
5718 }
5719
5720 Value = APValue();
5721 return true;
5722 }
5723
5724 if (RD->getNumVBases()) {
5725 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5726 return false;
5727 }
5728
5729 const CXXDestructorDecl *DD = RD->getDestructor();
5730 if (!DD && !RD->hasTrivialDestructor()) {
5731 Info.FFDiag(CallLoc);
5732 return false;
5733 }
5734
5735 if (!DD || DD->isTrivial() ||
5736 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5737 // A trivial destructor just ends the lifetime of the object. Check for
5738 // this case before checking for a body, because we might not bother
5739 // building a body for a trivial destructor. Note that it doesn't matter
5740 // whether the destructor is constexpr in this case; all trivial
5741 // destructors are constexpr.
5742 //
5743 // If an anonymous union would be destroyed, some enclosing destructor must
5744 // have been explicitly defined, and the anonymous union destruction should
5745 // have no effect.
5746 Value = APValue();
5747 return true;
5748 }
5749
5750 if (!Info.CheckCallLimit(CallLoc))
5751 return false;
5752
5753 const FunctionDecl *Definition = nullptr;
5754 const Stmt *Body = DD->getBody(Definition);
5755
5756 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5757 return false;
5758
5759 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5760
5761 // We're now in the period of destruction of this object.
5762 unsigned BasesLeft = RD->getNumBases();
5763 EvalInfo::EvaluatingDestructorRAII EvalObj(
5764 Info,
5765 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5766 if (!EvalObj.DidInsert) {
5767 // C++2a [class.dtor]p19:
5768 // the behavior is undefined if the destructor is invoked for an object
5769 // whose lifetime has ended
5770 // (Note that formally the lifetime ends when the period of destruction
5771 // begins, even though certain uses of the object remain valid until the
5772 // period of destruction ends.)
5773 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5774 return false;
5775 }
5776
5777 // FIXME: Creating an APValue just to hold a nonexistent return value is
5778 // wasteful.
5779 APValue RetVal;
5780 StmtResult Ret = {RetVal, nullptr};
5781 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5782 return false;
5783
5784 // A union destructor does not implicitly destroy its members.
5785 if (RD->isUnion())
5786 return true;
5787
5788 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5789
5790 // We don't have a good way to iterate fields in reverse, so collect all the
5791 // fields first and then walk them backwards.
5792 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5793 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5794 if (FD->isUnnamedBitfield())
5795 continue;
5796
5797 LValue Subobject = This;
5798 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5799 return false;
5800
5801 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5802 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5803 FD->getType()))
5804 return false;
5805 }
5806
5807 if (BasesLeft != 0)
5808 EvalObj.startedDestroyingBases();
5809
5810 // Destroy base classes in reverse order.
5811 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5812 --BasesLeft;
5813
5814 QualType BaseType = Base.getType();
5815 LValue Subobject = This;
5816 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5817 BaseType->getAsCXXRecordDecl(), &Layout))
5818 return false;
5819
5820 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5821 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5822 BaseType))
5823 return false;
5824 }
5825 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~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5825, __PRETTY_FUNCTION__))
;
5826
5827 // The period of destruction ends now. The object is gone.
5828 Value = APValue();
5829 return true;
5830}
5831
5832namespace {
5833struct DestroyObjectHandler {
5834 EvalInfo &Info;
5835 const Expr *E;
5836 const LValue &This;
5837 const AccessKinds AccessKind;
5838
5839 typedef bool result_type;
5840 bool failed() { return false; }
5841 bool found(APValue &Subobj, QualType SubobjType) {
5842 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5843 SubobjType);
5844 }
5845 bool found(APSInt &Value, QualType SubobjType) {
5846 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5847 return false;
5848 }
5849 bool found(APFloat &Value, QualType SubobjType) {
5850 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5851 return false;
5852 }
5853};
5854}
5855
5856/// Perform a destructor or pseudo-destructor call on the given object, which
5857/// might in general not be a complete object.
5858static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5859 const LValue &This, QualType ThisType) {
5860 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5861 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5862 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5863}
5864
5865/// Destroy and end the lifetime of the given complete object.
5866static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5867 APValue::LValueBase LVBase, APValue &Value,
5868 QualType T) {
5869 // If we've had an unmodeled side-effect, we can't rely on mutable state
5870 // (such as the object we're about to destroy) being correct.
5871 if (Info.EvalStatus.HasSideEffects)
5872 return false;
5873
5874 LValue LV;
5875 LV.set({LVBase});
5876 return HandleDestructionImpl(Info, Loc, LV, Value, T);
5877}
5878
5879//===----------------------------------------------------------------------===//
5880// Generic Evaluation
5881//===----------------------------------------------------------------------===//
5882namespace {
5883
5884class BitCastBuffer {
5885 // FIXME: We're going to need bit-level granularity when we support
5886 // bit-fields.
5887 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5888 // we don't support a host or target where that is the case. Still, we should
5889 // use a more generic type in case we ever do.
5890 SmallVector<Optional<unsigned char>, 32> Bytes;
5891
5892 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5893 "Need at least 8 bit unsigned char");
5894
5895 bool TargetIsLittleEndian;
5896
5897public:
5898 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5899 : Bytes(Width.getQuantity()),
5900 TargetIsLittleEndian(TargetIsLittleEndian) {}
5901
5902 LLVM_NODISCARD[[clang::warn_unused_result]]
5903 bool readObject(CharUnits Offset, CharUnits Width,
5904 SmallVectorImpl<unsigned char> &Output) const {
5905 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5906 // If a byte of an integer is uninitialized, then the whole integer is
5907 // uninitalized.
5908 if (!Bytes[I.getQuantity()])
5909 return false;
5910 Output.push_back(*Bytes[I.getQuantity()]);
5911 }
5912 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5913 std::reverse(Output.begin(), Output.end());
5914 return true;
5915 }
5916
5917 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5918 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5919 std::reverse(Input.begin(), Input.end());
5920
5921 size_t Index = 0;
5922 for (unsigned char Byte : Input) {
5923 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?")((!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"
) ? static_cast<void> (0) : __assert_fail ("!Bytes[Offset.getQuantity() + Index] && \"overwriting a byte?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5923, __PRETTY_FUNCTION__))
;
5924 Bytes[Offset.getQuantity() + Index] = Byte;
5925 ++Index;
5926 }
5927 }
5928
5929 size_t size() { return Bytes.size(); }
5930};
5931
5932/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5933/// target would represent the value at runtime.
5934class APValueToBufferConverter {
5935 EvalInfo &Info;
5936 BitCastBuffer Buffer;
5937 const CastExpr *BCE;
5938
5939 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5940 const CastExpr *BCE)
5941 : Info(Info),
5942 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5943 BCE(BCE) {}
5944
5945 bool visit(const APValue &Val, QualType Ty) {
5946 return visit(Val, Ty, CharUnits::fromQuantity(0));
5947 }
5948
5949 // Write out Val with type Ty into Buffer starting at Offset.
5950 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5951 assert((size_t)Offset.getQuantity() <= Buffer.size())(((size_t)Offset.getQuantity() <= Buffer.size()) ? static_cast
<void> (0) : __assert_fail ("(size_t)Offset.getQuantity() <= Buffer.size()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5951, __PRETTY_FUNCTION__))
;
5952
5953 // As a special case, nullptr_t has an indeterminate value.
5954 if (Ty->isNullPtrType())
5955 return true;
5956
5957 // Dig through Src to find the byte at SrcOffset.
5958 switch (Val.getKind()) {
5959 case APValue::Indeterminate:
5960 case APValue::None:
5961 return true;
5962
5963 case APValue::Int:
5964 return visitInt(Val.getInt(), Ty, Offset);
5965 case APValue::Float:
5966 return visitFloat(Val.getFloat(), Ty, Offset);
5967 case APValue::Array:
5968 return visitArray(Val, Ty, Offset);
5969 case APValue::Struct:
5970 return visitRecord(Val, Ty, Offset);
5971
5972 case APValue::ComplexInt:
5973 case APValue::ComplexFloat:
5974 case APValue::Vector:
5975 case APValue::FixedPoint:
5976 // FIXME: We should support these.
5977
5978 case APValue::Union:
5979 case APValue::MemberPointer:
5980 case APValue::AddrLabelDiff: {
5981 Info.FFDiag(BCE->getBeginLoc(),
5982 diag::note_constexpr_bit_cast_unsupported_type)
5983 << Ty;
5984 return false;
5985 }
5986
5987 case APValue::LValue:
5988 llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5988)
;
5989 }
5990 llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 5990)
;
5991 }
5992
5993 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5994 const RecordDecl *RD = Ty->getAsRecordDecl();
5995 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5996
5997 // Visit the base classes.
5998 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5999 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6000 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6001 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6002
6003 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6004 Layout.getBaseClassOffset(BaseDecl) + Offset))
6005 return false;
6006 }
6007 }
6008
6009 // Visit the fields.
6010 unsigned FieldIdx = 0;
6011 for (FieldDecl *FD : RD->fields()) {
6012 if (FD->isBitField()) {
6013 Info.FFDiag(BCE->getBeginLoc(),
6014 diag::note_constexpr_bit_cast_unsupported_bitfield);
6015 return false;
6016 }
6017
6018 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6019
6020 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&((FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && "only bit-fields can have sub-char alignment"
) ? static_cast<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6021, __PRETTY_FUNCTION__))
6021 "only bit-fields can have sub-char alignment")((FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && "only bit-fields can have sub-char alignment"
) ? static_cast<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6021, __PRETTY_FUNCTION__))
;
6022 CharUnits FieldOffset =
6023 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6024 QualType FieldTy = FD->getType();
6025 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6026 return false;
6027 ++FieldIdx;
6028 }
6029
6030 return true;
6031 }
6032
6033 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6034 const auto *CAT =
6035 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6036 if (!CAT)
6037 return false;
6038
6039 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6040 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6041 unsigned ArraySize = Val.getArraySize();
6042 // First, initialize the initialized elements.
6043 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6044 const APValue &SubObj = Val.getArrayInitializedElt(I);
6045 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6046 return false;
6047 }
6048
6049 // Next, initialize the rest of the array using the filler.
6050 if (Val.hasArrayFiller()) {
6051 const APValue &Filler = Val.getArrayFiller();
6052 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6053 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6054 return false;
6055 }
6056 }
6057
6058 return true;
6059 }
6060
6061 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6062 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6063 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6064 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6065 Buffer.writeObject(Offset, Bytes);
6066 return true;
6067 }
6068
6069 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6070 APSInt AsInt(Val.bitcastToAPInt());
6071 return visitInt(AsInt, Ty, Offset);
6072 }
6073
6074public:
6075 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6076 const CastExpr *BCE) {
6077 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6078 APValueToBufferConverter Converter(Info, DstSize, BCE);
6079 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6080 return None;
6081 return Converter.Buffer;
6082 }
6083};
6084
6085/// Write an BitCastBuffer into an APValue.
6086class BufferToAPValueConverter {
6087 EvalInfo &Info;
6088 const BitCastBuffer &Buffer;
6089 const CastExpr *BCE;
6090
6091 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6092 const CastExpr *BCE)
6093 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6094
6095 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6096 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6097 // Ideally this will be unreachable.
6098 llvm::NoneType unsupportedType(QualType Ty) {
6099 Info.FFDiag(BCE->getBeginLoc(),
6100 diag::note_constexpr_bit_cast_unsupported_type)
6101 << Ty;
6102 return None;
6103 }
6104
6105 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6106 const EnumType *EnumSugar = nullptr) {
6107 if (T->isNullPtrType()) {
6108 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6109 return APValue((Expr *)nullptr,
6110 /*Offset=*/CharUnits::fromQuantity(NullValue),
6111 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6112 }
6113
6114 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6115 SmallVector<uint8_t, 8> Bytes;
6116 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6117 // If this is std::byte or unsigned char, then its okay to store an
6118 // indeterminate value.
6119 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6120 bool IsUChar =
6121 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6122 T->isSpecificBuiltinType(BuiltinType::Char_U));
6123 if (!IsStdByte && !IsUChar) {
6124 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6125 Info.FFDiag(BCE->getExprLoc(),
6126 diag::note_constexpr_bit_cast_indet_dest)
6127 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6128 return None;
6129 }
6130
6131 return APValue::IndeterminateValue();
6132 }
6133
6134 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6135 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6136
6137 if (T->isIntegralOrEnumerationType()) {
6138 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6139 return APValue(Val);
6140 }
6141
6142 if (T->isRealFloatingType()) {
6143 const llvm::fltSemantics &Semantics =
6144 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6145 return APValue(APFloat(Semantics, Val));
6146 }
6147
6148 return unsupportedType(QualType(T, 0));
6149 }
6150
6151 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6152 const RecordDecl *RD = RTy->getAsRecordDecl();
6153 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6154
6155 unsigned NumBases = 0;
6156 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6157 NumBases = CXXRD->getNumBases();
6158
6159 APValue ResultVal(APValue::UninitStruct(), NumBases,
6160 std::distance(RD->field_begin(), RD->field_end()));
6161
6162 // Visit the base classes.
6163 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6164 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6165 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6166 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6167 if (BaseDecl->isEmpty() ||
6168 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6169 continue;
6170
6171 Optional<APValue> SubObj = visitType(
6172 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6173 if (!SubObj)
6174 return None;
6175 ResultVal.getStructBase(I) = *SubObj;
6176 }
6177 }
6178
6179 // Visit the fields.
6180 unsigned FieldIdx = 0;
6181 for (FieldDecl *FD : RD->fields()) {
6182 // FIXME: We don't currently support bit-fields. A lot of the logic for
6183 // this is in CodeGen, so we need to factor it around.
6184 if (FD->isBitField()) {
6185 Info.FFDiag(BCE->getBeginLoc(),
6186 diag::note_constexpr_bit_cast_unsupported_bitfield);
6187 return None;
6188 }
6189
6190 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6191 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0)((FieldOffsetBits % Info.Ctx.getCharWidth() == 0) ? static_cast
<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6191, __PRETTY_FUNCTION__))
;
6192
6193 CharUnits FieldOffset =
6194 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6195 Offset;
6196 QualType FieldTy = FD->getType();
6197 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6198 if (!SubObj)
6199 return None;
6200 ResultVal.getStructField(FieldIdx) = *SubObj;
6201 ++FieldIdx;
6202 }
6203
6204 return ResultVal;
6205 }
6206
6207 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6208 QualType RepresentationType = Ty->getDecl()->getIntegerType();
6209 assert(!RepresentationType.isNull() &&((!RepresentationType.isNull() && "enum forward decl should be caught by Sema"
) ? static_cast<void> (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6210, __PRETTY_FUNCTION__))
6210 "enum forward decl should be caught by Sema")((!RepresentationType.isNull() && "enum forward decl should be caught by Sema"
) ? static_cast<void> (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6210, __PRETTY_FUNCTION__))
;
6211 const BuiltinType *AsBuiltin =
6212 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
6213 assert(AsBuiltin && "non-integral enum underlying type?")((AsBuiltin && "non-integral enum underlying type?") ?
static_cast<void> (0) : __assert_fail ("AsBuiltin && \"non-integral enum underlying type?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6213, __PRETTY_FUNCTION__))
;
6214 // Recurse into the underlying type. Treat std::byte transparently as
6215 // unsigned char.
6216 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6217 }
6218
6219 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6220 size_t Size = Ty->getSize().getLimitedValue();
6221 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6222
6223 APValue ArrayValue(APValue::UninitArray(), Size, Size);
6224 for (size_t I = 0; I != Size; ++I) {
6225 Optional<APValue> ElementValue =
6226 visitType(Ty->getElementType(), Offset + I * ElementWidth);
6227 if (!ElementValue)
6228 return None;
6229 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6230 }
6231
6232 return ArrayValue;
6233 }
6234
6235 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6236 return unsupportedType(QualType(Ty, 0));
6237 }
6238
6239 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6240 QualType Can = Ty.getCanonicalType();
6241
6242 switch (Can->getTypeClass()) {
6243#define TYPE(Class, Base) \
6244 case Type::Class: \
6245 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6246#define ABSTRACT_TYPE(Class, Base)
6247#define NON_CANONICAL_TYPE(Class, Base) \
6248 case Type::Class: \
6249 llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6249)
;
6250#define DEPENDENT_TYPE(Class, Base) \
6251 case Type::Class: \
6252 llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6253)
6253 "dependent types aren't supported in the constant evaluator!")::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6253)
;
6254#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6254);
\
6255 case Type::Class: \
6256 llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6256)
;
6257#include "clang/AST/TypeNodes.def"
6258 }
6259 llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6259)
;
6260 }
6261
6262public:
6263 // Pull out a full value of type DstType.
6264 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6265 const CastExpr *BCE) {
6266 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6267 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6268 }
6269};
6270
6271static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6272 QualType Ty, EvalInfo *Info,
6273 const ASTContext &Ctx,
6274 bool CheckingDest) {
6275 Ty = Ty.getCanonicalType();
6276
6277 auto diag = [&](int Reason) {
6278 if (Info)
6279 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6280 << CheckingDest << (Reason == 4) << Reason;
6281 return false;
6282 };
6283 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6284 if (Info)
6285 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6286 << NoteTy << Construct << Ty;
6287 return false;
6288 };
6289
6290 if (Ty->isUnionType())
6291 return diag(0);
6292 if (Ty->isPointerType())
6293 return diag(1);
6294 if (Ty->isMemberPointerType())
6295 return diag(2);
6296 if (Ty.isVolatileQualified())
6297 return diag(3);
6298
6299 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6300 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6301 for (CXXBaseSpecifier &BS : CXXRD->bases())
6302 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6303 CheckingDest))
6304 return note(1, BS.getType(), BS.getBeginLoc());
6305 }
6306 for (FieldDecl *FD : Record->fields()) {
6307 if (FD->getType()->isReferenceType())
6308 return diag(4);
6309 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6310 CheckingDest))
6311 return note(0, FD->getType(), FD->getBeginLoc());
6312 }
6313 }
6314
6315 if (Ty->isArrayType() &&
6316 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6317 Info, Ctx, CheckingDest))
6318 return false;
6319
6320 return true;
6321}
6322
6323static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6324 const ASTContext &Ctx,
6325 const CastExpr *BCE) {
6326 bool DestOK = checkBitCastConstexprEligibilityType(
6327 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6328 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6329 BCE->getBeginLoc(),
6330 BCE->getSubExpr()->getType(), Info, Ctx, false);
6331 return SourceOK;
6332}
6333
6334static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6335 APValue &SourceValue,
6336 const CastExpr *BCE) {
6337 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&((8 == 8 && Info.Ctx.getTargetInfo().getCharWidth() ==
8 && "no host or target supports non 8-bit chars") ?
static_cast<void> (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6338, __PRETTY_FUNCTION__))
6338 "no host or target supports non 8-bit chars")((8 == 8 && Info.Ctx.getTargetInfo().getCharWidth() ==
8 && "no host or target supports non 8-bit chars") ?
static_cast<void> (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6338, __PRETTY_FUNCTION__))
;
6339 assert(SourceValue.isLValue() &&((SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!"
) ? static_cast<void> (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6340, __PRETTY_FUNCTION__))
6340 "LValueToRValueBitcast requires an lvalue operand!")((SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!"
) ? static_cast<void> (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6340, __PRETTY_FUNCTION__))
;
6341
6342 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6343 return false;
6344
6345 LValue SourceLValue;
6346 APValue SourceRValue;
6347 SourceLValue.setFrom(Info.Ctx, SourceValue);
6348 if (!handleLValueToRValueConversion(
6349 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6350 SourceRValue, /*WantObjectRepresentation=*/true))
6351 return false;
6352
6353 // Read out SourceValue into a char buffer.
6354 Optional<BitCastBuffer> Buffer =
6355 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6356 if (!Buffer)
6357 return false;
6358
6359 // Write out the buffer into a new APValue.
6360 Optional<APValue> MaybeDestValue =
6361 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6362 if (!MaybeDestValue)
6363 return false;
6364
6365 DestValue = std::move(*MaybeDestValue);
6366 return true;
6367}
6368
6369template <class Derived>
6370class ExprEvaluatorBase
6371 : public ConstStmtVisitor<Derived, bool> {
6372private:
6373 Derived &getDerived() { return static_cast<Derived&>(*this); }
6374 bool DerivedSuccess(const APValue &V, const Expr *E) {
6375 return getDerived().Success(V, E);
6376 }
6377 bool DerivedZeroInitialization(const Expr *E) {
6378 return getDerived().ZeroInitialization(E);
6379 }
6380
6381 // Check whether a conditional operator with a non-constant condition is a
6382 // potential constant expression. If neither arm is a potential constant
6383 // expression, then the conditional operator is not either.
6384 template<typename ConditionalOperator>
6385 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6386 assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast<
void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6386, __PRETTY_FUNCTION__))
;
6387
6388 // Speculatively evaluate both arms.
6389 SmallVector<PartialDiagnosticAt, 8> Diag;
6390 {
6391 SpeculativeEvaluationRAII Speculate(Info, &Diag);
6392 StmtVisitorTy::Visit(E->getFalseExpr());
6393 if (Diag.empty())
6394 return;
6395 }
6396
6397 {
6398 SpeculativeEvaluationRAII Speculate(Info, &Diag);
6399 Diag.clear();
6400 StmtVisitorTy::Visit(E->getTrueExpr());
6401 if (Diag.empty())
6402 return;
6403 }
6404
6405 Error(E, diag::note_constexpr_conditional_never_const);
6406 }
6407
6408
6409 template<typename ConditionalOperator>
6410 bool HandleConditionalOperator(const ConditionalOperator *E) {
6411 bool BoolResult;
6412 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6413 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6414 CheckPotentialConstantConditional(E);
6415 return false;
6416 }
6417 if (Info.noteFailure()) {
6418 StmtVisitorTy::Visit(E->getTrueExpr());
6419 StmtVisitorTy::Visit(E->getFalseExpr());
6420 }
6421 return false;
6422 }
6423
6424 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6425 return StmtVisitorTy::Visit(EvalExpr);
6426 }
6427
6428protected:
6429 EvalInfo &Info;
6430 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6431 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6432
6433 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6434 return Info.CCEDiag(E, D);
6435 }
6436
6437 bool ZeroInitialization(const Expr *E) { return Error(E); }
6438
6439public:
6440 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6441
6442 EvalInfo &getEvalInfo() { return Info; }
6443
6444 /// Report an evaluation error. This should only be called when an error is
6445 /// first discovered. When propagating an error, just return false.
6446 bool Error(const Expr *E, diag::kind D) {
6447 Info.FFDiag(E, D);
6448 return false;
6449 }
6450 bool Error(const Expr *E) {
6451 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6452 }
6453
6454 bool VisitStmt(const Stmt *) {
6455 llvm_unreachable("Expression evaluator should not be called on stmts")::llvm::llvm_unreachable_internal("Expression evaluator should not be called on stmts"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6455)
;
6456 }
6457 bool VisitExpr(const Expr *E) {
6458 return Error(E);
6459 }
6460
6461 bool VisitConstantExpr(const ConstantExpr *E)
6462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6463 bool VisitParenExpr(const ParenExpr *E)
6464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6465 bool VisitUnaryExtension(const UnaryOperator *E)
6466 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6467 bool VisitUnaryPlus(const UnaryOperator *E)
6468 { return StmtVisitorTy::Visit(E->getSubExpr()); }
6469 bool VisitChooseExpr(const ChooseExpr *E)
6470 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6471 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6472 { return StmtVisitorTy::Visit(E->getResultExpr()); }
6473 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6474 { return StmtVisitorTy::Visit(E->getReplacement()); }
6475 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6476 TempVersionRAII RAII(*Info.CurrentCall);
6477 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6478 return StmtVisitorTy::Visit(E->getExpr());
6479 }
6480 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6481 TempVersionRAII RAII(*Info.CurrentCall);
6482 // The initializer may not have been parsed yet, or might be erroneous.
6483 if (!E->getExpr())
6484 return Error(E);
6485 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6486 return StmtVisitorTy::Visit(E->getExpr());
6487 }
6488
6489 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6490 FullExpressionRAII Scope(Info);
6491 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6492 }
6493
6494 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6495 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6496 return static_cast<Derived*>(this)->VisitCastExpr(E);
6497 }
6498 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6499 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6500 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6501 return static_cast<Derived*>(this)->VisitCastExpr(E);
6502 }
6503 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6504 return static_cast<Derived*>(this)->VisitCastExpr(E);
6505 }
6506
6507 bool VisitBinaryOperator(const BinaryOperator *E) {
6508 switch (E->getOpcode()) {
6509 default:
6510 return Error(E);
6511
6512 case BO_Comma:
6513 VisitIgnoredValue(E->getLHS());
6514 return StmtVisitorTy::Visit(E->getRHS());
6515
6516 case BO_PtrMemD:
6517 case BO_PtrMemI: {
6518 LValue Obj;
6519 if (!HandleMemberPointerAccess(Info, E, Obj))
6520 return false;
6521 APValue Result;
6522 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6523 return false;
6524 return DerivedSuccess(Result, E);
6525 }
6526 }
6527 }
6528
6529 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6530 // Evaluate and cache the common expression. We treat it as a temporary,
6531 // even though it's not quite the same thing.
6532 LValue CommonLV;
6533 if (!Evaluate(Info.CurrentCall->createTemporary(
6534 E->getOpaqueValue(),
6535 getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6536 CommonLV),
6537 Info, E->getCommon()))
6538 return false;
6539
6540 return HandleConditionalOperator(E);
6541 }
6542
6543 bool VisitConditionalOperator(const ConditionalOperator *E) {
6544 bool IsBcpCall = false;
6545 // If the condition (ignoring parens) is a __builtin_constant_p call,
6546 // the result is a constant expression if it can be folded without
6547 // side-effects. This is an important GNU extension. See GCC PR38377
6548 // for discussion.
6549 if (const CallExpr *CallCE =
6550 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6551 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6552 IsBcpCall = true;
6553
6554 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6555 // constant expression; we can't check whether it's potentially foldable.
6556 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6557 // it would return 'false' in this mode.
6558 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6559 return false;
6560
6561 FoldConstant Fold(Info, IsBcpCall);
6562 if (!HandleConditionalOperator(E)) {
6563 Fold.keepDiagnostics();
6564 return false;
6565 }
6566
6567 return true;
6568 }
6569
6570 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6571 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6572 return DerivedSuccess(*Value, E);
6573
6574 const Expr *Source = E->getSourceExpr();
6575 if (!Source)
6576 return Error(E);
6577 if (Source == E) { // sanity checking.
6578 assert(0 && "OpaqueValueExpr recursively refers to itself")((0 && "OpaqueValueExpr recursively refers to itself"
) ? static_cast<void> (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6578, __PRETTY_FUNCTION__))
;
6579 return Error(E);
6580 }
6581 return StmtVisitorTy::Visit(Source);
6582 }
6583
6584 bool VisitCallExpr(const CallExpr *E) {
6585 APValue Result;
6586 if (!handleCallExpr(E, Result, nullptr))
1
Calling 'ExprEvaluatorBase::handleCallExpr'
6587 return false;
6588 return DerivedSuccess(Result, E);
6589 }
6590
6591 bool handleCallExpr(const CallExpr *E, APValue &Result,
6592 const LValue *ResultSlot) {
6593 const Expr *Callee = E->getCallee()->IgnoreParens();
6594 QualType CalleeType = Callee->getType();
6595
6596 const FunctionDecl *FD = nullptr;
6597 LValue *This = nullptr, ThisVal;
6598 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6599 bool HasQualifier = false;
6600
6601 // Extract function decl and 'this' pointer from the callee.
6602 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2
Taking true branch
6603 const CXXMethodDecl *Member = nullptr;
6604 if (const MemberExpr *ME
3.1
'ME' is null
3.1
'ME' is null
3.1
'ME' is null
= dyn_cast<MemberExpr>(Callee)) {
3
Assuming 'Callee' is not a 'MemberExpr'
4
Taking false branch
6605 // Explicit bound member calls, such as x.f() or p->g();
6606 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6607 return false;
6608 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6609 if (!Member)
6610 return Error(Callee);
6611 This = &ThisVal;
6612 HasQualifier = ME->hasQualifier();
6613 } else if (const BinaryOperator *BE
5.1
'BE' is non-null
5.1
'BE' is non-null
5.1
'BE' is non-null
= dyn_cast<BinaryOperator>(Callee)) {
5
Assuming 'Callee' is a 'BinaryOperator'
6
Taking true branch
6614 // Indirect bound member calls ('.*' or '->*').
6615 Member = dyn_cast_or_null<CXXMethodDecl>(
7
Assuming the object is a 'CXXMethodDecl'
6616 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6617 if (!Member
7.1
'Member' is non-null
7.1
'Member' is non-null
7.1
'Member' is non-null
)
8
Taking false branch
6618 return Error(Callee);
6619 This = &ThisVal;
6620 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6621 if (!Info.getLangOpts().CPlusPlus2a)
6622 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6623 // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6624 // their callee, we should start calling HandleDestruction here.
6625 // For now, we just evaluate the object argument and discard it.
6626 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
6627 } else
6628 return Error(Callee);
6629 FD = Member;
6630 } else if (CalleeType->isFunctionPointerType()) {
6631 LValue Call;
6632 if (!EvaluatePointer(Callee, Call, Info))
6633 return false;
6634
6635 if (!Call.getLValueOffset().isZero())
6636 return Error(Callee);
6637 FD = dyn_cast_or_null<FunctionDecl>(
6638 Call.getLValueBase().dyn_cast<const ValueDecl*>());
6639 if (!FD)
6640 return Error(Callee);
6641 // Don't call function pointers which have been cast to some other type.
6642 // Per DR (no number yet), the caller and callee can differ in noexcept.
6643 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6644 CalleeType->getPointeeType(), FD->getType())) {
6645 return Error(E);
6646 }
6647
6648 // Overloaded operator calls to member functions are represented as normal
6649 // calls with '*this' as the first argument.
6650 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6651 if (MD && !MD->isStatic()) {
6652 // FIXME: When selecting an implicit conversion for an overloaded
6653 // operator delete, we sometimes try to evaluate calls to conversion
6654 // operators without a 'this' parameter!
6655 if (Args.empty())
6656 return Error(E);
6657
6658 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6659 return false;
6660 This = &ThisVal;
6661 Args = Args.slice(1);
6662 } else if (MD && MD->isLambdaStaticInvoker()) {
6663 // Map the static invoker for the lambda back to the call operator.
6664 // Conveniently, we don't have to slice out the 'this' argument (as is
6665 // being done for the non-static case), since a static member function
6666 // doesn't have an implicit argument passed in.
6667 const CXXRecordDecl *ClosureClass = MD->getParent();
6668 assert(((ClosureClass->captures_begin() == ClosureClass->captures_end
() && "Number of captures must be zero for conversion to function-ptr"
) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6670, __PRETTY_FUNCTION__))
6669 ClosureClass->captures_begin() == ClosureClass->captures_end() &&((ClosureClass->captures_begin() == ClosureClass->captures_end
() && "Number of captures must be zero for conversion to function-ptr"
) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6670, __PRETTY_FUNCTION__))
6670 "Number of captures must be zero for conversion to function-ptr")((ClosureClass->captures_begin() == ClosureClass->captures_end
() && "Number of captures must be zero for conversion to function-ptr"
) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6670, __PRETTY_FUNCTION__))
;
6671
6672 const CXXMethodDecl *LambdaCallOp =
6673 ClosureClass->getLambdaCallOperator();
6674
6675 // Set 'FD', the function that will be called below, to the call
6676 // operator. If the closure object represents a generic lambda, find
6677 // the corresponding specialization of the call operator.
6678
6679 if (ClosureClass->isGenericLambda()) {
6680 assert(MD->isFunctionTemplateSpecialization() &&((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a "
"template specialization") ? static_cast<void> (0) : __assert_fail
("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6682, __PRETTY_FUNCTION__))
6681 "A generic lambda's static-invoker function must be a "((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a "
"template specialization") ? static_cast<void> (0) : __assert_fail
("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6682, __PRETTY_FUNCTION__))
6682 "template specialization")((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a "
"template specialization") ? static_cast<void> (0) : __assert_fail
("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6682, __PRETTY_FUNCTION__))
;
6683 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6684 FunctionTemplateDecl *CallOpTemplate =
6685 LambdaCallOp->getDescribedFunctionTemplate();
6686 void *InsertPos = nullptr;
6687 FunctionDecl *CorrespondingCallOpSpecialization =
6688 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6689 assert(CorrespondingCallOpSpecialization &&((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? static_cast
<void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6691, __PRETTY_FUNCTION__))
6690 "We must always have a function call operator specialization "((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? static_cast
<void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6691, __PRETTY_FUNCTION__))
6691 "that corresponds to our static invoker specialization")((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? static_cast
<void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6691, __PRETTY_FUNCTION__))
;
6692 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6693 } else
6694 FD = LambdaCallOp;
6695 }
6696 } else
6697 return Error(E);
6698
6699 SmallVector<QualType, 4> CovariantAdjustmentPath;
6700 if (This
8.1
'This' is non-null
8.1
'This' is non-null
8.1
'This' is non-null
) {
9
Taking true branch
6701 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
10
Assuming 'FD' is not a 'CXXMethodDecl'
6702 if (NamedMember
10.1
'NamedMember' is null
10.1
'NamedMember' is null
10.1
'NamedMember' is null
&& NamedMember->isVirtual() && !HasQualifier) {
6703 // Perform virtual dispatch, if necessary.
6704 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6705 CovariantAdjustmentPath);
6706 if (!FD)
6707 return false;
6708 } else {
6709 // Check that the 'this' pointer points to an object of the right type.
6710 // FIXME: If this is an assignment operator call, we may need to change
6711 // the active union member before we check this.
6712 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
11
Assuming the condition is false
12
Taking false branch
6713 return false;
6714 }
6715 }
6716
6717 // Destructor calls are different enough that they have their own codepath.
6718 if (auto *DD
13.1
'DD' is null
13.1
'DD' is null
13.1
'DD' is null
= dyn_cast<CXXDestructorDecl>(FD)) {
13
Assuming 'FD' is not a 'CXXDestructorDecl'
14
Taking false branch
6719 assert(This && "no 'this' pointer for destructor call")((This && "no 'this' pointer for destructor call") ? static_cast
<void> (0) : __assert_fail ("This && \"no 'this' pointer for destructor call\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6719, __PRETTY_FUNCTION__))
;
6720 return HandleDestruction(Info, E, *This,
6721 Info.Ctx.getRecordType(DD->getParent()));
6722 }
6723
6724 const FunctionDecl *Definition = nullptr;
6725 Stmt *Body = FD->getBody(Definition);
6726
6727 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
15
Calling 'CheckConstexprFunction'
25
Returning from 'CheckConstexprFunction'
6728 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
26
Calling 'HandleFunctionCall'
6729 Result, ResultSlot))
6730 return false;
6731
6732 if (!CovariantAdjustmentPath.empty() &&
6733 !HandleCovariantReturnAdjustment(Info, E, Result,
6734 CovariantAdjustmentPath))
6735 return false;
6736
6737 return true;
6738 }
6739
6740 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6741 return StmtVisitorTy::Visit(E->getInitializer());
6742 }
6743 bool VisitInitListExpr(const InitListExpr *E) {
6744 if (E->getNumInits() == 0)
6745 return DerivedZeroInitialization(E);
6746 if (E->getNumInits() == 1)
6747 return StmtVisitorTy::Visit(E->getInit(0));
6748 return Error(E);
6749 }
6750 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
6751 return DerivedZeroInitialization(E);
6752 }
6753 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
6754 return DerivedZeroInitialization(E);
6755 }
6756 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
6757 return DerivedZeroInitialization(E);
6758 }
6759
6760 /// A member expression where the object is a prvalue is itself a prvalue.
6761 bool VisitMemberExpr(const MemberExpr *E) {
6762 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&((!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion"
) ? static_cast<void> (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6763, __PRETTY_FUNCTION__))
6763 "missing temporary materialization conversion")((!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion"
) ? static_cast<void> (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6763, __PRETTY_FUNCTION__))
;
6764 assert(!E->isArrow() && "missing call to bound member function?")((!E->isArrow() && "missing call to bound member function?"
) ? static_cast<void> (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6764, __PRETTY_FUNCTION__))
;
6765
6766 APValue Val;
6767 if (!Evaluate(Val, Info, E->getBase()))
6768 return false;
6769
6770 QualType BaseTy = E->getBase()->getType();
6771
6772 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
6773 if (!FD) return Error(E);
6774 assert(!FD->getType()->isReferenceType() && "prvalue reference?")((!FD->getType()->isReferenceType() && "prvalue reference?"
) ? static_cast<void> (0) : __assert_fail ("!FD->getType()->isReferenceType() && \"prvalue reference?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6774, __PRETTY_FUNCTION__))
;
6775 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6776, __PRETTY_FUNCTION__))
6776 FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6776, __PRETTY_FUNCTION__))
;
6777
6778 // Note: there is no lvalue base here. But this case should only ever
6779 // happen in C or in C++98, where we cannot be evaluating a constexpr
6780 // constructor, which is the only case the base matters.
6781 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
6782 SubobjectDesignator Designator(BaseTy);
6783 Designator.addDeclUnchecked(FD);
6784
6785 APValue Result;
6786 return extractSubobject(Info, E, Obj, Designator, Result) &&
6787 DerivedSuccess(Result, E);
6788 }
6789
6790 bool VisitCastExpr(const CastExpr *E) {
6791 switch (E->getCastKind()) {
6792 default:
6793 break;
6794
6795 case CK_AtomicToNonAtomic: {
6796 APValue AtomicVal;
6797 // This does not need to be done in place even for class/array types:
6798 // atomic-to-non-atomic conversion implies copying the object
6799 // representation.
6800 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
6801 return false;
6802 return DerivedSuccess(AtomicVal, E);
6803 }
6804
6805 case CK_NoOp:
6806 case CK_UserDefinedConversion:
6807 return StmtVisitorTy::Visit(E->getSubExpr());
6808
6809 case CK_LValueToRValue: {
6810 LValue LVal;
6811 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6812 return false;
6813 APValue RVal;
6814 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6815 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6816 LVal, RVal))
6817 return false;
6818 return DerivedSuccess(RVal, E);
6819 }
6820 case CK_LValueToRValueBitCast: {
6821 APValue DestValue, SourceValue;
6822 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6823 return false;
6824 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6825 return false;
6826 return DerivedSuccess(DestValue, E);
6827 }
6828 }
6829
6830 return Error(E);
6831 }
6832
6833 bool VisitUnaryPostInc(const UnaryOperator *UO) {
6834 return VisitUnaryPostIncDec(UO);
6835 }
6836 bool VisitUnaryPostDec(const UnaryOperator *UO) {
6837 return VisitUnaryPostIncDec(UO);
6838 }
6839 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
6840 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6841 return Error(UO);
6842
6843 LValue LVal;
6844 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6845 return false;
6846 APValue RVal;
6847 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6848 UO->isIncrementOp(), &RVal))
6849 return false;
6850 return DerivedSuccess(RVal, UO);
6851 }
6852
6853 bool VisitStmtExpr(const StmtExpr *E) {
6854 // We will have checked the full-expressions inside the statement expression
6855 // when they were completed, and don't need to check them again now.
6856 if (Info.checkingForUndefinedBehavior())
6857 return Error(E);
6858
6859 const CompoundStmt *CS = E->getSubStmt();
6860 if (CS->body_empty())
6861 return true;
6862
6863 BlockScopeRAII Scope(Info);
6864 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6865 BE = CS->body_end();
6866 /**/; ++BI) {
6867 if (BI + 1 == BE) {
6868 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6869 if (!FinalExpr) {
6870 Info.FFDiag((*BI)->getBeginLoc(),
6871 diag::note_constexpr_stmt_expr_unsupported);
6872 return false;
6873 }
6874 return this->Visit(FinalExpr) && Scope.destroy();
6875 }
6876
6877 APValue ReturnValue;
6878 StmtResult Result = { ReturnValue, nullptr };
6879 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
6880 if (ESR != ESR_Succeeded) {
6881 // FIXME: If the statement-expression terminated due to 'return',
6882 // 'break', or 'continue', it would be nice to propagate that to
6883 // the outer statement evaluation rather than bailing out.
6884 if (ESR != ESR_Failed)
6885 Info.FFDiag((*BI)->getBeginLoc(),
6886 diag::note_constexpr_stmt_expr_unsupported);
6887 return false;
6888 }
6889 }
6890
6891 llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above."
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6891)
;
6892 }
6893
6894 /// Visit a value which is evaluated, but whose value is ignored.
6895 void VisitIgnoredValue(const Expr *E) {
6896 EvaluateIgnoredValue(Info, E);
6897 }
6898
6899 /// Potentially visit a MemberExpr's base expression.
6900 void VisitIgnoredBaseExpression(const Expr *E) {
6901 // While MSVC doesn't evaluate the base expression, it does diagnose the
6902 // presence of side-effecting behavior.
6903 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6904 return;
6905 VisitIgnoredValue(E);
6906 }
6907};
6908
6909} // namespace
6910
6911//===----------------------------------------------------------------------===//
6912// Common base class for lvalue and temporary evaluation.
6913//===----------------------------------------------------------------------===//
6914namespace {
6915template<class Derived>
6916class LValueExprEvaluatorBase
6917 : public ExprEvaluatorBase<Derived> {
6918protected:
6919 LValue &Result;
6920 bool InvalidBaseOK;
6921 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
6922 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
6923
6924 bool Success(APValue::LValueBase B) {
6925 Result.set(B);
6926 return true;
6927 }
6928
6929 bool evaluatePointer(const Expr *E, LValue &Result) {
6930 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6931 }
6932
6933public:
6934 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6935 : ExprEvaluatorBaseTy(Info), Result(Result),
6936 InvalidBaseOK(InvalidBaseOK) {}
6937
6938 bool Success(const APValue &V, const Expr *E) {
6939 Result.setFrom(this->Info.Ctx, V);
6940 return true;
6941 }
6942
6943 bool VisitMemberExpr(const MemberExpr *E) {
6944 // Handle non-static data members.
6945 QualType BaseTy;
6946 bool EvalOK;
6947 if (E->isArrow()) {
6948 EvalOK = evaluatePointer(E->getBase(), Result);
6949 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
6950 } else if (E->getBase()->isRValue()) {
6951 assert(E->getBase()->getType()->isRecordType())((E->getBase()->getType()->isRecordType()) ? static_cast
<void> (0) : __assert_fail ("E->getBase()->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6951, __PRETTY_FUNCTION__))
;
6952 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
6953 BaseTy = E->getBase()->getType();
6954 } else {
6955 EvalOK = this->Visit(E->getBase());
6956 BaseTy = E->getBase()->getType();
6957 }
6958 if (!EvalOK) {
6959 if (!InvalidBaseOK)
6960 return false;
6961 Result.setInvalid(E);
6962 return true;
6963 }
6964
6965 const ValueDecl *MD = E->getMemberDecl();
6966 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6967 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6968, __PRETTY_FUNCTION__))
6968 FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 6968, __PRETTY_FUNCTION__))
;
6969 (void)BaseTy;
6970 if (!HandleLValueMember(this->Info, E, Result, FD))
6971 return false;
6972 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
6973 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6974 return false;
6975 } else
6976 return this->Error(E);
6977
6978 if (MD->getType()->isReferenceType()) {
6979 APValue RefValue;
6980 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
6981 RefValue))
6982 return false;
6983 return Success(RefValue, E);
6984 }
6985 return true;
6986 }
6987
6988 bool VisitBinaryOperator(const BinaryOperator *E) {
6989 switch (E->getOpcode()) {
6990 default:
6991 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6992
6993 case BO_PtrMemD:
6994 case BO_PtrMemI:
6995 return HandleMemberPointerAccess(this->Info, E, Result);
6996 }
6997 }
6998
6999 bool VisitCastExpr(const CastExpr *E) {
7000 switch (E->getCastKind()) {
7001 default:
7002 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7003
7004 case CK_DerivedToBase:
7005 case CK_UncheckedDerivedToBase:
7006 if (!this->Visit(E->getSubExpr()))
7007 return false;
7008
7009 // Now figure out the necessary offset to add to the base LV to get from
7010 // the derived class to the base class.
7011 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7012 Result);
7013 }
7014 }
7015};
7016}
7017
7018//===----------------------------------------------------------------------===//
7019// LValue Evaluation
7020//
7021// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7022// function designators (in C), decl references to void objects (in C), and
7023// temporaries (if building with -Wno-address-of-temporary).
7024//
7025// LValue evaluation produces values comprising a base expression of one of the
7026// following types:
7027// - Declarations
7028// * VarDecl
7029// * FunctionDecl
7030// - Literals
7031// * CompoundLiteralExpr in C (and in global scope in C++)
7032// * StringLiteral
7033// * PredefinedExpr
7034// * ObjCStringLiteralExpr
7035// * ObjCEncodeExpr
7036// * AddrLabelExpr
7037// * BlockExpr
7038// * CallExpr for a MakeStringConstant builtin
7039// - typeid(T) expressions, as TypeInfoLValues
7040// - Locals and temporaries
7041// * MaterializeTemporaryExpr
7042// * Any Expr, with a CallIndex indicating the function in which the temporary
7043// was evaluated, for cases where the MaterializeTemporaryExpr is missing
7044// from the AST (FIXME).
7045// * A MaterializeTemporaryExpr that has static storage duration, with no
7046// CallIndex, for a lifetime-extended temporary.
7047// plus an offset in bytes.
7048//===----------------------------------------------------------------------===//
7049namespace {
7050class LValueExprEvaluator
7051 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7052public:
7053 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7054 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7055
7056 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7057 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7058
7059 bool VisitDeclRefExpr(const DeclRefExpr *E);
7060 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7061 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7062 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7063 bool VisitMemberExpr(const MemberExpr *E);
7064 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7065 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7066 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7067 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7068 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7069 bool VisitUnaryDeref(const UnaryOperator *E);
7070 bool VisitUnaryReal(const UnaryOperator *E);
7071 bool VisitUnaryImag(const UnaryOperator *E);
7072 bool VisitUnaryPreInc(const UnaryOperator *UO) {
7073 return VisitUnaryPreIncDec(UO);
7074 }
7075 bool VisitUnaryPreDec(const UnaryOperator *UO) {
7076 return VisitUnaryPreIncDec(UO);
7077 }
7078 bool VisitBinAssign(const BinaryOperator *BO);
7079 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7080
7081 bool VisitCastExpr(const CastExpr *E) {
7082 switch (E->getCastKind()) {
7083 default:
7084 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7085
7086 case CK_LValueBitCast:
7087 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7088 if (!Visit(E->getSubExpr()))
7089 return false;
7090 Result.Designator.setInvalid();
7091 return true;
7092
7093 case CK_BaseToDerived:
7094 if (!Visit(E->getSubExpr()))
7095 return false;
7096 return HandleBaseToDerivedCast(Info, E, Result);
7097
7098 case CK_Dynamic:
7099 if (!Visit(E->getSubExpr()))
7100 return false;
7101 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7102 }
7103 }
7104};
7105} // end anonymous namespace
7106
7107/// Evaluate an expression as an lvalue. This can be legitimately called on
7108/// expressions which are not glvalues, in three cases:
7109/// * function designators in C, and
7110/// * "extern void" objects
7111/// * @selector() expressions in Objective-C
7112static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7113 bool InvalidBaseOK) {
7114 assert(E->isGLValue() || E->getType()->isFunctionType() ||((E->isGLValue() || E->getType()->isFunctionType() ||
E->getType()->isVoidType() || isa<ObjCSelectorExpr>
(E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7115, __PRETTY_FUNCTION__))
7115 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))((E->isGLValue() || E->getType()->isFunctionType() ||
E->getType()->isVoidType() || isa<ObjCSelectorExpr>
(E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7115, __PRETTY_FUNCTION__))
;
7116 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7117}
7118
7119bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7120 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7121 return Success(FD);
7122 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7123 return VisitVarDecl(E, VD);
7124 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7125 return Visit(BD->getBinding());
7126 return Error(E);
7127}
7128
7129
7130bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7131
7132 // If we are within a lambda's call operator, check whether the 'VD' referred
7133 // to within 'E' actually represents a lambda-capture that maps to a
7134 // data-member/field within the closure object, and if so, evaluate to the
7135 // field or what the field refers to.
7136 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7137 isa<DeclRefExpr>(E) &&
7138 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7139 // We don't always have a complete capture-map when checking or inferring if
7140 // the function call operator meets the requirements of a constexpr function
7141 // - but we don't need to evaluate the captures to determine constexprness
7142 // (dcl.constexpr C++17).
7143 if (Info.checkingPotentialConstantExpression())
7144 return false;
7145
7146 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7147 // Start with 'Result' referring to the complete closure object...
7148 Result = *Info.CurrentCall->This;
7149 // ... then update it to refer to the field of the closure object
7150 // that represents the capture.
7151 if (!HandleLValueMember(Info, E, Result, FD))
7152 return false;
7153 // And if the field is of reference type, update 'Result' to refer to what
7154 // the field refers to.
7155 if (FD->getType()->isReferenceType()) {
7156 APValue RVal;
7157 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7158 RVal))
7159 return false;
7160 Result.setFrom(Info.Ctx, RVal);
7161 }
7162 return true;
7163 }
7164 }
7165 CallStackFrame *Frame = nullptr;
7166 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7167 // Only if a local variable was declared in the function currently being
7168 // evaluated, do we expect to be able to find its value in the current
7169 // frame. (Otherwise it was likely declared in an enclosing context and
7170 // could either have a valid evaluatable value (for e.g. a constexpr
7171 // variable) or be ill-formed (and trigger an appropriate evaluation
7172 // diagnostic)).
7173 if (Info.CurrentCall->Callee &&
7174 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7175 Frame = Info.CurrentCall;
7176 }
7177 }
7178
7179 if (!VD->getType()->isReferenceType()) {
7180 if (Frame) {
7181 Result.set({VD, Frame->Index,
7182 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7183 return true;
7184 }
7185 return Success(VD);
7186 }
7187
7188 APValue *V;
7189 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7190 return false;
7191 if (!V->hasValue()) {
7192 // FIXME: Is it possible for V to be indeterminate here? If so, we should
7193 // adjust the diagnostic to say that.
7194 if (!Info.checkingPotentialConstantExpression())
7195 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7196 return false;
7197 }
7198 return Success(*V, E);
7199}
7200
7201bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7202 const MaterializeTemporaryExpr *E) {
7203 // Walk through the expression to find the materialized temporary itself.
7204 SmallVector<const Expr *, 2> CommaLHSs;
7205 SmallVector<SubobjectAdjustment, 2> Adjustments;
7206 const Expr *Inner = E->GetTemporaryExpr()->
7207 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7208
7209 // If we passed any comma operators, evaluate their LHSs.
7210 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7211 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7212 return false;
7213
7214 // A materialized temporary with static storage duration can appear within the
7215 // result of a constant expression evaluation, so we need to preserve its
7216 // value for use outside this evaluation.
7217 APValue *Value;
7218 if (E->getStorageDuration() == SD_Static) {
7219 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
7220 *Value = APValue();
7221 Result.set(E);
7222 } else {
7223 Value = &Info.CurrentCall->createTemporary(
7224 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7225 }
7226
7227 QualType Type = Inner->getType();
7228
7229 // Materialize the temporary itself.
7230 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7231 *Value = APValue();
7232 return false;
7233 }
7234
7235 // Adjust our lvalue to refer to the desired subobject.
7236 for (unsigned I = Adjustments.size(); I != 0; /**/) {
7237 --I;
7238 switch (Adjustments[I].Kind) {
7239 case SubobjectAdjustment::DerivedToBaseAdjustment:
7240 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7241 Type, Result))
7242 return false;
7243 Type = Adjustments[I].DerivedToBase.BasePath->getType();
7244 break;
7245
7246 case SubobjectAdjustment::FieldAdjustment:
7247 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7248 return false;
7249 Type = Adjustments[I].Field->getType();
7250 break;
7251
7252 case SubobjectAdjustment::MemberPointerAdjustment:
7253 if (!HandleMemberPointerAccess(this->Info, Type, Result,
7254 Adjustments[I].Ptr.RHS))
7255 return false;
7256 Type = Adjustments[I].Ptr.MPT->getPointeeType();
7257 break;
7258 }
7259 }
7260
7261 return true;
7262}
7263
7264bool
7265LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7266 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
"lvalue compound literal in c++?") ? static_cast<void>
(0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7267, __PRETTY_FUNCTION__))
7267 "lvalue compound literal in c++?")(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
"lvalue compound literal in c++?") ? static_cast<void>
(0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7267, __PRETTY_FUNCTION__))
;
7268 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7269 // only see this when folding in C, so there's no standard to follow here.
7270 return Success(E);
7271}
7272
7273bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7274 TypeInfoLValue TypeInfo;
7275
7276 if (!E->isPotentiallyEvaluated()) {
7277 if (E->isTypeOperand())
7278 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7279 else
7280 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7281 } else {
7282 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7283 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7284 << E->getExprOperand()->getType()
7285 << E->getExprOperand()->getSourceRange();
7286 }
7287
7288 if (!Visit(E->getExprOperand()))
7289 return false;
7290
7291 Optional<DynamicType> DynType =
7292 ComputeDynamicType(Info, E, Result, AK_TypeId);
7293 if (!DynType)
7294 return false;
7295
7296 TypeInfo =
7297 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7298 }
7299
7300 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7301}
7302
7303bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7304 return Success(E);
7305}
7306
7307bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7308 // Handle static data members.
7309 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7310 VisitIgnoredBaseExpression(E->getBase());
7311 return VisitVarDecl(E, VD);
7312 }
7313
7314 // Handle static member functions.
7315 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7316 if (MD->isStatic()) {
7317 VisitIgnoredBaseExpression(E->getBase());
7318 return Success(MD);
7319 }
7320 }
7321
7322 // Handle non-static data members.
7323 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7324}
7325
7326bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7327 // FIXME: Deal with vectors as array subscript bases.
7328 if (E->getBase()->getType()->isVectorType())
7329 return Error(E);
7330
7331 bool Success = true;
7332 if (!evaluatePointer(E->getBase(), Result)) {
7333 if (!Info.noteFailure())
7334 return false;
7335 Success = false;
7336 }
7337
7338 APSInt Index;
7339 if (!EvaluateInteger(E->getIdx(), Index, Info))
7340 return false;
7341
7342 return Success &&
7343 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7344}
7345
7346bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7347 return evaluatePointer(E->getSubExpr(), Result);
7348}
7349
7350bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7351 if (!Visit(E->getSubExpr()))
7352 return false;
7353 // __real is a no-op on scalar lvalues.
7354 if (E->getSubExpr()->getType()->isAnyComplexType())
7355 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7356 return true;
7357}
7358
7359bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7360 assert(E->getSubExpr()->getType()->isAnyComplexType() &&((E->getSubExpr()->getType()->isAnyComplexType() &&
"lvalue __imag__ on scalar?") ? static_cast<void> (0) :
__assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7361, __PRETTY_FUNCTION__))
7361 "lvalue __imag__ on scalar?")((E->getSubExpr()->getType()->isAnyComplexType() &&
"lvalue __imag__ on scalar?") ? static_cast<void> (0) :
__assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7361, __PRETTY_FUNCTION__))
;
7362 if (!Visit(E->getSubExpr()))
7363 return false;
7364 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7365 return true;
7366}
7367
7368bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7369 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7370 return Error(UO);
7371
7372 if (!this->Visit(UO->getSubExpr()))
7373 return false;
7374
7375 return handleIncDec(
7376 this->Info, UO, Result, UO->getSubExpr()->getType(),
7377 UO->isIncrementOp(), nullptr);
7378}
7379
7380bool LValueExprEvaluator::VisitCompoundAssignOperator(
7381 const CompoundAssignOperator *CAO) {
7382 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7383 return Error(CAO);
7384
7385 APValue RHS;
7386
7387 // The overall lvalue result is the result of evaluating the LHS.
7388 if (!this->Visit(CAO->getLHS())) {
7389 if (Info.noteFailure())
7390 Evaluate(RHS, this->Info, CAO->getRHS());
7391 return false;
7392 }
7393
7394 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7395 return false;
7396
7397 return handleCompoundAssignment(
7398 this->Info, CAO,
7399 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7400 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7401}
7402
7403bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7404 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7405 return Error(E);
7406
7407 APValue NewVal;
7408
7409 if (!this->Visit(E->getLHS())) {
7410 if (Info.noteFailure())
7411 Evaluate(NewVal, this->Info, E->getRHS());
7412 return false;
7413 }
7414
7415 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7416 return false;
7417
7418 if (Info.getLangOpts().CPlusPlus2a &&
7419 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7420 return false;
7421
7422 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7423 NewVal);
7424}
7425
7426//===----------------------------------------------------------------------===//
7427// Pointer Evaluation
7428//===----------------------------------------------------------------------===//
7429
7430/// Attempts to compute the number of bytes available at the pointer
7431/// returned by a function with the alloc_size attribute. Returns true if we
7432/// were successful. Places an unsigned number into `Result`.
7433///
7434/// This expects the given CallExpr to be a call to a function with an
7435/// alloc_size attribute.
7436static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7437 const CallExpr *Call,
7438 llvm::APInt &Result) {
7439 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7440
7441 assert(AllocSize && AllocSize->getElemSizeParam().isValid())((AllocSize && AllocSize->getElemSizeParam().isValid
()) ? static_cast<void> (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7441, __PRETTY_FUNCTION__))
;
7442 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7443 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7444 if (Call->getNumArgs() <= SizeArgNo)
7445 return false;
7446
7447 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7448 Expr::EvalResult ExprResult;
7449 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7450 return false;
7451 Into = ExprResult.Val.getInt();
7452 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7453 return false;
7454 Into = Into.zextOrSelf(BitsInSizeT);
7455 return true;
7456 };
7457
7458 APSInt SizeOfElem;
7459 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7460 return false;
7461
7462 if (!AllocSize->getNumElemsParam().isValid()) {
7463 Result = std::move(SizeOfElem);
7464 return true;
7465 }
7466
7467 APSInt NumberOfElems;
7468 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7469 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7470 return false;
7471
7472 bool Overflow;
7473 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7474 if (Overflow)
7475 return false;
7476
7477 Result = std::move(BytesAvailable);
7478 return true;
7479}
7480
7481/// Convenience function. LVal's base must be a call to an alloc_size
7482/// function.
7483static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7484 const LValue &LVal,
7485 llvm::APInt &Result) {
7486 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7487, __PRETTY_FUNCTION__))
7487 "Can't get the size of a non alloc_size function")((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7487, __PRETTY_FUNCTION__))
;
7488 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7489 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7490 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7491}
7492
7493/// Attempts to evaluate the given LValueBase as the result of a call to
7494/// a function with the alloc_size attribute. If it was possible to do so, this
7495/// function will return true, make Result's Base point to said function call,
7496/// and mark Result's Base as invalid.
7497static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7498 LValue &Result) {
7499 if (Base.isNull())
7500 return false;
7501
7502 // Because we do no form of static analysis, we only support const variables.
7503 //
7504 // Additionally, we can't support parameters, nor can we support static
7505 // variables (in the latter case, use-before-assign isn't UB; in the former,
7506 // we have no clue what they'll be assigned to).
7507 const auto *VD =
7508 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7509 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7510 return false;
7511
7512 const Expr *Init = VD->getAnyInitializer();
7513 if (!Init)
7514 return false;
7515
7516 const Expr *E = Init->IgnoreParens();
7517 if (!tryUnwrapAllocSizeCall(E))
7518 return false;
7519
7520 // Store E instead of E unwrapped so that the type of the LValue's base is
7521 // what the user wanted.
7522 Result.setInvalid(E);
7523
7524 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7525 Result.addUnsizedArray(Info, E, Pointee);
7526 return true;
7527}
7528
7529namespace {
7530class PointerExprEvaluator
7531 : public ExprEvaluatorBase<PointerExprEvaluator> {
7532 LValue &Result;
7533 bool InvalidBaseOK;
7534
7535 bool Success(const Expr *E) {
7536 Result.set(E);
7537 return true;
7538 }
7539
7540 bool evaluateLValue(const Expr *E, LValue &Result) {
7541 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7542 }
7543
7544 bool evaluatePointer(const Expr *E, LValue &Result) {
7545 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7546 }
7547
7548 bool visitNonBuiltinCallExpr(const CallExpr *E);
7549public:
7550
7551 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7552 : ExprEvaluatorBaseTy(info), Result(Result),
7553 InvalidBaseOK(InvalidBaseOK) {}
7554
7555 bool Success(const APValue &V, const Expr *E) {
7556 Result.setFrom(Info.Ctx, V);
7557 return true;
7558 }
7559 bool ZeroInitialization(const Expr *E) {
7560 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7561 Result.setNull(E->getType(), TargetVal);
7562 return true;
7563 }
7564
7565 bool VisitBinaryOperator(const BinaryOperator *E);
7566 bool VisitCastExpr(const CastExpr* E);
7567 bool VisitUnaryAddrOf(const UnaryOperator *E);
7568 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7569 { return Success(E); }
7570 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7571 if (E->isExpressibleAsConstantInitializer())
7572 return Success(E);
7573 if (Info.noteFailure())
7574 EvaluateIgnoredValue(Info, E->getSubExpr());
7575 return Error(E);
7576 }
7577 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7578 { return Success(E); }
7579 bool VisitCallExpr(const CallExpr *E);
7580 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7581 bool VisitBlockExpr(const BlockExpr *E) {
7582 if (!E->getBlockDecl()->hasCaptures())
7583 return Success(E);
7584 return Error(E);
7585 }
7586 bool VisitCXXThisExpr(const CXXThisExpr *E) {
7587 // Can't look at 'this' when checking a potential constant expression.
7588 if (Info.checkingPotentialConstantExpression())
7589 return false;
7590 if (!Info.CurrentCall->This) {
7591 if (Info.getLangOpts().CPlusPlus11)
7592 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7593 else
7594 Info.FFDiag(E);
7595 return false;
7596 }
7597 Result = *Info.CurrentCall->This;
7598 // If we are inside a lambda's call operator, the 'this' expression refers
7599 // to the enclosing '*this' object (either by value or reference) which is
7600 // either copied into the closure object's field that represents the '*this'
7601 // or refers to '*this'.
7602 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7603 // Update 'Result' to refer to the data member/field of the closure object
7604 // that represents the '*this' capture.
7605 if (!HandleLValueMember(Info, E, Result,
7606 Info.CurrentCall->LambdaThisCaptureField))
7607 return false;
7608 // If we captured '*this' by reference, replace the field with its referent.
7609 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7610 ->isPointerType()) {
7611 APValue RVal;
7612 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7613 RVal))
7614 return false;
7615
7616 Result.setFrom(Info.Ctx, RVal);
7617 }
7618 }
7619 return true;
7620 }
7621
7622 bool VisitCXXNewExpr(const CXXNewExpr *E);
7623
7624 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7625 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?")((E->isStringType() && "SourceLocExpr isn't a pointer type?"
) ? static_cast<void> (0) : __assert_fail ("E->isStringType() && \"SourceLocExpr isn't a pointer type?\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7625, __PRETTY_FUNCTION__))
;
7626 APValue LValResult = E->EvaluateInContext(
7627 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7628 Result.setFrom(Info.Ctx, LValResult);
7629 return true;
7630 }
7631
7632 // FIXME: Missing: @protocol, @selector
7633};
7634} // end anonymous namespace
7635
7636static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7637 bool InvalidBaseOK) {
7638 assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7638, __PRETTY_FUNCTION__))
;
7639 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7640}
7641
7642bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7643 if (E->getOpcode() != BO_Add &&
7644 E->getOpcode() != BO_Sub)
7645 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7646
7647 const Expr *PExp = E->getLHS();
7648 const Expr *IExp = E->getRHS();
7649 if (IExp->getType()->isPointerType())
7650 std::swap(PExp, IExp);
7651
7652 bool EvalPtrOK = evaluatePointer(PExp, Result);
7653 if (!EvalPtrOK && !Info.noteFailure())
7654 return false;
7655
7656 llvm::APSInt Offset;
7657 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7658 return false;
7659
7660 if (E->getOpcode() == BO_Sub)
7661 negateAsSigned(Offset);
7662
7663 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7664 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7665}
7666
7667bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7668 return evaluateLValue(E->getSubExpr(), Result);
7669}
7670
7671bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7672 const Expr *SubExpr = E->getSubExpr();
7673
7674 switch (E->getCastKind()) {
7675 default:
7676 break;
7677 case CK_BitCast:
7678 case CK_CPointerToObjCPointerCast:
7679 case CK_BlockPointerToObjCPointerCast:
7680 case CK_AnyPointerToBlockPointerCast:
7681 case CK_AddressSpaceConversion:
7682 if (!Visit(SubExpr))
7683 return false;
7684 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7685 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7686 // also static_casts, but we disallow them as a resolution to DR1312.
7687 if (!E->getType()->isVoidPointerType()) {
7688 Result.Designator.setInvalid();
7689 if (SubExpr->getType()->isVoidPointerType())
7690 CCEDiag(E, diag::note_constexpr_invalid_cast)
7691 << 3 << SubExpr->getType();
7692 else
7693 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7694 }
7695 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7696 ZeroInitialization(E);
7697 return true;
7698
7699 case CK_DerivedToBase:
7700 case CK_UncheckedDerivedToBase:
7701 if (!evaluatePointer(E->getSubExpr(), Result))
7702 return false;
7703 if (!Result.Base && Result.Offset.isZero())
7704 return true;
7705
7706 // Now figure out the necessary offset to add to the base LV to get from
7707 // the derived class to the base class.
7708 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7709 castAs<PointerType>()->getPointeeType(),
7710 Result);
7711
7712 case CK_BaseToDerived:
7713 if (!Visit(E->getSubExpr()))
7714 return false;
7715 if (!Result.Base && Result.Offset.isZero())
7716 return true;
7717 return HandleBaseToDerivedCast(Info, E, Result);
7718
7719 case CK_Dynamic:
7720 if (!Visit(E->getSubExpr()))
7721 return false;
7722 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7723
7724 case CK_NullToPointer:
7725 VisitIgnoredValue(E->getSubExpr());
7726 return ZeroInitialization(E);
7727
7728 case CK_IntegralToPointer: {
7729 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7730
7731 APValue Value;
7732 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
7733 break;
7734
7735 if (Value.isInt()) {
7736 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7737 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
7738 Result.Base = (Expr*)nullptr;
7739 Result.InvalidBase = false;
7740 Result.Offset = CharUnits::fromQuantity(N);
7741 Result.Designator.setInvalid();
7742 Result.IsNullPtr = false;
7743 return true;
7744 } else {
7745 // Cast is of an lvalue, no need to change value.
7746 Result.setFrom(Info.Ctx, Value);
7747 return true;
7748 }
7749 }
7750
7751 case CK_ArrayToPointerDecay: {
7752 if (SubExpr->isGLValue()) {
7753 if (!evaluateLValue(SubExpr, Result))
7754 return false;
7755 } else {
7756 APValue &Value = Info.CurrentCall->createTemporary(
7757 SubExpr, SubExpr->getType(), false, Result);
7758 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
7759 return false;
7760 }
7761 // The result is a pointer to the first element of the array.
7762 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7763 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
7764 Result.addArray(Info, E, CAT);
7765 else
7766 Result.addUnsizedArray(Info, E, AT->getElementType());
7767 return true;
7768 }
7769
7770 case CK_FunctionToPointerDecay:
7771 return evaluateLValue(SubExpr, Result);
7772
7773 case CK_LValueToRValue: {
7774 LValue LVal;
7775 if (!evaluateLValue(E->getSubExpr(), LVal))
7776 return false;
7777
7778 APValue RVal;
7779 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7780 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7781 LVal, RVal))
7782 return InvalidBaseOK &&
7783 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
7784 return Success(RVal, E);
7785 }
7786 }
7787
7788 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7789}
7790
7791static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7792 UnaryExprOrTypeTrait ExprKind) {
7793 // C++ [expr.alignof]p3:
7794 // When alignof is applied to a reference type, the result is the
7795 // alignment of the referenced type.
7796 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7797 T = Ref->getPointeeType();
7798
7799 if (T.getQualifiers().hasUnaligned())
7800 return CharUnits::One();
7801
7802 const bool AlignOfReturnsPreferred =
7803 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7804
7805 // __alignof is defined to return the preferred alignment.
7806 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7807 // as well.
7808 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7809 return Info.Ctx.toCharUnitsFromBits(
7810 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7811 // alignof and _Alignof are defined to return the ABI alignment.
7812 else if (ExprKind == UETT_AlignOf)
7813 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7814 else
7815 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7815)
;
7816}
7817
7818static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7819 UnaryExprOrTypeTrait ExprKind) {
7820 E = E->IgnoreParens();
7821
7822 // The kinds of expressions that we have special-case logic here for
7823 // should be kept up to date with the special checks for those
7824 // expressions in Sema.
7825
7826 // alignof decl is always accepted, even if it doesn't make sense: we default
7827 // to 1 in those cases.
7828 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7829 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7830 /*RefAsPointee*/true);
7831
7832 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7833 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7834 /*RefAsPointee*/true);
7835
7836 return GetAlignOfType(Info, E->getType(), ExprKind);
7837}
7838
7839// To be clear: this happily visits unsupported builtins. Better name welcomed.
7840bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7841 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7842 return true;
7843
7844 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
7845 return false;
7846
7847 Result.setInvalid(E);
7848 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
7849 Result.addUnsizedArray(Info, E, PointeeTy);
7850 return true;
7851}
7852
7853bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
7854 if (IsStringLiteralCall(E))
7855 return Success(E);
7856
7857 if (unsigned BuiltinOp = E->getBuiltinCallee())
7858 return VisitBuiltinCallExpr(E, BuiltinOp);
7859
7860 return visitNonBuiltinCallExpr(E);
7861}
7862
7863bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7864 unsigned BuiltinOp) {
7865 switch (BuiltinOp) {
7866 case Builtin::BI__builtin_addressof:
7867 return evaluateLValue(E->getArg(0), Result);
7868 case Builtin::BI__builtin_assume_aligned: {
7869 // We need to be very careful here because: if the pointer does not have the
7870 // asserted alignment, then the behavior is undefined, and undefined
7871 // behavior is non-constant.
7872 if (!evaluatePointer(E->getArg(0), Result))
7873 return false;
7874
7875 LValue OffsetResult(Result);
7876 APSInt Alignment;
7877 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7878 return false;
7879 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
7880
7881 if (E->getNumArgs() > 2) {
7882 APSInt Offset;
7883 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7884 return false;
7885
7886 int64_t AdditionalOffset = -Offset.getZExtValue();
7887 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7888 }
7889
7890 // If there is a base object, then it must have the correct alignment.
7891 if (OffsetResult.Base) {
7892 CharUnits BaseAlignment;
7893 if (const ValueDecl *VD =
7894 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7895 BaseAlignment = Info.Ctx.getDeclAlign(VD);
7896 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7897 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
7898 } else {
7899 BaseAlignment = GetAlignOfType(
7900 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
7901 }
7902
7903 if (BaseAlignment < Align) {
7904 Result.Designator.setInvalid();
7905 // FIXME: Add support to Diagnostic for long / long long.
7906 CCEDiag(E->getArg(0),
7907 diag::note_constexpr_baa_insufficient_alignment) << 0
7908 << (unsigned)BaseAlignment.getQuantity()
7909 << (unsigned)Align.getQuantity();
7910 return false;
7911 }
7912 }
7913
7914 // The offset must also have the correct alignment.
7915 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
7916 Result.Designator.setInvalid();
7917
7918 (OffsetResult.Base
7919 ? CCEDiag(E->getArg(0),
7920 diag::note_constexpr_baa_insufficient_alignment) << 1
7921 : CCEDiag(E->getArg(0),
7922 diag::note_constexpr_baa_value_insufficient_alignment))
7923 << (int)OffsetResult.Offset.getQuantity()
7924 << (unsigned)Align.getQuantity();
7925 return false;
7926 }
7927
7928 return true;
7929 }
7930 case Builtin::BI__builtin_launder:
7931 return evaluatePointer(E->getArg(0), Result);
7932 case Builtin::BIstrchr:
7933 case Builtin::BIwcschr:
7934 case Builtin::BImemchr:
7935 case Builtin::BIwmemchr:
7936 if (Info.getLangOpts().CPlusPlus11)
7937 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7938 << /*isConstexpr*/0 << /*isConstructor*/0
7939 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7940 else
7941 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7942 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7943 case Builtin::BI__builtin_strchr:
7944 case Builtin::BI__builtin_wcschr:
7945 case Builtin::BI__builtin_memchr:
7946 case Builtin::BI__builtin_char_memchr:
7947 case Builtin::BI__builtin_wmemchr: {
7948 if (!Visit(E->getArg(0)))
7949 return false;
7950 APSInt Desired;
7951 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7952 return false;
7953 uint64_t MaxLength = uint64_t(-1);
7954 if (BuiltinOp != Builtin::BIstrchr &&
7955 BuiltinOp != Builtin::BIwcschr &&
7956 BuiltinOp != Builtin::BI__builtin_strchr &&
7957 BuiltinOp != Builtin::BI__builtin_wcschr) {
7958 APSInt N;
7959 if (!EvaluateInteger(E->getArg(2), N, Info))
7960 return false;
7961 MaxLength = N.getExtValue();
7962 }
7963 // We cannot find the value if there are no candidates to match against.
7964 if (MaxLength == 0u)
7965 return ZeroInitialization(E);
7966 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7967 Result.Designator.Invalid)
7968 return false;
7969 QualType CharTy = Result.Designator.getType(Info.Ctx);
7970 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7971 BuiltinOp == Builtin::BI__builtin_memchr;
7972 assert(IsRawByte ||((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->
getArg(0)->getType()->getPointeeType())) ? static_cast<
void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7974, __PRETTY_FUNCTION__))
7973 Info.Ctx.hasSameUnqualifiedType(((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->
getArg(0)->getType()->getPointeeType())) ? static_cast<
void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7974, __PRETTY_FUNCTION__))
7974 CharTy, E->getArg(0)->getType()->getPointeeType()))((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->
getArg(0)->getType()->getPointeeType())) ? static_cast<
void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 7974, __PRETTY_FUNCTION__))
;
7975 // Pointers to const void may point to objects of incomplete type.
7976 if (IsRawByte && CharTy->isIncompleteType()) {
7977 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7978 return false;
7979 }
7980 // Give up on byte-oriented matching against multibyte elements.
7981 // FIXME: We can compare the bytes in the correct order.
7982 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7983 return false;
7984 // Figure out what value we're actually looking for (after converting to
7985 // the corresponding unsigned type if necessary).
7986 uint64_t DesiredVal;
7987 bool StopAtNull = false;
7988 switch (BuiltinOp) {
7989 case Builtin::BIstrchr:
7990 case Builtin::BI__builtin_strchr:
7991 // strchr compares directly to the passed integer, and therefore
7992 // always fails if given an int that is not a char.
7993 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7994 E->getArg(1)->getType(),
7995 Desired),
7996 Desired))
7997 return ZeroInitialization(E);
7998 StopAtNull = true;
7999 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8000 case Builtin::BImemchr:
8001 case Builtin::BI__builtin_memchr:
8002 case Builtin::BI__builtin_char_memchr:
8003 // memchr compares by converting both sides to unsigned char. That's also
8004 // correct for strchr if we get this far (to cope with plain char being
8005 // unsigned in the strchr case).
8006 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8007 break;
8008
8009 case Builtin::BIwcschr:
8010 case Builtin::BI__builtin_wcschr:
8011 StopAtNull = true;
8012 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8013 case Builtin::BIwmemchr:
8014 case Builtin::BI__builtin_wmemchr:
8015 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8016 DesiredVal = Desired.getZExtValue();
8017 break;
8018 }
8019
8020 for (; MaxLength; --MaxLength) {
8021 APValue Char;
8022 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8023 !Char.isInt())
8024 return false;
8025 if (Char.getInt().getZExtValue() == DesiredVal)
8026 return true;
8027 if (StopAtNull && !Char.getInt())
8028 break;
8029 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8030 return false;
8031 }
8032 // Not found: return nullptr.
8033 return ZeroInitialization(E);
8034 }
8035
8036 case Builtin::BImemcpy:
8037 case Builtin::BImemmove:
8038 case Builtin::BIwmemcpy:
8039 case Builtin::BIwmemmove:
8040 if (Info.getLangOpts().CPlusPlus11)
8041 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8042 << /*isConstexpr*/0 << /*isConstructor*/0
8043 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8044 else
8045 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8046 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8047 case Builtin::BI__builtin_memcpy:
8048 case Builtin::BI__builtin_memmove:
8049 case Builtin::BI__builtin_wmemcpy:
8050 case Builtin::BI__builtin_wmemmove: {
8051 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8052 BuiltinOp == Builtin::BIwmemmove ||
8053 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8054 BuiltinOp == Builtin::BI__builtin_wmemmove;
8055 bool Move = BuiltinOp == Builtin::BImemmove ||
8056 BuiltinOp == Builtin::BIwmemmove ||
8057 BuiltinOp == Builtin::BI__builtin_memmove ||
8058 BuiltinOp == Builtin::BI__builtin_wmemmove;
8059
8060 // The result of mem* is the first argument.
8061 if (!Visit(E->getArg(0)))
8062 return false;
8063 LValue Dest = Result;
8064
8065 LValue Src;
8066 if (!EvaluatePointer(E->getArg(1), Src, Info))
8067 return false;
8068
8069 APSInt N;
8070 if (!EvaluateInteger(E->getArg(2), N, Info))
8071 return false;
8072 assert(!N.isSigned() && "memcpy and friends take an unsigned size")((!N.isSigned() && "memcpy and friends take an unsigned size"
) ? static_cast<void> (0) : __assert_fail ("!N.isSigned() && \"memcpy and friends take an unsigned size\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8072, __PRETTY_FUNCTION__))
;
8073
8074 // If the size is zero, we treat this as always being a valid no-op.
8075 // (Even if one of the src and dest pointers is null.)
8076 if (!N)
8077 return true;
8078
8079 // Otherwise, if either of the operands is null, we can't proceed. Don't
8080 // try to determine the type of the copied objects, because there aren't
8081 // any.
8082 if (!Src.Base || !Dest.Base) {
8083 APValue Val;
8084 (!Src.Base ? Src : Dest).moveInto(Val);
8085 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8086 << Move << WChar << !!Src.Base
8087 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8088 return false;
8089 }
8090 if (Src.Designator.Invalid || Dest.Designator.Invalid)
8091 return false;
8092
8093 // We require that Src and Dest are both pointers to arrays of
8094 // trivially-copyable type. (For the wide version, the designator will be
8095 // invalid if the designated object is not a wchar_t.)
8096 QualType T = Dest.Designator.getType(Info.Ctx);
8097 QualType SrcT = Src.Designator.getType(Info.Ctx);
8098 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8099 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8100 return false;
8101 }
8102 if (T->isIncompleteType()) {
8103 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8104 return false;
8105 }
8106 if (!T.isTriviallyCopyableType(Info.Ctx)) {
8107 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8108 return false;
8109 }
8110
8111 // Figure out how many T's we're copying.
8112 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8113 if (!WChar) {
8114 uint64_t Remainder;
8115 llvm::APInt OrigN = N;
8116 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8117 if (Remainder) {
8118 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8119 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8120 << (unsigned)TSize;
8121 return false;
8122 }
8123 }
8124
8125 // Check that the copying will remain within the arrays, just so that we
8126 // can give a more meaningful diagnostic. This implicitly also checks that
8127 // N fits into 64 bits.
8128 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8129 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8130 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8131 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8132 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8133 << N.toString(10, /*Signed*/false);
8134 return false;
8135 }
8136 uint64_t NElems = N.getZExtValue();
8137 uint64_t NBytes = NElems * TSize;
8138
8139 // Check for overlap.
8140 int Direction = 1;
8141 if (HasSameBase(Src, Dest)) {
8142 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8143 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8144 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8145 // Dest is inside the source region.
8146 if (!Move) {
8147 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8148 return false;
8149 }
8150 // For memmove and friends, copy backwards.
8151 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8152 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8153 return false;
8154 Direction = -1;
8155 } else if (!Move && SrcOffset >= DestOffset &&
8156 SrcOffset - DestOffset < NBytes) {
8157 // Src is inside the destination region for memcpy: invalid.
8158 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8159 return false;
8160 }
8161 }
8162
8163 while (true) {
8164 APValue Val;
8165 // FIXME: Set WantObjectRepresentation to true if we're copying a
8166 // char-like type?
8167 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8168 !handleAssignment(Info, E, Dest, T, Val))
8169 return false;
8170 // Do not iterate past the last element; if we're copying backwards, that
8171 // might take us off the start of the array.
8172 if (--NElems == 0)
8173 return true;
8174 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8175 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8176 return false;
8177 }
8178 }
8179
8180 default:
8181 return visitNonBuiltinCallExpr(E);
8182 }
8183}
8184
8185static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8186 APValue &Result, const InitListExpr *ILE,
8187 QualType AllocType);
8188
8189bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8190 if (!Info.getLangOpts().CPlusPlus2a)
8191 Info.CCEDiag(E, diag::note_constexpr_new);
8192
8193 // We cannot speculatively evaluate a delete expression.
8194 if (Info.SpeculativeEvaluationDepth)
8195 return false;
8196
8197 FunctionDecl *OperatorNew = E->getOperatorNew();
8198 if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8199 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8200 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8201 return false;
8202 }
8203
8204 bool IsNothrow = false;
8205 if (E->getNumPlacementArgs()) {
8206 // The only new-placement list we support is of the form (std::nothrow).
8207 //
8208 // FIXME: There is no restriction on this, but it's not clear that any
8209 // other form makes any sense. We get here for cases such as:
8210 //
8211 // new (std::align_val_t{N}) X(int)
8212 //
8213 // (which should presumably be valid only if N is a multiple of
8214 // alignof(int), and in any case can't be deallocated unless N is
8215 // alignof(X) and X has new-extended alignment).
8216 if (E->getNumPlacementArgs() != 1 ||
8217 !E->getPlacementArg(0)->getType()->isNothrowT())
8218 return Error(E, diag::note_constexpr_new_placement);
8219
8220 LValue Nothrow;
8221 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8222 return false;
8223 IsNothrow = true;
8224 }
8225
8226 const Expr *Init = E->getInitializer();
8227 const InitListExpr *ResizedArrayILE = nullptr;
8228
8229 QualType AllocType = E->getAllocatedType();
8230 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8231 const Expr *Stripped = *ArraySize;
8232 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8233 Stripped = ICE->getSubExpr())
8234 if (ICE->getCastKind() != CK_NoOp &&
8235 ICE->getCastKind() != CK_IntegralCast)
8236 break;
8237
8238 llvm::APSInt ArrayBound;
8239 if (!EvaluateInteger(Stripped, ArrayBound, Info))
8240 return false;
8241
8242 // C++ [expr.new]p9:
8243 // The expression is erroneous if:
8244 // -- [...] its value before converting to size_t [or] applying the
8245 // second standard conversion sequence is less than zero
8246 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8247 if (IsNothrow)
8248 return ZeroInitialization(E);
8249
8250 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8251 << ArrayBound << (*ArraySize)->getSourceRange();
8252 return false;
8253 }
8254
8255 // -- its value is such that the size of the allocated object would
8256 // exceed the implementation-defined limit
8257 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8258 ArrayBound) >
8259 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8260 if (IsNothrow)
8261 return ZeroInitialization(E);
8262
8263 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8264 << ArrayBound << (*ArraySize)->getSourceRange();
8265 return false;
8266 }
8267
8268 // -- the new-initializer is a braced-init-list and the number of
8269 // array elements for which initializers are provided [...]
8270 // exceeds the number of elements to initialize
8271 if (Init) {
8272 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8273 assert(CAT && "unexpected type for array initializer")((CAT && "unexpected type for array initializer") ? static_cast
<void> (0) : __assert_fail ("CAT && \"unexpected type for array initializer\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8273, __PRETTY_FUNCTION__))
;
8274
8275 unsigned Bits =
8276 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8277 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8278 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8279 if (InitBound.ugt(AllocBound)) {
8280 if (IsNothrow)
8281 return ZeroInitialization(E);
8282
8283 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8284 << AllocBound.toString(10, /*Signed=*/false)
8285 << InitBound.toString(10, /*Signed=*/false)
8286 << (*ArraySize)->getSourceRange();
8287 return false;
8288 }
8289
8290 // If the sizes differ, we must have an initializer list, and we need
8291 // special handling for this case when we initialize.
8292 if (InitBound != AllocBound)
8293 ResizedArrayILE = cast<InitListExpr>(Init);
8294 }
8295
8296 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound,
8297 ArrayType::Normal, 0);
8298 } else {
8299 assert(!AllocType->isArrayType() &&((!AllocType->isArrayType() && "array allocation with non-array new"
) ? static_cast<void> (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8300, __PRETTY_FUNCTION__))
8300 "array allocation with non-array new")((!AllocType->isArrayType() && "array allocation with non-array new"
) ? static_cast<void> (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8300, __PRETTY_FUNCTION__))
;
8301 }
8302
8303 // Perform the allocation and obtain a pointer to the resulting object.
8304 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
8305 if (!Val)
8306 return false;
8307
8308 if (ResizedArrayILE) {
8309 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8310 AllocType))
8311 return false;
8312 } else if (Init) {
8313 if (!EvaluateInPlace(*Val, Info, Result, Init))
8314 return false;
8315 } else {
8316 *Val = getDefaultInitValue(AllocType);
8317 }
8318
8319 // Array new returns a pointer to the first element, not a pointer to the
8320 // array.
8321 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8322 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8323
8324 return true;
8325}
8326//===----------------------------------------------------------------------===//
8327// Member Pointer Evaluation
8328//===----------------------------------------------------------------------===//
8329
8330namespace {
8331class MemberPointerExprEvaluator
8332 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8333 MemberPtr &Result;
8334
8335 bool Success(const ValueDecl *D) {
8336 Result = MemberPtr(D);
8337 return true;
8338 }
8339public:
8340
8341 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8342 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8343
8344 bool Success(const APValue &V, const Expr *E) {
8345 Result.setFrom(V);
8346 return true;
8347 }
8348 bool ZeroInitialization(const Expr *E) {
8349 return Success((const ValueDecl*)nullptr);
8350 }
8351
8352 bool VisitCastExpr(const CastExpr *E);
8353 bool VisitUnaryAddrOf(const UnaryOperator *E);
8354};
8355} // end anonymous namespace
8356
8357static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8358 EvalInfo &Info) {
8359 assert(E->isRValue() && E->getType()->isMemberPointerType())((E->isRValue() && E->getType()->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8359, __PRETTY_FUNCTION__))
;
8360 return MemberPointerExprEvaluator(Info, Result).Visit(E);
8361}
8362
8363bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8364 switch (E->getCastKind()) {
8365 default:
8366 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8367
8368 case CK_NullToMemberPointer:
8369 VisitIgnoredValue(E->getSubExpr());
8370 return ZeroInitialization(E);
8371
8372 case CK_BaseToDerivedMemberPointer: {
8373 if (!Visit(E->getSubExpr()))
8374 return false;
8375 if (E->path_empty())
8376 return true;
8377 // Base-to-derived member pointer casts store the path in derived-to-base
8378 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8379 // the wrong end of the derived->base arc, so stagger the path by one class.
8380 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8381 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8382 PathI != PathE; ++PathI) {
8383 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase"
) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8383, __PRETTY_FUNCTION__))
;
8384 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8385 if (!Result.castToDerived(Derived))
8386 return Error(E);
8387 }
8388 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8389 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8390 return Error(E);
8391 return true;
8392 }
8393
8394 case CK_DerivedToBaseMemberPointer:
8395 if (!Visit(E->getSubExpr()))
8396 return false;
8397 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8398 PathE = E->path_end(); PathI != PathE; ++PathI) {
8399 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase"
) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8399, __PRETTY_FUNCTION__))
;
8400 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8401 if (!Result.castToBase(Base))
8402 return Error(E);
8403 }
8404 return true;
8405 }
8406}
8407
8408bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8409 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8410 // member can be formed.
8411 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8412}
8413
8414//===----------------------------------------------------------------------===//
8415// Record Evaluation
8416//===----------------------------------------------------------------------===//
8417
8418namespace {
8419 class RecordExprEvaluator
8420 : public ExprEvaluatorBase<RecordExprEvaluator> {
8421 const LValue &This;
8422 APValue &Result;
8423 public:
8424
8425 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8426 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8427
8428 bool Success(const APValue &V, const Expr *E) {
8429 Result = V;
8430 return true;
8431 }
8432 bool ZeroInitialization(const Expr *E) {
8433 return ZeroInitialization(E, E->getType());
8434 }
8435 bool ZeroInitialization(const Expr *E, QualType T);
8436
8437 bool VisitCallExpr(const CallExpr *E) {
8438 return handleCallExpr(E, Result, &This);
8439 }
8440 bool VisitCastExpr(const CastExpr *E);
8441 bool VisitInitListExpr(const InitListExpr *E);
8442 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8443 return VisitCXXConstructExpr(E, E->getType());
8444 }
8445 bool VisitLambdaExpr(const LambdaExpr *E);
8446 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
8447 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
8448 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
8449
8450 // Temporaries are registered when created, so we don't care about
8451 // CXXBindTemporaryExpr.
8452 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8453 return Visit(E->getSubExpr());
8454 }
8455
8456 bool VisitBinCmp(const BinaryOperator *E);
8457 };
8458}
8459
8460/// Perform zero-initialization on an object of non-union class type.
8461/// C++11 [dcl.init]p5:
8462/// To zero-initialize an object or reference of type T means:
8463/// [...]
8464/// -- if T is a (possibly cv-qualified) non-union class type,
8465/// each non-static data member and each base-class subobject is
8466/// zero-initialized
8467static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8468 const RecordDecl *RD,
8469 const LValue &This, APValue &Result) {
8470 assert(!RD->isUnion() && "Expected non-union class type")((!RD->isUnion() && "Expected non-union class type"
) ? static_cast<void> (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8470, __PRETTY_FUNCTION__))
;
8471 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8472 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
8473 std::distance(RD->field_begin(), RD->field_end()));
8474
8475 if (RD->isInvalidDecl()) return false;
8476 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8477
8478 if (CD) {
8479 unsigned Index = 0;
8480 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
8481 End = CD->bases_end(); I != End; ++I, ++Index) {
8482 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8483 LValue Subobject = This;
8484 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8485 return false;
8486 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
8487 Result.getStructBase(Index)))
8488 return false;
8489 }
8490 }
8491
8492 for (const auto *I : RD->fields()) {
8493 // -- if T is a reference type, no initialization is performed.
8494 if (I->getType()->isReferenceType())
8495 continue;
8496
8497 LValue Subobject = This;
8498 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
8499 return false;
8500
8501 ImplicitValueInitExpr VIE(I->getType());
8502 if (!EvaluateInPlace(
8503 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
8504 return false;
8505 }
8506
8507 return true;
8508}
8509
8510bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8511 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
8512 if (RD->isInvalidDecl()) return false;
8513 if (RD->isUnion()) {
8514 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8515 // object's first non-static named data member is zero-initialized
8516 RecordDecl::field_iterator I = RD->field_begin();
8517 if (I == RD->field_end()) {
8518 Result = APValue((const FieldDecl*)nullptr);
8519 return true;
8520 }
8521
8522 LValue Subobject = This;
8523 if (!HandleLValueMember(Info, E, Subobject, *I))
8524 return false;
8525 Result = APValue(*I);
8526 ImplicitValueInitExpr VIE(I->getType());
8527 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
8528 }
8529
8530 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
8531 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
8532 return false;
8533 }
8534
8535 return HandleClassZeroInitialization(Info, E, RD, This, Result);
8536}
8537
8538bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8539 switch (E->getCastKind()) {
8540 default:
8541 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8542
8543 case CK_ConstructorConversion:
8544 return Visit(E->getSubExpr());
8545
8546 case CK_DerivedToBase:
8547 case CK_UncheckedDerivedToBase: {
8548 APValue DerivedObject;
8549 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
8550 return false;
8551 if (!DerivedObject.isStruct())
8552 return Error(E->getSubExpr());
8553
8554 // Derived-to-base rvalue conversion: just slice off the derived part.
8555 APValue *Value = &DerivedObject;
8556 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8557 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8558 PathE = E->path_end(); PathI != PathE; ++PathI) {
8559 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")((!(*PathI)->isVirtual() && "record rvalue with virtual base"
) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"record rvalue with virtual base\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8559, __PRETTY_FUNCTION__))
;
8560 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8561 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8562 RD = Base;
8563 }
8564 Result = *Value;
8565 return true;
8566 }
8567 }
8568}
8569
8570bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8571 if (E->isTransparent())
8572 return Visit(E->getInit(0));
8573
8574 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
8575 if (RD->isInvalidDecl()) return false;
8576 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8577 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8578
8579 EvalInfo::EvaluatingConstructorRAII EvalObj(
8580 Info,
8581 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8582 CXXRD && CXXRD->getNumBases());
8583
8584 if (RD->isUnion()) {
8585 const FieldDecl *Field = E->getInitializedFieldInUnion();
8586 Result = APValue(Field);
8587 if (!Field)
8588 return true;
8589
8590 // If the initializer list for a union does not contain any elements, the
8591 // first element of the union is value-initialized.
8592 // FIXME: The element should be initialized from an initializer list.
8593 // Is this difference ever observable for initializer lists which
8594 // we don't build?
8595 ImplicitValueInitExpr VIE(Field->getType());
8596 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8597
8598 LValue Subobject = This;
8599 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8600 return false;
8601
8602 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8603 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8604 isa<CXXDefaultInitExpr>(InitExpr));
8605
8606 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
8607 }
8608
8609 if (!Result.hasValue())
8610 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8611 std::distance(RD->field_begin(), RD->field_end()));
8612 unsigned ElementNo = 0;
8613 bool Success = true;
8614
8615 // Initialize base classes.
8616 if (CXXRD && CXXRD->getNumBases()) {
8617 for (const auto &Base : CXXRD->bases()) {
8618 assert(ElementNo < E->getNumInits() && "missing init for base class")((ElementNo < E->getNumInits() && "missing init for base class"
) ? static_cast<void> (0) : __assert_fail ("ElementNo < E->getNumInits() && \"missing init for base class\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8618, __PRETTY_FUNCTION__))
;
8619 const Expr *Init = E->getInit(ElementNo);
8620
8621 LValue Subobject = This;
8622 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8623 return false;
8624
8625 APValue &FieldVal = Result.getStructBase(ElementNo);
8626 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
8627 if (!Info.noteFailure())
8628 return false;
8629 Success = false;
8630 }
8631 ++ElementNo;
8632 }
8633
8634 EvalObj.finishedConstructingBases();
8635 }
8636
8637 // Initialize members.
8638 for (const auto *Field : RD->fields()) {
8639 // Anonymous bit-fields are not considered members of the class for
8640 // purposes of aggregate initialization.
8641 if (Field->isUnnamedBitfield())
8642 continue;
8643
8644 LValue Subobject = This;
8645
8646 bool HaveInit = ElementNo < E->getNumInits();
8647
8648 // FIXME: Diagnostics here should point to the end of the initializer
8649 // list, not the start.
8650 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
8651 Subobject, Field, &Layout))
8652 return false;
8653
8654 // Perform an implicit value-initialization for members beyond the end of
8655 // the initializer list.
8656 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
8657 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
8658
8659 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8660 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8661 isa<CXXDefaultInitExpr>(Init));
8662
8663 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8664 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8665 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
8666 FieldVal, Field))) {
8667 if (!Info.noteFailure())
8668 return false;
8669 Success = false;
8670 }
8671 }
8672
8673 return Success;
8674}
8675
8676bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8677 QualType T) {
8678 // Note that E's type is not necessarily the type of our class here; we might
8679 // be initializing an array element instead.
8680 const CXXConstructorDecl *FD = E->getConstructor();
8681 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8682
8683 bool ZeroInit = E->requiresZeroInitialization();
8684 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
8685 // If we've already performed zero-initialization, we're already done.
8686 if (Result.hasValue())
8687 return true;
8688
8689 if (ZeroInit)
8690 return ZeroInitialization(E, T);
8691
8692 Result = getDefaultInitValue(T);
8693 return true;
8694 }
8695
8696 const FunctionDecl *Definition = nullptr;
8697 auto Body = FD->getBody(Definition);
8698
8699 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8700 return false;
8701
8702 // Avoid materializing a temporary for an elidable copy/move constructor.
8703 if (E->isElidable() && !ZeroInit)
8704 if (const MaterializeTemporaryExpr *ME
8705 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8706 return Visit(ME->GetTemporaryExpr());
8707
8708 if (ZeroInit && !ZeroInitialization(E, T))
8709 return false;
8710
8711 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
8712 return HandleConstructorCall(E, This, Args,
8713 cast<CXXConstructorDecl>(Definition), Info,
8714 Result);
8715}
8716
8717bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8718 const CXXInheritedCtorInitExpr *E) {
8719 if (!Info.CurrentCall) {
8720 assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast<
void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8720, __PRETTY_FUNCTION__))
;
8721 return false;
8722 }
8723
8724 const CXXConstructorDecl *FD = E->getConstructor();
8725 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8726 return false;
8727
8728 const FunctionDecl *Definition = nullptr;
8729 auto Body = FD->getBody(Definition);
8730
8731 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8732 return false;
8733
8734 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
8735 cast<CXXConstructorDecl>(Definition), Info,
8736 Result);
8737}
8738
8739bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8740 const CXXStdInitializerListExpr *E) {
8741 const ConstantArrayType *ArrayType =
8742 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8743
8744 LValue Array;
8745 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8746 return false;
8747
8748 // Get a pointer to the first element of the array.
8749 Array.addArray(Info, E, ArrayType);
8750
8751 // FIXME: Perform the checks on the field types in SemaInit.
8752 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8753 RecordDecl::field_iterator Field = Record->field_begin();
8754 if (Field == Record->field_end())
8755 return Error(E);
8756
8757 // Start pointer.
8758 if (!Field->getType()->isPointerType() ||
8759 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8760 ArrayType->getElementType()))
8761 return Error(E);
8762
8763 // FIXME: What if the initializer_list type has base classes, etc?
8764 Result = APValue(APValue::UninitStruct(), 0, 2);
8765 Array.moveInto(Result.getStructField(0));
8766
8767 if (++Field == Record->field_end())
8768 return Error(E);
8769
8770 if (Field->getType()->isPointerType() &&
8771 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8772 ArrayType->getElementType())) {
8773 // End pointer.
8774 if (!HandleLValueArrayAdjustment(Info, E, Array,
8775 ArrayType->getElementType(),
8776 ArrayType->getSize().getZExtValue()))
8777 return false;
8778 Array.moveInto(Result.getStructField(1));
8779 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8780 // Length.
8781 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8782 else
8783 return Error(E);
8784
8785 if (++Field != Record->field_end())
8786 return Error(E);
8787
8788 return true;
8789}
8790
8791bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8792 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8793 if (ClosureClass->isInvalidDecl())
8794 return false;
8795
8796 const size_t NumFields =
8797 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
8798
8799 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8802, __PRETTY_FUNCTION__))
8800 E->capture_init_end()) &&((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8802, __PRETTY_FUNCTION__))
8801 "The number of lambda capture initializers should equal the number of "((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8802, __PRETTY_FUNCTION__))
8802 "fields within the closure type")((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8802, __PRETTY_FUNCTION__))
;
8803
8804 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8805 // Iterate through all the lambda's closure object's fields and initialize
8806 // them.
8807 auto *CaptureInitIt = E->capture_init_begin();
8808 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8809 bool Success = true;
8810 for (const auto *Field : ClosureClass->fields()) {
8811 assert(CaptureInitIt != E->capture_init_end())((CaptureInitIt != E->capture_init_end()) ? static_cast<
void> (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8811, __PRETTY_FUNCTION__))
;
8812 // Get the initializer for this field
8813 Expr *const CurFieldInit = *CaptureInitIt++;
8814
8815 // If there is no initializer, either this is a VLA or an error has
8816 // occurred.
8817 if (!CurFieldInit)
8818 return Error(E);
8819
8820 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8821 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8822 if (!Info.keepEvaluatingAfterFailure())
8823 return false;
8824 Success = false;
8825 }
8826 ++CaptureIt;
8827 }
8828 return Success;
8829}
8830
8831static bool EvaluateRecord(const Expr *E, const LValue &This,
8832 APValue &Result, EvalInfo &Info) {
8833 assert(E->isRValue() && E->getType()->isRecordType() &&((E->isRValue() && E->getType()->isRecordType
() && "can't evaluate expression as a record rvalue")
? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8834, __PRETTY_FUNCTION__))
8834 "can't evaluate expression as a record rvalue")((E->isRValue() && E->getType()->isRecordType
() && "can't evaluate expression as a record rvalue")
? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8834, __PRETTY_FUNCTION__))
;
8835 return RecordExprEvaluator(Info, This, Result).Visit(E);
8836}
8837
8838//===----------------------------------------------------------------------===//
8839// Temporary Evaluation
8840//
8841// Temporaries are represented in the AST as rvalues, but generally behave like
8842// lvalues. The full-object of which the temporary is a subobject is implicitly
8843// materialized so that a reference can bind to it.
8844//===----------------------------------------------------------------------===//
8845namespace {
8846class TemporaryExprEvaluator
8847 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8848public:
8849 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
8850 LValueExprEvaluatorBaseTy(Info, Result, false) {}
8851
8852 /// Visit an expression which constructs the value of this temporary.
8853 bool VisitConstructExpr(const Expr *E) {
8854 APValue &Value =
8855 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
8856 return EvaluateInPlace(Value, Info, Result, E);
8857 }
8858
8859 bool VisitCastExpr(const CastExpr *E) {
8860 switch (E->getCastKind()) {
8861 default:
8862 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8863
8864 case CK_ConstructorConversion:
8865 return VisitConstructExpr(E->getSubExpr());
8866 }
8867 }
8868 bool VisitInitListExpr(const InitListExpr *E) {
8869 return VisitConstructExpr(E);
8870 }
8871 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8872 return VisitConstructExpr(E);
8873 }
8874 bool VisitCallExpr(const CallExpr *E) {
8875 return VisitConstructExpr(E);
8876 }
8877 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8878 return VisitConstructExpr(E);
8879 }
8880 bool VisitLambdaExpr(const LambdaExpr *E) {
8881 return VisitConstructExpr(E);
8882 }
8883};
8884} // end anonymous namespace
8885
8886/// Evaluate an expression of record type as a temporary.
8887static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
8888 assert(E->isRValue() && E->getType()->isRecordType())((E->isRValue() && E->getType()->isRecordType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8888, __PRETTY_FUNCTION__))
;
8889 return TemporaryExprEvaluator(Info, Result).Visit(E);
8890}
8891
8892//===----------------------------------------------------------------------===//
8893// Vector Evaluation
8894//===----------------------------------------------------------------------===//
8895
8896namespace {
8897 class VectorExprEvaluator
8898 : public ExprEvaluatorBase<VectorExprEvaluator> {
8899 APValue &Result;
8900 public:
8901
8902 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8903 : ExprEvaluatorBaseTy(info), Result(Result) {}
8904
8905 bool Success(ArrayRef<APValue> V, const Expr *E) {
8906 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())((V.size() == E->getType()->castAs<VectorType>()->
getNumElements()) ? static_cast<void> (0) : __assert_fail
("V.size() == E->getType()->castAs<VectorType>()->getNumElements()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8906, __PRETTY_FUNCTION__))
;
8907 // FIXME: remove this APValue copy.
8908 Result = APValue(V.data(), V.size());
8909 return true;
8910 }
8911 bool Success(const APValue &V, const Expr *E) {
8912 assert(V.isVector())((V.isVector()) ? static_cast<void> (0) : __assert_fail
("V.isVector()", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8912, __PRETTY_FUNCTION__))
;
8913 Result = V;
8914 return true;
8915 }
8916 bool ZeroInitialization(const Expr *E);
8917
8918 bool VisitUnaryReal(const UnaryOperator *E)
8919 { return Visit(E->getSubExpr()); }
8920 bool VisitCastExpr(const CastExpr* E);
8921 bool VisitInitListExpr(const InitListExpr *E);
8922 bool VisitUnaryImag(const UnaryOperator *E);
8923 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
8924 // binary comparisons, binary and/or/xor,
8925 // shufflevector, ExtVectorElementExpr
8926 };
8927} // end anonymous namespace
8928
8929static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
8930 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue")((E->isRValue() && E->getType()->isVectorType
() &&"not a vector rvalue") ? static_cast<void>
(0) : __assert_fail ("E->isRValue() && E->getType()->isVectorType() &&\"not a vector rvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 8930, __PRETTY_FUNCTION__))
;
8931 return VectorExprEvaluator(Info, Result).Visit(E);
8932}
8933
8934bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
8935 const VectorType *VTy = E->getType()->castAs<VectorType>();
8936 unsigned NElts = VTy->getNumElements();
8937
8938 const Expr *SE = E->getSubExpr();
8939 QualType SETy = SE->getType();
8940
8941 switch (E->getCastKind()) {
8942 case CK_VectorSplat: {
8943 APValue Val = APValue();
8944 if (SETy->isIntegerType()) {
8945 APSInt IntResult;
8946 if (!EvaluateInteger(SE, IntResult, Info))
8947 return false;
8948 Val = APValue(std::move(IntResult));
8949 } else if (SETy->isRealFloatingType()) {
8950 APFloat FloatResult(0.0);
8951 if (!EvaluateFloat(SE, FloatResult, Info))
8952 return false;
8953 Val = APValue(std::move(FloatResult));
8954 } else {
8955 return Error(E);
8956 }
8957
8958 // Splat and create vector APValue.
8959 SmallVector<APValue, 4> Elts(NElts, Val);
8960 return Success(Elts, E);
8961 }
8962 case CK_BitCast: {
8963 // Evaluate the operand into an APInt we can extract from.
8964 llvm::APInt SValInt;
8965 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8966 return false;
8967 // Extract the elements
8968 QualType EltTy = VTy->getElementType();
8969 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8970 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8971 SmallVector<APValue, 4> Elts;
8972 if (EltTy->isRealFloatingType()) {
8973 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
8974 unsigned FloatEltSize = EltSize;
8975 if (&Sem == &APFloat::x87DoubleExtended())
8976 FloatEltSize = 80;
8977 for (unsigned i = 0; i < NElts; i++) {
8978 llvm::APInt Elt;
8979 if (BigEndian)
8980 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8981 else
8982 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
8983 Elts.push_back(APValue(APFloat(Sem, Elt)));
8984 }
8985 } else if (EltTy->isIntegerType()) {
8986 for (unsigned i = 0; i < NElts; i++) {
8987 llvm::APInt Elt;
8988 if (BigEndian)
8989 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8990 else
8991 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8992 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8993 }
8994 } else {
8995 return Error(E);
8996 }
8997 return Success(Elts, E);
8998 }
8999 default:
9000 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9001 }
9002}
9003
9004bool
9005VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9006 const VectorType *VT = E->getType()->castAs<VectorType>();
9007 unsigned NumInits = E->getNumInits();
9008 unsigned NumElements = VT->getNumElements();
9009
9010 QualType EltTy = VT->getElementType();
9011 SmallVector<APValue, 4> Elements;
9012
9013 // The number of initializers can be less than the number of
9014 // vector elements. For OpenCL, this can be due to nested vector
9015 // initialization. For GCC compatibility, missing trailing elements
9016 // should be initialized with zeroes.
9017 unsigned CountInits = 0, CountElts = 0;
9018 while (CountElts < NumElements) {
9019 // Handle nested vector initialization.
9020 if (CountInits < NumInits
9021 && E->getInit(CountInits)->getType()->isVectorType()) {
9022 APValue v;
9023 if (!EvaluateVector(E->getInit(CountInits), v, Info))
9024 return Error(E);
9025 unsigned vlen = v.getVectorLength();
9026 for (unsigned j = 0; j < vlen; j++)
9027 Elements.push_back(v.getVectorElt(j));
9028 CountElts += vlen;
9029 } else if (EltTy->isIntegerType()) {
9030 llvm::APSInt sInt(32);
9031 if (CountInits < NumInits) {
9032 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9033 return false;
9034 } else // trailing integer zero.
9035 sInt = Info.Ctx.MakeIntValue(0, EltTy);
9036 Elements.push_back(APValue(sInt));
9037 CountElts++;
9038 } else {
9039 llvm::APFloat f(0.0);
9040 if (CountInits < NumInits) {
9041 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9042 return false;
9043 } else // trailing float zero.
9044 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9045 Elements.push_back(APValue(f));
9046 CountElts++;
9047 }
9048 CountInits++;
9049 }
9050 return Success(Elements, E);
9051}
9052
9053bool
9054VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9055 const VectorType *VT = E->getType()->getAs<VectorType>();
9056 QualType EltTy = VT->getElementType();
9057 APValue ZeroElement;
9058 if (EltTy->isIntegerType())
9059 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9060 else
9061 ZeroElement =
9062 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9063
9064 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9065 return Success(Elements, E);
9066}
9067
9068bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9069 VisitIgnoredValue(E->getSubExpr());
9070 return ZeroInitialization(E);
9071}
9072
9073//===----------------------------------------------------------------------===//
9074// Array Evaluation
9075//===----------------------------------------------------------------------===//
9076
9077namespace {
9078 class ArrayExprEvaluator
9079 : public ExprEvaluatorBase<ArrayExprEvaluator> {
9080 const LValue &This;
9081 APValue &Result;
9082 public:
9083
9084 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9085 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9086
9087 bool Success(const APValue &V, const Expr *E) {
9088 assert(V.isArray() && "expected array")((V.isArray() && "expected array") ? static_cast<void
> (0) : __assert_fail ("V.isArray() && \"expected array\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9088, __PRETTY_FUNCTION__))
;
9089 Result = V;
9090 return true;
9091 }
9092
9093 bool ZeroInitialization(const Expr *E) {
9094 const ConstantArrayType *CAT =
9095 Info.Ctx.getAsConstantArrayType(E->getType());
9096 if (!CAT)
9097 return Error(E);
9098
9099 Result = APValue(APValue::UninitArray(), 0,
9100 CAT->getSize().getZExtValue());
9101 if (!Result.hasArrayFiller()) return true;
9102
9103 // Zero-initialize all elements.
9104 LValue Subobject = This;
9105 Subobject.addArray(Info, E, CAT);
9106 ImplicitValueInitExpr VIE(CAT->getElementType());
9107 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9108 }
9109
9110 bool VisitCallExpr(const CallExpr *E) {
9111 return handleCallExpr(E, Result, &This);
9112 }
9113 bool VisitInitListExpr(const InitListExpr *E,
9114 QualType AllocType = QualType());
9115 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9116 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9117 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9118 const LValue &Subobject,
9119 APValue *Value, QualType Type);
9120 bool VisitStringLiteral(const StringLiteral *E,
9121 QualType AllocType = QualType()) {
9122 expandStringLiteral(Info, E, Result, AllocType);
9123 return true;
9124 }
9125 };
9126} // end anonymous namespace
9127
9128static bool EvaluateArray(const Expr *E, const LValue &This,
9129 APValue &Result, EvalInfo &Info) {
9130 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue")((E->isRValue() && E->getType()->isArrayType
() && "not an array rvalue") ? static_cast<void>
(0) : __assert_fail ("E->isRValue() && E->getType()->isArrayType() && \"not an array rvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9130, __PRETTY_FUNCTION__))
;
9131 return ArrayExprEvaluator(Info, This, Result).Visit(E);
9132}
9133
9134static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9135 APValue &Result, const InitListExpr *ILE,
9136 QualType AllocType) {
9137 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&((ILE->isRValue() && ILE->getType()->isArrayType
() && "not an array rvalue") ? static_cast<void>
(0) : __assert_fail ("ILE->isRValue() && ILE->getType()->isArrayType() && \"not an array rvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9138, __PRETTY_FUNCTION__))
9138 "not an array rvalue")((ILE->isRValue() && ILE->getType()->isArrayType
() && "not an array rvalue") ? static_cast<void>
(0) : __assert_fail ("ILE->isRValue() && ILE->getType()->isArrayType() && \"not an array rvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9138, __PRETTY_FUNCTION__))
;
9139 return ArrayExprEvaluator(Info, This, Result)
9140 .VisitInitListExpr(ILE, AllocType);
9141}
9142
9143// Return true iff the given array filler may depend on the element index.
9144static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9145 // For now, just whitelist non-class value-initialization and initialization
9146 // lists comprised of them.
9147 if (isa<ImplicitValueInitExpr>(FillerExpr))
9148 return false;
9149 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9150 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9151 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9152 return true;
9153 }
9154 return false;
9155 }
9156 return true;
9157}
9158
9159bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9160 QualType AllocType) {
9161 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9162 AllocType.isNull() ? E->getType() : AllocType);
9163 if (!CAT)
9164 return Error(E);
9165
9166 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9167 // an appropriately-typed string literal enclosed in braces.
9168 if (E->isStringLiteralInit()) {
9169 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9170 // FIXME: Support ObjCEncodeExpr here once we support it in
9171 // ArrayExprEvaluator generally.
9172 if (!SL)
9173 return Error(E);
9174 return VisitStringLiteral(SL, AllocType);
9175 }
9176
9177 bool Success = true;
9178
9179 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(((!Result.isArray() || Result.getArrayInitializedElts() == 0
) && "zero-initialized array shouldn't have any initialized elts"
) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9180, __PRETTY_FUNCTION__))
9180 "zero-initialized array shouldn't have any initialized elts")(((!Result.isArray() || Result.getArrayInitializedElts() == 0
) && "zero-initialized array shouldn't have any initialized elts"
) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9180, __PRETTY_FUNCTION__))
;
9181 APValue Filler;
9182 if (Result.isArray() && Result.hasArrayFiller())
9183 Filler = Result.getArrayFiller();
9184
9185 unsigned NumEltsToInit = E->getNumInits();
9186 unsigned NumElts = CAT->getSize().getZExtValue();
9187 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9188
9189 // If the initializer might depend on the array index, run it for each
9190 // array element.
9191 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9192 NumEltsToInit = NumElts;
9193
9194 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: "
<< NumEltsToInit << ".\n"; } } while (false)
9195 << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: "
<< NumEltsToInit << ".\n"; } } while (false)
;
9196
9197 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9198
9199 // If the array was previously zero-initialized, preserve the
9200 // zero-initialized values.
9201 if (Filler.hasValue()) {
9202 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9203 Result.getArrayInitializedElt(I) = Filler;
9204 if (Result.hasArrayFiller())
9205 Result.getArrayFiller() = Filler;
9206 }
9207
9208 LValue Subobject = This;
9209 Subobject.addArray(Info, E, CAT);
9210 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9211 const Expr *Init =
9212 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9213 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9214 Info, Subobject, Init) ||
9215 !HandleLValueArrayAdjustment(Info, Init, Subobject,
9216 CAT->getElementType(), 1)) {
9217 if (!Info.noteFailure())
9218 return false;
9219 Success = false;
9220 }
9221 }
9222
9223 if (!Result.hasArrayFiller())
9224 return Success;
9225
9226 // If we get here, we have a trivial filler, which we can just evaluate
9227 // once and splat over the rest of the array elements.
9228 assert(FillerExpr && "no array filler for incomplete init list")((FillerExpr && "no array filler for incomplete init list"
) ? static_cast<void> (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9228, __PRETTY_FUNCTION__))
;
9229 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9230 FillerExpr) && Success;
9231}
9232
9233bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9234 LValue CommonLV;
9235 if (E->getCommonExpr() &&
9236 !Evaluate(Info.CurrentCall->createTemporary(
9237 E->getCommonExpr(),
9238 getStorageType(Info.Ctx, E->getCommonExpr()), false,
9239 CommonLV),
9240 Info, E->getCommonExpr()->getSourceExpr()))
9241 return false;
9242
9243 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9244
9245 uint64_t Elements = CAT->getSize().getZExtValue();
9246 Result = APValue(APValue::UninitArray(), Elements, Elements);
9247
9248 LValue Subobject = This;
9249 Subobject.addArray(Info, E, CAT);
9250
9251 bool Success = true;
9252 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9253 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9254 Info, Subobject, E->getSubExpr()) ||
9255 !HandleLValueArrayAdjustment(Info, E, Subobject,
9256 CAT->getElementType(), 1)) {
9257 if (!Info.noteFailure())
9258 return false;
9259 Success = false;
9260 }
9261 }
9262
9263 return Success;
9264}
9265
9266bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9267 return VisitCXXConstructExpr(E, This, &Result, E->getType());
9268}
9269
9270bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9271 const LValue &Subobject,
9272 APValue *Value,
9273 QualType Type) {
9274 bool HadZeroInit = Value->hasValue();
9275
9276 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9277 unsigned N = CAT->getSize().getZExtValue();
9278
9279 // Preserve the array filler if we had prior zero-initialization.
9280 APValue Filler =
9281 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9282 : APValue();
9283
9284 *Value = APValue(APValue::UninitArray(), N, N);
9285
9286 if (HadZeroInit)
9287 for (unsigned I = 0; I != N; ++I)
9288 Value->getArrayInitializedElt(I) = Filler;
9289
9290 // Initialize the elements.
9291 LValue ArrayElt = Subobject;
9292 ArrayElt.addArray(Info, E, CAT);
9293 for (unsigned I = 0; I != N; ++I)
9294 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9295 CAT->getElementType()) ||
9296 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9297 CAT->getElementType(), 1))
9298 return false;
9299
9300 return true;
9301 }
9302
9303 if (!Type->isRecordType())
9304 return Error(E);
9305
9306 return RecordExprEvaluator(Info, Subobject, *Value)
9307 .VisitCXXConstructExpr(E, Type);
9308}
9309
9310//===----------------------------------------------------------------------===//
9311// Integer Evaluation
9312//
9313// As a GNU extension, we support casting pointers to sufficiently-wide integer
9314// types and back in constant folding. Integer values are thus represented
9315// either as an integer-valued APValue, or as an lvalue-valued APValue.
9316//===----------------------------------------------------------------------===//
9317
9318namespace {
9319class IntExprEvaluator
9320 : public ExprEvaluatorBase<IntExprEvaluator> {
9321 APValue &Result;
9322public:
9323 IntExprEvaluator(EvalInfo &info, APValue &result)
9324 : ExprEvaluatorBaseTy(info), Result(result) {}
9325
9326 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9327 assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9328, __PRETTY_FUNCTION__))
9328 "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9328, __PRETTY_FUNCTION__))
;
9329 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType
() && "Invalid evaluation result.") ? static_cast<
void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9330, __PRETTY_FUNCTION__))
9330 "Invalid evaluation result.")((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType
() && "Invalid evaluation result.") ? static_cast<
void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9330, __PRETTY_FUNCTION__))
;
9331 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9332, __PRETTY_FUNCTION__))
9332 "Invalid evaluation result.")((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9332, __PRETTY_FUNCTION__))
;
9333 Result = APValue(SI);
9334 return true;
9335 }
9336 bool Success(const llvm::APSInt &SI, const Expr *E) {
9337 return Success(SI, E, Result);
9338 }
9339
9340 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9341 assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9342, __PRETTY_FUNCTION__))
9342 "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9342, __PRETTY_FUNCTION__))
;
9343 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9344, __PRETTY_FUNCTION__))
9344 "Invalid evaluation result.")((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9344, __PRETTY_FUNCTION__))
;
9345 Result = APValue(APSInt(I));
9346 Result.getInt().setIsUnsigned(
9347 E->getType()->isUnsignedIntegerOrEnumerationType());
9348 return true;
9349 }
9350 bool Success(const llvm::APInt &I, const Expr *E) {
9351 return Success(I, E, Result);
9352 }
9353
9354 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9355 assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9356, __PRETTY_FUNCTION__))
9356 "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9356, __PRETTY_FUNCTION__))
;
9357 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9358 return true;
9359 }
9360 bool Success(uint64_t Value, const Expr *E) {
9361 return Success(Value, E, Result);
9362 }
9363
9364 bool Success(CharUnits Size, const Expr *E) {
9365 return Success(Size.getQuantity(), E);
9366 }
9367
9368 bool Success(const APValue &V, const Expr *E) {
9369 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9370 Result = V;
9371 return true;
9372 }
9373 return Success(V.getInt(), E);
9374 }
9375
9376 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9377
9378 //===--------------------------------------------------------------------===//
9379 // Visitor Methods
9380 //===--------------------------------------------------------------------===//
9381
9382 bool VisitConstantExpr(const ConstantExpr *E);
9383
9384 bool VisitIntegerLiteral(const IntegerLiteral *E) {
9385 return Success(E->getValue(), E);
9386 }
9387 bool VisitCharacterLiteral(const CharacterLiteral *E) {
9388 return Success(E->getValue(), E);
9389 }
9390
9391 bool CheckReferencedDecl(const Expr *E, const Decl *D);
9392 bool VisitDeclRefExpr(const DeclRefExpr *E) {
9393 if (CheckReferencedDecl(E, E->getDecl()))
9394 return true;
9395
9396 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9397 }
9398 bool VisitMemberExpr(const MemberExpr *E) {
9399 if (CheckReferencedDecl(E, E->getMemberDecl())) {
9400 VisitIgnoredBaseExpression(E->getBase());
9401 return true;
9402 }
9403
9404 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9405 }
9406
9407 bool VisitCallExpr(const CallExpr *E);
9408 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9409 bool VisitBinaryOperator(const BinaryOperator *E);
9410 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9411 bool VisitUnaryOperator(const UnaryOperator *E);
9412
9413 bool VisitCastExpr(const CastExpr* E);
9414 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9415
9416 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9417 return Success(E->getValue(), E);
9418 }
9419
9420 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9421 return Success(E->getValue(), E);
9422 }
9423
9424 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9425 if (Info.ArrayInitIndex == uint64_t(-1)) {
9426 // We were asked to evaluate this subexpression independent of the
9427 // enclosing ArrayInitLoopExpr. We can't do that.
9428 Info.FFDiag(E);
9429 return false;
9430 }
9431 return Success(Info.ArrayInitIndex, E);
9432 }
9433
9434 // Note, GNU defines __null as an integer, not a pointer.
9435 bool VisitGNUNullExpr(const GNUNullExpr *E) {
9436 return ZeroInitialization(E);
9437 }
9438
9439 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9440 return Success(E->getValue(), E);
9441 }
9442
9443 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9444 return Success(E->getValue(), E);
9445 }
9446
9447 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9448 return Success(E->getValue(), E);
9449 }
9450
9451 bool VisitUnaryReal(const UnaryOperator *E);
9452 bool VisitUnaryImag(const UnaryOperator *E);
9453
9454 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
9455 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
9456 bool VisitSourceLocExpr(const SourceLocExpr *E);
9457 // FIXME: Missing: array subscript of vector, member of vector
9458};
9459
9460class FixedPointExprEvaluator
9461 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9462 APValue &Result;
9463
9464 public:
9465 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9466 : ExprEvaluatorBaseTy(info), Result(result) {}
9467
9468 bool Success(const llvm::APInt &I, const Expr *E) {
9469 return Success(
9470 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9471 }
9472
9473 bool Success(uint64_t Value, const Expr *E) {
9474 return Success(
9475 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9476 }
9477
9478 bool Success(const APValue &V, const Expr *E) {
9479 return Success(V.getFixedPoint(), E);
9480 }
9481
9482 bool Success(const APFixedPoint &V, const Expr *E) {
9483 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.")((E->getType()->isFixedPointType() && "Invalid evaluation result."
) ? static_cast<void> (0) : __assert_fail ("E->getType()->isFixedPointType() && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9483, __PRETTY_FUNCTION__))
;
9484 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&((V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9485, __PRETTY_FUNCTION__))
9485 "Invalid evaluation result.")((V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9485, __PRETTY_FUNCTION__))
;
9486 Result = APValue(V);
9487 return true;
9488 }
9489
9490 //===--------------------------------------------------------------------===//
9491 // Visitor Methods
9492 //===--------------------------------------------------------------------===//
9493
9494 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9495 return Success(E->getValue(), E);
9496 }
9497
9498 bool VisitCastExpr(const CastExpr *E);
9499 bool VisitUnaryOperator(const UnaryOperator *E);
9500 bool VisitBinaryOperator(const BinaryOperator *E);
9501};
9502} // end anonymous namespace
9503
9504/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9505/// produce either the integer value or a pointer.
9506///
9507/// GCC has a heinous extension which folds casts between pointer types and
9508/// pointer-sized integral types. We support this by allowing the evaluation of
9509/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9510/// Some simple arithmetic on such values is supported (they are treated much
9511/// like char*).
9512static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
9513 EvalInfo &Info) {
9514 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType())((E->isRValue() && E->getType()->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9514, __PRETTY_FUNCTION__))
;
9515 return IntExprEvaluator(Info, Result).Visit(E);
9516}
9517
9518static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
9519 APValue Val;
9520 if (!EvaluateIntegerOrLValue(E, Val, Info))
9521 return false;
9522 if (!Val.isInt()) {
9523 // FIXME: It would be better to produce the diagnostic for casting
9524 // a pointer to an integer.
9525 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9526 return false;
9527 }
9528 Result = Val.getInt();
9529 return true;
9530}
9531
9532bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9533 APValue Evaluated = E->EvaluateInContext(
9534 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9535 return Success(Evaluated, E);
9536}
9537
9538static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9539 EvalInfo &Info) {
9540 if (E->getType()->isFixedPointType()) {
9541 APValue Val;
9542 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9543 return false;
9544 if (!Val.isFixedPoint())
9545 return false;
9546
9547 Result = Val.getFixedPoint();
9548 return true;
9549 }
9550 return false;
9551}
9552
9553static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9554 EvalInfo &Info) {
9555 if (E->getType()->isIntegerType()) {
9556 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9557 APSInt Val;
9558 if (!EvaluateInteger(E, Val, Info))
9559 return false;
9560 Result = APFixedPoint(Val, FXSema);
9561 return true;
9562 } else if (E->getType()->isFixedPointType()) {
9563 return EvaluateFixedPoint(E, Result, Info);
9564 }
9565 return false;
9566}
9567
9568/// Check whether the given declaration can be directly converted to an integral
9569/// rvalue. If not, no diagnostic is produced; there are other things we can
9570/// try.
9571bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
9572 // Enums are integer constant exprs.
9573 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
9574 // Check for signedness/width mismatches between E type and ECD value.
9575 bool SameSign = (ECD->getInitVal().isSigned()
9576 == E->getType()->isSignedIntegerOrEnumerationType());
9577 bool SameWidth = (ECD->getInitVal().getBitWidth()
9578 == Info.Ctx.getIntWidth(E->getType()));
9579 if (SameSign && SameWidth)
9580 return Success(ECD->getInitVal(), E);
9581 else {
9582 // Get rid of mismatch (otherwise Success assertions will fail)
9583 // by computing a new value matching the type of E.
9584 llvm::APSInt Val = ECD->getInitVal();
9585 if (!SameSign)
9586 Val.setIsSigned(!ECD->getInitVal().isSigned());
9587 if (!SameWidth)
9588 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9589 return Success(Val, E);
9590 }
9591 }
9592 return false;
9593}
9594
9595/// Values returned by __builtin_classify_type, chosen to match the values
9596/// produced by GCC's builtin.
9597enum class GCCTypeClass {
9598 None = -1,
9599 Void = 0,
9600 Integer = 1,
9601 // GCC reserves 2 for character types, but instead classifies them as
9602 // integers.
9603 Enum = 3,
9604 Bool = 4,
9605 Pointer = 5,
9606 // GCC reserves 6 for references, but appears to never use it (because
9607 // expressions never have reference type, presumably).
9608 PointerToDataMember = 7,
9609 RealFloat = 8,
9610 Complex = 9,
9611 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9612 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9613 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9614 // uses 12 for that purpose, same as for a class or struct. Maybe it
9615 // internally implements a pointer to member as a struct? Who knows.
9616 PointerToMemberFunction = 12, // Not a bug, see above.
9617 ClassOrStruct = 12,
9618 Union = 13,
9619 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9620 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9621 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9622 // literals.
9623};
9624
9625/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9626/// as GCC.
9627static GCCTypeClass
9628EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9629 assert(!T->isDependentType() && "unexpected dependent type")((!T->isDependentType() && "unexpected dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"unexpected dependent type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9629, __PRETTY_FUNCTION__))
;
9630
9631 QualType CanTy = T.getCanonicalType();
9632 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9633
9634 switch (CanTy->getTypeClass()) {
9635#define TYPE(ID, BASE)
9636#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9637#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9638#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
9639#include "clang/AST/TypeNodes.def"
9640 case Type::Auto:
9641 case Type::DeducedTemplateSpecialization:
9642 llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9642)
;
9643
9644 case Type::Builtin:
9645 switch (BT->getKind()) {
9646#define BUILTIN_TYPE(ID, SINGLETON_ID)
9647#define SIGNED_TYPE(ID, SINGLETON_ID) \
9648 case BuiltinType::ID: return GCCTypeClass::Integer;
9649#define FLOATING_TYPE(ID, SINGLETON_ID) \
9650 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9651#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9652 case BuiltinType::ID: break;
9653#include "clang/AST/BuiltinTypes.def"
9654 case BuiltinType::Void:
9655 return GCCTypeClass::Void;
9656
9657 case BuiltinType::Bool:
9658 return GCCTypeClass::Bool;
9659
9660 case BuiltinType::Char_U:
9661 case BuiltinType::UChar:
9662 case BuiltinType::WChar_U:
9663 case BuiltinType::Char8:
9664 case BuiltinType::Char16:
9665 case BuiltinType::Char32:
9666 case BuiltinType::UShort:
9667 case BuiltinType::UInt:
9668 case BuiltinType::ULong:
9669 case BuiltinType::ULongLong:
9670 case BuiltinType::UInt128:
9671 return GCCTypeClass::Integer;
9672
9673 case BuiltinType::UShortAccum:
9674 case BuiltinType::UAccum:
9675 case BuiltinType::ULongAccum:
9676 case BuiltinType::UShortFract:
9677 case BuiltinType::UFract:
9678 case BuiltinType::ULongFract:
9679 case BuiltinType::SatUShortAccum:
9680 case BuiltinType::SatUAccum:
9681 case BuiltinType::SatULongAccum:
9682 case BuiltinType::SatUShortFract:
9683 case BuiltinType::SatUFract:
9684 case BuiltinType::SatULongFract:
9685 return GCCTypeClass::None;
9686
9687 case BuiltinType::NullPtr:
9688
9689 case BuiltinType::ObjCId:
9690 case BuiltinType::ObjCClass:
9691 case BuiltinType::ObjCSel:
9692#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9693 case BuiltinType::Id:
9694#include "clang/Basic/OpenCLImageTypes.def"
9695#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9696 case BuiltinType::Id:
9697#include "clang/Basic/OpenCLExtensionTypes.def"
9698 case BuiltinType::OCLSampler:
9699 case BuiltinType::OCLEvent:
9700 case BuiltinType::OCLClkEvent:
9701 case BuiltinType::OCLQueue:
9702 case BuiltinType::OCLReserveID:
9703#define SVE_TYPE(Name, Id, SingletonId) \
9704 case BuiltinType::Id:
9705#include "clang/Basic/AArch64SVEACLETypes.def"
9706 return GCCTypeClass::None;
9707
9708 case BuiltinType::Dependent:
9709 llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9709)
;
9710 };
9711 llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9711)
;
9712
9713 case Type::Enum:
9714 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
9715
9716 case Type::Pointer:
9717 case Type::ConstantArray:
9718 case Type::VariableArray:
9719 case Type::IncompleteArray:
9720 case Type::FunctionNoProto:
9721 case Type::FunctionProto:
9722 return GCCTypeClass::Pointer;
9723
9724 case Type::MemberPointer:
9725 return CanTy->isMemberDataPointerType()
9726 ? GCCTypeClass::PointerToDataMember
9727 : GCCTypeClass::PointerToMemberFunction;
9728
9729 case Type::Complex:
9730 return GCCTypeClass::Complex;
9731
9732 case Type::Record:
9733 return CanTy->isUnionType() ? GCCTypeClass::Union
9734 : GCCTypeClass::ClassOrStruct;
9735
9736 case Type::Atomic:
9737 // GCC classifies _Atomic T the same as T.
9738 return EvaluateBuiltinClassifyType(
9739 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
9740
9741 case Type::BlockPointer:
9742 case Type::Vector:
9743 case Type::ExtVector:
9744 case Type::ObjCObject:
9745 case Type::ObjCInterface:
9746 case Type::ObjCObjectPointer:
9747 case Type::Pipe:
9748 // GCC classifies vectors as None. We follow its lead and classify all
9749 // other types that don't fit into the regular classification the same way.
9750 return GCCTypeClass::None;
9751
9752 case Type::LValueReference:
9753 case Type::RValueReference:
9754 llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9754)
;
9755 }
9756
9757 llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9757)
;
9758}
9759
9760/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9761/// as GCC.
9762static GCCTypeClass
9763EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9764 // If no argument was supplied, default to None. This isn't
9765 // ideal, however it is what gcc does.
9766 if (E->getNumArgs() == 0)
9767 return GCCTypeClass::None;
9768
9769 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9770 // being an ICE, but still folds it to a constant using the type of the first
9771 // argument.
9772 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
9773}
9774
9775/// EvaluateBuiltinConstantPForLValue - Determine the result of
9776/// __builtin_constant_p when applied to the given pointer.
9777///
9778/// A pointer is only "constant" if it is null (or a pointer cast to integer)
9779/// or it points to the first character of a string literal.
9780static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9781 APValue::LValueBase Base = LV.getLValueBase();
9782 if (Base.isNull()) {
9783 // A null base is acceptable.
9784 return true;
9785 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9786 if (!isa<StringLiteral>(E))
9787 return false;
9788 return LV.getLValueOffset().isZero();
9789 } else if (Base.is<TypeInfoLValue>()) {
9790 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9791 // evaluate to true.
9792 return true;
9793 } else {
9794 // Any other base is not constant enough for GCC.
9795 return false;
9796 }
9797}
9798
9799/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9800/// GCC as we can manage.
9801static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9802 // This evaluation is not permitted to have side-effects, so evaluate it in
9803 // a speculative evaluation context.
9804 SpeculativeEvaluationRAII SpeculativeEval(Info);
9805
9806 // Constant-folding is always enabled for the operand of __builtin_constant_p
9807 // (even when the enclosing evaluation context otherwise requires a strict
9808 // language-specific constant expression).
9809 FoldConstant Fold(Info, true);
9810
9811 QualType ArgType = Arg->getType();
9812
9813 // __builtin_constant_p always has one operand. The rules which gcc follows
9814 // are not precisely documented, but are as follows:
9815 //
9816 // - If the operand is of integral, floating, complex or enumeration type,
9817 // and can be folded to a known value of that type, it returns 1.
9818 // - If the operand can be folded to a pointer to the first character
9819 // of a string literal (or such a pointer cast to an integral type)
9820 // or to a null pointer or an integer cast to a pointer, it returns 1.
9821 //
9822 // Otherwise, it returns 0.
9823 //
9824 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9825 // its support for this did not work prior to GCC 9 and is not yet well
9826 // understood.
9827 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9828 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9829 ArgType->isNullPtrType()) {
9830 APValue V;
9831 if (!::EvaluateAsRValue(Info, Arg, V)) {
9832 Fold.keepDiagnostics();
9833 return false;
9834 }
9835
9836 // For a pointer (possibly cast to integer), there are special rules.
9837 if (V.getKind() == APValue::LValue)
9838 return EvaluateBuiltinConstantPForLValue(V);
9839
9840 // Otherwise, any constant value is good enough.
9841 return V.hasValue();
9842 }
9843
9844 // Anything else isn't considered to be sufficiently constant.
9845 return false;
9846}
9847
9848/// Retrieves the "underlying object type" of the given expression,
9849/// as used by __builtin_object_size.
9850static QualType getObjectType(APValue::LValueBase B) {
9851 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9852 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9853 return VD->getType();
9854 } else if (const Expr *E = B.get<const Expr*>()) {
9855 if (isa<CompoundLiteralExpr>(E))
9856 return E->getType();
9857 } else if (B.is<TypeInfoLValue>()) {
9858 return B.getTypeInfoType();
9859 } else if (B.is<DynamicAllocLValue>()) {
9860 return B.getDynamicAllocType();
9861 }
9862
9863 return QualType();
9864}
9865
9866/// A more selective version of E->IgnoreParenCasts for
9867/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9868/// to change the type of E.
9869/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9870///
9871/// Always returns an RValue with a pointer representation.
9872static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9873 assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9873, __PRETTY_FUNCTION__))
;
9874
9875 auto *NoParens = E->IgnoreParens();
9876 auto *Cast = dyn_cast<CastExpr>(NoParens);
9877 if (Cast == nullptr)
9878 return NoParens;
9879
9880 // We only conservatively allow a few kinds of casts, because this code is
9881 // inherently a simple solution that seeks to support the common case.
9882 auto CastKind = Cast->getCastKind();
9883 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9884 CastKind != CK_AddressSpaceConversion)
9885 return NoParens;
9886
9887 auto *SubExpr = Cast->getSubExpr();
9888 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9889 return NoParens;
9890 return ignorePointerCastsAndParens(SubExpr);
9891}
9892
9893/// Checks to see if the given LValue's Designator is at the end of the LValue's
9894/// record layout. e.g.
9895/// struct { struct { int a, b; } fst, snd; } obj;
9896/// obj.fst // no
9897/// obj.snd // yes
9898/// obj.fst.a // no
9899/// obj.fst.b // no
9900/// obj.snd.a // no
9901/// obj.snd.b // yes
9902///
9903/// Please note: this function is specialized for how __builtin_object_size
9904/// views "objects".
9905///
9906/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9907/// correct result, it will always return true.
9908static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9909 assert(!LVal.Designator.Invalid)((!LVal.Designator.Invalid) ? static_cast<void> (0) : __assert_fail
("!LVal.Designator.Invalid", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9909, __PRETTY_FUNCTION__))
;
9910
9911 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9912 const RecordDecl *Parent = FD->getParent();
9913 Invalid = Parent->isInvalidDecl();
9914 if (Invalid || Parent->isUnion())
9915 return true;
9916 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9917 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9918 };
9919
9920 auto &Base = LVal.getLValueBase();
9921 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9922 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9923 bool Invalid;
9924 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9925 return Invalid;
9926 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9927 for (auto *FD : IFD->chain()) {
9928 bool Invalid;
9929 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9930 return Invalid;
9931 }
9932 }
9933 }
9934
9935 unsigned I = 0;
9936 QualType BaseType = getType(Base);
9937 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9938 // If we don't know the array bound, conservatively assume we're looking at
9939 // the final array element.
9940 ++I;
9941 if (BaseType->isIncompleteArrayType())
9942 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9943 else
9944 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9945 }
9946
9947 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9948 const auto &Entry = LVal.Designator.Entries[I];
9949 if (BaseType->isArrayType()) {
9950 // Because __builtin_object_size treats arrays as objects, we can ignore
9951 // the index iff this is the last array in the Designator.
9952 if (I + 1 == E)
9953 return true;
9954 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9955 uint64_t Index = Entry.getAsArrayIndex();
9956 if (Index + 1 != CAT->getSize())
9957 return false;
9958 BaseType = CAT->getElementType();
9959 } else if (BaseType->isAnyComplexType()) {
9960 const auto *CT = BaseType->castAs<ComplexType>();
9961 uint64_t Index = Entry.getAsArrayIndex();
9962 if (Index != 1)
9963 return false;
9964 BaseType = CT->getElementType();
9965 } else if (auto *FD = getAsField(Entry)) {
9966 bool Invalid;
9967 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9968 return Invalid;
9969 BaseType = FD->getType();
9970 } else {
9971 assert(getAsBaseClass(Entry) && "Expecting cast to a base class")((getAsBaseClass(Entry) && "Expecting cast to a base class"
) ? static_cast<void> (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 9971, __PRETTY_FUNCTION__))
;
9972 return false;
9973 }
9974 }
9975 return true;
9976}
9977
9978/// Tests to see if the LValue has a user-specified designator (that isn't
9979/// necessarily valid). Note that this always returns 'true' if the LValue has
9980/// an unsized array as its first designator entry, because there's currently no
9981/// way to tell if the user typed *foo or foo[0].
9982static bool refersToCompleteObject(const LValue &LVal) {
9983 if (LVal.Designator.Invalid)
9984 return false;
9985
9986 if (!LVal.Designator.Entries.empty())
9987 return LVal.Designator.isMostDerivedAnUnsizedArray();
9988
9989 if (!LVal.InvalidBase)
9990 return true;
9991
9992 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9993 // the LValueBase.
9994 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9995 return !E || !isa<MemberExpr>(E);
9996}
9997
9998/// Attempts to detect a user writing into a piece of memory that's impossible
9999/// to figure out the size of by just using types.
10000static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10001 const SubobjectDesignator &Designator = LVal.Designator;
10002 // Notes:
10003 // - Users can only write off of the end when we have an invalid base. Invalid
10004 // bases imply we don't know where the memory came from.
10005 // - We used to be a bit more aggressive here; we'd only be conservative if
10006 // the array at the end was flexible, or if it had 0 or 1 elements. This
10007 // broke some common standard library extensions (PR30346), but was
10008 // otherwise seemingly fine. It may be useful to reintroduce this behavior
10009 // with some sort of whitelist. OTOH, it seems that GCC is always
10010 // conservative with the last element in structs (if it's an array), so our
10011 // current behavior is more compatible than a whitelisting approach would
10012 // be.
10013 return LVal.InvalidBase &&
10014 Designator.Entries.size() == Designator.MostDerivedPathLength &&
10015 Designator.MostDerivedIsArrayElement &&
10016 isDesignatorAtObjectEnd(Ctx, LVal);
10017}
10018
10019/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10020/// Fails if the conversion would cause loss of precision.
10021static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10022 CharUnits &Result) {
10023 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10024 if (Int.ugt(CharUnitsMax))
10025 return false;
10026 Result = CharUnits::fromQuantity(Int.getZExtValue());
10027 return true;
10028}
10029
10030/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10031/// determine how many bytes exist from the beginning of the object to either
10032/// the end of the current subobject, or the end of the object itself, depending
10033/// on what the LValue looks like + the value of Type.
10034///
10035/// If this returns false, the value of Result is undefined.
10036static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10037 unsigned Type, const LValue &LVal,
10038 CharUnits &EndOffset) {
10039 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10040
10041 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10042 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10043 return false;
10044 return HandleSizeof(Info, ExprLoc, Ty, Result);
10045 };
10046
10047 // We want to evaluate the size of the entire object. This is a valid fallback
10048 // for when Type=1 and the designator is invalid, because we're asked for an
10049 // upper-bound.
10050 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10051 // Type=3 wants a lower bound, so we can't fall back to this.
10052 if (Type == 3 && !DetermineForCompleteObject)
10053 return false;
10054
10055 llvm::APInt APEndOffset;
10056 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10057 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10058 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10059
10060 if (LVal.InvalidBase)
10061 return false;
10062
10063 QualType BaseTy = getObjectType(LVal.getLValueBase());
10064 return CheckedHandleSizeof(BaseTy, EndOffset);
10065 }
10066
10067 // We want to evaluate the size of a subobject.
10068 const SubobjectDesignator &Designator = LVal.Designator;
10069
10070 // The following is a moderately common idiom in C:
10071 //
10072 // struct Foo { int a; char c[1]; };
10073 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10074 // strcpy(&F->c[0], Bar);
10075 //
10076 // In order to not break too much legacy code, we need to support it.
10077 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10078 // If we can resolve this to an alloc_size call, we can hand that back,
10079 // because we know for certain how many bytes there are to write to.
10080 llvm::APInt APEndOffset;
10081 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10082 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10083 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10084
10085 // If we cannot determine the size of the initial allocation, then we can't
10086 // given an accurate upper-bound. However, we are still able to give
10087 // conservative lower-bounds for Type=3.
10088 if (Type == 1)
10089 return false;
10090 }
10091
10092 CharUnits BytesPerElem;
10093 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10094 return false;
10095
10096 // According to the GCC documentation, we want the size of the subobject
10097 // denoted by the pointer. But that's not quite right -- what we actually
10098 // want is the size of the immediately-enclosing array, if there is one.
10099 int64_t ElemsRemaining;
10100 if (Designator.MostDerivedIsArrayElement &&
10101 Designator.Entries.size() == Designator.MostDerivedPathLength) {
10102 uint64_t ArraySize = Designator.getMostDerivedArraySize();
10103 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10104 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10105 } else {
10106 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10107 }
10108
10109 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10110 return true;
10111}
10112
10113/// Tries to evaluate the __builtin_object_size for @p E. If successful,
10114/// returns true and stores the result in @p Size.
10115///
10116/// If @p WasError is non-null, this will report whether the failure to evaluate
10117/// is to be treated as an Error in IntExprEvaluator.
10118static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10119 EvalInfo &Info, uint64_t &Size) {
10120 // Determine the denoted object.
10121 LValue LVal;
10122 {
10123 // The operand of __builtin_object_size is never evaluated for side-effects.
10124 // If there are any, but we can determine the pointed-to object anyway, then
10125 // ignore the side-effects.
10126 SpeculativeEvaluationRAII SpeculativeEval(Info);
10127 IgnoreSideEffectsRAII Fold(Info);
10128
10129 if (E->isGLValue()) {
10130 // It's possible for us to be given GLValues if we're called via
10131 // Expr::tryEvaluateObjectSize.
10132 APValue RVal;
10133 if (!EvaluateAsRValue(Info, E, RVal))
10134 return false;
10135 LVal.setFrom(Info.Ctx, RVal);
10136 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10137 /*InvalidBaseOK=*/true))
10138 return false;
10139 }
10140
10141 // If we point to before the start of the object, there are no accessible
10142 // bytes.
10143 if (LVal.getLValueOffset().isNegative()) {
10144 Size = 0;
10145 return true;
10146 }
10147
10148 CharUnits EndOffset;
10149 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10150 return false;
10151
10152 // If we've fallen outside of the end offset, just pretend there's nothing to
10153 // write to/read from.
10154 if (EndOffset <= LVal.getLValueOffset())
10155 Size = 0;
10156 else
10157 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10158 return true;
10159}
10160
10161bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10162 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10163 if (E->getResultAPValueKind() != APValue::None)
10164 return Success(E->getAPValueResult(), E);
10165 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10166}
10167
10168bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10169 if (unsigned BuiltinOp = E->getBuiltinCallee())
10170 return VisitBuiltinCallExpr(E, BuiltinOp);
10171
10172 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10173}
10174
10175bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10176 unsigned BuiltinOp) {
10177 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
10178 default:
10179 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10180
10181 case Builtin::BI__builtin_dynamic_object_size:
10182 case Builtin::BI__builtin_object_size: {
10183 // The type was checked when we built the expression.
10184 unsigned Type =
10185 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10186 assert(Type <= 3 && "unexpected type")((Type <= 3 && "unexpected type") ? static_cast<
void> (0) : __assert_fail ("Type <= 3 && \"unexpected type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10186, __PRETTY_FUNCTION__))
;
10187
10188 uint64_t Size;
10189 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10190 return Success(Size, E);
10191
10192 if (E->getArg(0)->HasSideEffects(Info.Ctx))
10193 return Success((Type & 2) ? 0 : -1, E);
10194
10195 // Expression had no side effects, but we couldn't statically determine the
10196 // size of the referenced object.
10197 switch (Info.EvalMode) {
10198 case EvalInfo::EM_ConstantExpression:
10199 case EvalInfo::EM_ConstantFold:
10200 case EvalInfo::EM_IgnoreSideEffects:
10201 // Leave it to IR generation.
10202 return Error(E);
10203 case EvalInfo::EM_ConstantExpressionUnevaluated:
10204 // Reduce it to a constant now.
10205 return Success((Type & 2) ? 0 : -1, E);
10206 }
10207
10208 llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10208)
;
10209 }
10210
10211 case Builtin::BI__builtin_os_log_format_buffer_size: {
10212 analyze_os_log::OSLogBufferLayout Layout;
10213 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10214 return Success(Layout.size().getQuantity(), E);
10215 }
10216
10217 case Builtin::BI__builtin_bswap16:
10218 case Builtin::BI__builtin_bswap32:
10219 case Builtin::BI__builtin_bswap64: {
10220 APSInt Val;
10221 if (!EvaluateInteger(E->getArg(0), Val, Info))
10222 return false;
10223
10224 return Success(Val.byteSwap(), E);
10225 }
10226
10227 case Builtin::BI__builtin_classify_type:
10228 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10229
10230 case Builtin::BI__builtin_clrsb:
10231 case Builtin::BI__builtin_clrsbl:
10232 case Builtin::BI__builtin_clrsbll: {
10233 APSInt Val;
10234 if (!EvaluateInteger(E->getArg(0), Val, Info))
10235 return false;
10236
10237 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10238 }
10239
10240 case Builtin::BI__builtin_clz:
10241 case Builtin::BI__builtin_clzl:
10242 case Builtin::BI__builtin_clzll:
10243 case Builtin::BI__builtin_clzs: {
10244 APSInt Val;
10245 if (!EvaluateInteger(E->getArg(0), Val, Info))
10246 return false;
10247 if (!Val)
10248 return Error(E);
10249
10250 return Success(Val.countLeadingZeros(), E);
10251 }
10252
10253 case Builtin::BI__builtin_constant_p: {
10254 const Expr *Arg = E->getArg(0);
10255 if (EvaluateBuiltinConstantP(Info, Arg))
10256 return Success(true, E);
10257 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10258 // Outside a constant context, eagerly evaluate to false in the presence
10259 // of side-effects in order to avoid -Wunsequenced false-positives in
10260 // a branch on __builtin_constant_p(expr).
10261 return Success(false, E);
10262 }
10263 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10264 return false;
10265 }
10266
10267 case Builtin::BI__builtin_is_constant_evaluated:
10268 return Success(Info.InConstantContext, E);
10269
10270 case Builtin::BI__builtin_ctz:
10271 case Builtin::BI__builtin_ctzl:
10272 case Builtin::BI__builtin_ctzll:
10273 case Builtin::BI__builtin_ctzs: {
10274 APSInt Val;
10275 if (!EvaluateInteger(E->getArg(0), Val, Info))
10276 return false;
10277 if (!Val)
10278 return Error(E);
10279
10280 return Success(Val.countTrailingZeros(), E);
10281 }
10282
10283 case Builtin::BI__builtin_eh_return_data_regno: {
10284 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10285 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10286 return Success(Operand, E);
10287 }
10288
10289 case Builtin::BI__builtin_expect:
10290 return Visit(E->getArg(0));
10291
10292 case Builtin::BI__builtin_ffs:
10293 case Builtin::BI__builtin_ffsl:
10294 case Builtin::BI__builtin_ffsll: {
10295 APSInt Val;
10296 if (!EvaluateInteger(E->getArg(0), Val, Info))
10297 return false;
10298
10299 unsigned N = Val.countTrailingZeros();
10300 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10301 }
10302
10303 case Builtin::BI__builtin_fpclassify: {
10304 APFloat Val(0.0);
10305 if (!EvaluateFloat(E->getArg(5), Val, Info))
10306 return false;
10307 unsigned Arg;
10308 switch (Val.getCategory()) {
10309 case APFloat::fcNaN: Arg = 0; break;
10310 case APFloat::fcInfinity: Arg = 1; break;
10311 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10312 case APFloat::fcZero: Arg = 4; break;
10313 }
10314 return Visit(E->getArg(Arg));
10315 }
10316
10317 case Builtin::BI__builtin_isinf_sign: {
10318 APFloat Val(0.0);
10319 return EvaluateFloat(E->getArg(0), Val, Info) &&
10320 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10321 }
10322
10323 case Builtin::BI__builtin_isinf: {
10324 APFloat Val(0.0);
10325 return EvaluateFloat(E->getArg(0), Val, Info) &&
10326 Success(Val.isInfinity() ? 1 : 0, E);
10327 }
10328
10329 case Builtin::BI__builtin_isfinite: {
10330 APFloat Val(0.0);
10331 return EvaluateFloat(E->getArg(0), Val, Info) &&
10332 Success(Val.isFinite() ? 1 : 0, E);
10333 }
10334
10335 case Builtin::BI__builtin_isnan: {
10336 APFloat Val(0.0);
10337 return EvaluateFloat(E->getArg(0), Val, Info) &&
10338 Success(Val.isNaN() ? 1 : 0, E);
10339 }
10340
10341 case Builtin::BI__builtin_isnormal: {
10342 APFloat Val(0.0);
10343 return EvaluateFloat(E->getArg(0), Val, Info) &&
10344 Success(Val.isNormal() ? 1 : 0, E);
10345 }
10346
10347 case Builtin::BI__builtin_parity:
10348 case Builtin::BI__builtin_parityl:
10349 case Builtin::BI__builtin_parityll: {
10350 APSInt Val;
10351 if (!EvaluateInteger(E->getArg(0), Val, Info))
10352 return false;
10353
10354 return Success(Val.countPopulation() % 2, E);
10355 }
10356
10357 case Builtin::BI__builtin_popcount:
10358 case Builtin::BI__builtin_popcountl:
10359 case Builtin::BI__builtin_popcountll: {
10360 APSInt Val;
10361 if (!EvaluateInteger(E->getArg(0), Val, Info))
10362 return false;
10363
10364 return Success(Val.countPopulation(), E);
10365 }
10366
10367 case Builtin::BIstrlen:
10368 case Builtin::BIwcslen:
10369 // A call to strlen is not a constant expression.
10370 if (Info.getLangOpts().CPlusPlus11)
10371 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10372 << /*isConstexpr*/0 << /*isConstructor*/0
10373 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
10374 else
10375 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10376 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10377 case Builtin::BI__builtin_strlen:
10378 case Builtin::BI__builtin_wcslen: {
10379 // As an extension, we support __builtin_strlen() as a constant expression,
10380 // and support folding strlen() to a constant.
10381 LValue String;
10382 if (!EvaluatePointer(E->getArg(0), String, Info))
10383 return false;
10384
10385 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10386
10387 // Fast path: if it's a string literal, search the string value.
10388 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10389 String.getLValueBase().dyn_cast<const Expr *>())) {
10390 // The string literal may have embedded null characters. Find the first
10391 // one and truncate there.
10392 StringRef Str = S->getBytes();
10393 int64_t Off = String.Offset.getQuantity();
10394 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
10395 S->getCharByteWidth() == 1 &&
10396 // FIXME: Add fast-path for wchar_t too.
10397 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
10398 Str = Str.substr(Off);
10399
10400 StringRef::size_type Pos = Str.find(0);
10401 if (Pos != StringRef::npos)
10402 Str = Str.substr(0, Pos);
10403
10404 return Success(Str.size(), E);
10405 }
10406
10407 // Fall through to slow path to issue appropriate diagnostic.
10408 }
10409
10410 // Slow path: scan the bytes of the string looking for the terminating 0.
10411 for (uint64_t Strlen = 0; /**/; ++Strlen) {
10412 APValue Char;
10413 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
10414 !Char.isInt())
10415 return false;
10416 if (!Char.getInt())
10417 return Success(Strlen, E);
10418 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
10419 return false;
10420 }
10421 }
10422
10423 case Builtin::BIstrcmp:
10424 case Builtin::BIwcscmp:
10425 case Builtin::BIstrncmp:
10426 case Builtin::BIwcsncmp:
10427 case Builtin::BImemcmp:
10428 case Builtin::BIbcmp:
10429 case Builtin::BIwmemcmp:
10430 // A call to strlen is not a constant expression.
10431 if (Info.getLangOpts().CPlusPlus11)
10432 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10433 << /*isConstexpr*/0 << /*isConstructor*/0
10434 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
10435 else
10436 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10437 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10438 case Builtin::BI__builtin_strcmp:
10439 case Builtin::BI__builtin_wcscmp:
10440 case Builtin::BI__builtin_strncmp:
10441 case Builtin::BI__builtin_wcsncmp:
10442 case Builtin::BI__builtin_memcmp:
10443 case Builtin::BI__builtin_bcmp:
10444 case Builtin::BI__builtin_wmemcmp: {
10445 LValue String1, String2;
10446 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10447 !EvaluatePointer(E->getArg(1), String2, Info))
10448 return false;
10449
10450 uint64_t MaxLength = uint64_t(-1);
10451 if (BuiltinOp != Builtin::BIstrcmp &&
10452 BuiltinOp != Builtin::BIwcscmp &&
10453 BuiltinOp != Builtin::BI__builtin_strcmp &&
10454 BuiltinOp != Builtin::BI__builtin_wcscmp) {
10455 APSInt N;
10456 if (!EvaluateInteger(E->getArg(2), N, Info))
10457 return false;
10458 MaxLength = N.getExtValue();
10459 }
10460
10461 // Empty substrings compare equal by definition.
10462 if (MaxLength == 0u)
10463 return Success(0, E);
10464
10465 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10466 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10467 String1.Designator.Invalid || String2.Designator.Invalid)
10468 return false;
10469
10470 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10471 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10472
10473 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
10474 BuiltinOp == Builtin::BIbcmp ||
10475 BuiltinOp == Builtin::BI__builtin_memcmp ||
10476 BuiltinOp == Builtin::BI__builtin_bcmp;
10477
10478 assert(IsRawByte ||((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->
getArg(0)->getType()->getPointeeType()) && Info
.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast
<void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10481, __PRETTY_FUNCTION__))
10479 (Info.Ctx.hasSameUnqualifiedType(((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->
getArg(0)->getType()->getPointeeType()) && Info
.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast
<void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10481, __PRETTY_FUNCTION__))
10480 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->
getArg(0)->getType()->getPointeeType()) && Info
.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast
<void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10481, __PRETTY_FUNCTION__))
10481 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)))((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->
getArg(0)->getType()->getPointeeType()) && Info
.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast
<void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10481, __PRETTY_FUNCTION__))
;
10482
10483 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10484 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10485 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10486 Char1.isInt() && Char2.isInt();
10487 };
10488 const auto &AdvanceElems = [&] {
10489 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10490 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10491 };
10492
10493 if (IsRawByte) {
10494 uint64_t BytesRemaining = MaxLength;
10495 // Pointers to const void may point to objects of incomplete type.
10496 if (CharTy1->isIncompleteType()) {
10497 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10498 return false;
10499 }
10500 if (CharTy2->isIncompleteType()) {
10501 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10502 return false;
10503 }
10504 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10505 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10506 // Give up on comparing between elements with disparate widths.
10507 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10508 return false;
10509 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10510 assert(BytesRemaining && "BytesRemaining should not be zero: the "((BytesRemaining && "BytesRemaining should not be zero: the "
"following loop considers at least one element") ? static_cast
<void> (0) : __assert_fail ("BytesRemaining && \"BytesRemaining should not be zero: the \" \"following loop considers at least one element\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10511, __PRETTY_FUNCTION__))
10511 "following loop considers at least one element")((BytesRemaining && "BytesRemaining should not be zero: the "
"following loop considers at least one element") ? static_cast
<void> (0) : __assert_fail ("BytesRemaining && \"BytesRemaining should not be zero: the \" \"following loop considers at least one element\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10511, __PRETTY_FUNCTION__))
;
10512 while (true) {
10513 APValue Char1, Char2;
10514 if (!ReadCurElems(Char1, Char2))
10515 return false;
10516 // We have compatible in-memory widths, but a possible type and
10517 // (for `bool`) internal representation mismatch.
10518 // Assuming two's complement representation, including 0 for `false` and
10519 // 1 for `true`, we can check an appropriate number of elements for
10520 // equality even if they are not byte-sized.
10521 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10522 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10523 if (Char1InMem.ne(Char2InMem)) {
10524 // If the elements are byte-sized, then we can produce a three-way
10525 // comparison result in a straightforward manner.
10526 if (BytesPerElement == 1u) {
10527 // memcmp always compares unsigned chars.
10528 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10529 }
10530 // The result is byte-order sensitive, and we have multibyte elements.
10531 // FIXME: We can compare the remaining bytes in the correct order.
10532 return false;
10533 }
10534 if (!AdvanceElems())
10535 return false;
10536 if (BytesRemaining <= BytesPerElement)
10537 break;
10538 BytesRemaining -= BytesPerElement;
10539 }
10540 // Enough elements are equal to account for the memcmp limit.
10541 return Success(0, E);
10542 }
10543
10544 bool StopAtNull =
10545 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10546 BuiltinOp != Builtin::BIwmemcmp &&
10547 BuiltinOp != Builtin::BI__builtin_memcmp &&
10548 BuiltinOp != Builtin::BI__builtin_bcmp &&
10549 BuiltinOp != Builtin::BI__builtin_wmemcmp);
10550 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10551 BuiltinOp == Builtin::BIwcsncmp ||
10552 BuiltinOp == Builtin::BIwmemcmp ||
10553 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10554 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10555 BuiltinOp == Builtin::BI__builtin_wmemcmp;
10556
10557 for (; MaxLength; --MaxLength) {
10558 APValue Char1, Char2;
10559 if (!ReadCurElems(Char1, Char2))
10560 return false;
10561 if (Char1.getInt() != Char2.getInt()) {
10562 if (IsWide) // wmemcmp compares with wchar_t signedness.
10563 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10564 // memcmp always compares unsigned chars.
10565 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10566 }
10567 if (StopAtNull && !Char1.getInt())
10568 return Success(0, E);
10569 assert(!(StopAtNull && !Char2.getInt()))((!(StopAtNull && !Char2.getInt())) ? static_cast<
void> (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10569, __PRETTY_FUNCTION__))
;
10570 if (!AdvanceElems())
10571 return false;
10572 }
10573 // We hit the strncmp / memcmp limit.
10574 return Success(0, E);
10575 }
10576
10577 case Builtin::BI__atomic_always_lock_free:
10578 case Builtin::BI__atomic_is_lock_free:
10579 case Builtin::BI__c11_atomic_is_lock_free: {
10580 APSInt SizeVal;
10581 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10582 return false;
10583
10584 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10585 // of two less than the maximum inline atomic width, we know it is
10586 // lock-free. If the size isn't a power of two, or greater than the
10587 // maximum alignment where we promote atomics, we know it is not lock-free
10588 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10589 // the answer can only be determined at runtime; for example, 16-byte
10590 // atomics have lock-free implementations on some, but not all,
10591 // x86-64 processors.
10592
10593 // Check power-of-two.
10594 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
10595 if (Size.isPowerOfTwo()) {
10596 // Check against inlining width.
10597 unsigned InlineWidthBits =
10598 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10599 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10600 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10601 Size == CharUnits::One() ||
10602 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10603 Expr::NPC_NeverValueDependent))
10604 // OK, we will inline appropriately-aligned operations of this size,
10605 // and _Atomic(T) is appropriately-aligned.
10606 return Success(1, E);
10607
10608 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10609 castAs<PointerType>()->getPointeeType();
10610 if (!PointeeType->isIncompleteType() &&
10611 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10612 // OK, we will inline operations on this object.
10613 return Success(1, E);
10614 }
10615 }
10616 }
10617
10618 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10619 Success(0, E) : Error(E);
10620 }
10621 case Builtin::BIomp_is_initial_device:
10622 // We can decide statically which value the runtime would return if called.
10623 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
10624 case Builtin::BI__builtin_add_overflow:
10625 case Builtin::BI__builtin_sub_overflow:
10626 case Builtin::BI__builtin_mul_overflow:
10627 case Builtin::BI__builtin_sadd_overflow:
10628 case Builtin::BI__builtin_uadd_overflow:
10629 case Builtin::BI__builtin_uaddl_overflow:
10630 case Builtin::BI__builtin_uaddll_overflow:
10631 case Builtin::BI__builtin_usub_overflow:
10632 case Builtin::BI__builtin_usubl_overflow:
10633 case Builtin::BI__builtin_usubll_overflow:
10634 case Builtin::BI__builtin_umul_overflow:
10635 case Builtin::BI__builtin_umull_overflow:
10636 case Builtin::BI__builtin_umulll_overflow:
10637 case Builtin::BI__builtin_saddl_overflow:
10638 case Builtin::BI__builtin_saddll_overflow:
10639 case Builtin::BI__builtin_ssub_overflow:
10640 case Builtin::BI__builtin_ssubl_overflow:
10641 case Builtin::BI__builtin_ssubll_overflow:
10642 case Builtin::BI__builtin_smul_overflow:
10643 case Builtin::BI__builtin_smull_overflow:
10644 case Builtin::BI__builtin_smulll_overflow: {
10645 LValue ResultLValue;
10646 APSInt LHS, RHS;
10647
10648 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10649 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10650 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10651 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10652 return false;
10653
10654 APSInt Result;
10655 bool DidOverflow = false;
10656
10657 // If the types don't have to match, enlarge all 3 to the largest of them.
10658 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10659 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10660 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10661 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
10662 ResultType->isSignedIntegerOrEnumerationType();
10663 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
10664 ResultType->isSignedIntegerOrEnumerationType();
10665 uint64_t LHSSize = LHS.getBitWidth();
10666 uint64_t RHSSize = RHS.getBitWidth();
10667 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
10668 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
10669
10670 // Add an additional bit if the signedness isn't uniformly agreed to. We
10671 // could do this ONLY if there is a signed and an unsigned that both have
10672 // MaxBits, but the code to check that is pretty nasty. The issue will be
10673 // caught in the shrink-to-result later anyway.
10674 if (IsSigned && !AllSigned)
10675 ++MaxBits;
10676
10677 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
10678 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
10679 Result = APSInt(MaxBits, !IsSigned);
10680 }
10681
10682 // Find largest int.
10683 switch (BuiltinOp) {
10684 default:
10685 llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10685)
;
10686 case Builtin::BI__builtin_add_overflow:
10687 case Builtin::BI__builtin_sadd_overflow:
10688 case Builtin::BI__builtin_saddl_overflow:
10689 case Builtin::BI__builtin_saddll_overflow:
10690 case Builtin::BI__builtin_uadd_overflow:
10691 case Builtin::BI__builtin_uaddl_overflow:
10692 case Builtin::BI__builtin_uaddll_overflow:
10693 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10694 : LHS.uadd_ov(RHS, DidOverflow);
10695 break;
10696 case Builtin::BI__builtin_sub_overflow:
10697 case Builtin::BI__builtin_ssub_overflow:
10698 case Builtin::BI__builtin_ssubl_overflow:
10699 case Builtin::BI__builtin_ssubll_overflow:
10700 case Builtin::BI__builtin_usub_overflow:
10701 case Builtin::BI__builtin_usubl_overflow:
10702 case Builtin::BI__builtin_usubll_overflow:
10703 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10704 : LHS.usub_ov(RHS, DidOverflow);
10705 break;
10706 case Builtin::BI__builtin_mul_overflow:
10707 case Builtin::BI__builtin_smul_overflow:
10708 case Builtin::BI__builtin_smull_overflow:
10709 case Builtin::BI__builtin_smulll_overflow:
10710 case Builtin::BI__builtin_umul_overflow:
10711 case Builtin::BI__builtin_umull_overflow:
10712 case Builtin::BI__builtin_umulll_overflow:
10713 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10714 : LHS.umul_ov(RHS, DidOverflow);
10715 break;
10716 }
10717
10718 // In the case where multiple sizes are allowed, truncate and see if
10719 // the values are the same.
10720 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10721 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10722 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10723 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10724 // since it will give us the behavior of a TruncOrSelf in the case where
10725 // its parameter <= its size. We previously set Result to be at least the
10726 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10727 // will work exactly like TruncOrSelf.
10728 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10729 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10730
10731 if (!APSInt::isSameValue(Temp, Result))
10732 DidOverflow = true;
10733 Result = Temp;
10734 }
10735
10736 APValue APV{Result};
10737 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10738 return false;
10739 return Success(DidOverflow, E);
10740 }
10741 }
10742}
10743
10744/// Determine whether this is a pointer past the end of the complete
10745/// object referred to by the lvalue.
10746static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10747 const LValue &LV) {
10748 // A null pointer can be viewed as being "past the end" but we don't
10749 // choose to look at it that way here.
10750 if (!LV.getLValueBase())
10751 return false;
10752
10753 // If the designator is valid and refers to a subobject, we're not pointing
10754 // past the end.
10755 if (!LV.getLValueDesignator().Invalid &&
10756 !LV.getLValueDesignator().isOnePastTheEnd())
10757 return false;
10758
10759 // A pointer to an incomplete type might be past-the-end if the type's size is
10760 // zero. We cannot tell because the type is incomplete.
10761 QualType Ty = getType(LV.getLValueBase());
10762 if (Ty->isIncompleteType())
10763 return true;
10764
10765 // We're a past-the-end pointer if we point to the byte after the object,
10766 // no matter what our type or path is.
10767 auto Size = Ctx.getTypeSizeInChars(Ty);
10768 return LV.getLValueOffset() == Size;
10769}
10770
10771namespace {
10772
10773/// Data recursive integer evaluator of certain binary operators.
10774///
10775/// We use a data recursive algorithm for binary operators so that we are able
10776/// to handle extreme cases of chained binary operators without causing stack
10777/// overflow.
10778class DataRecursiveIntBinOpEvaluator {
10779 struct EvalResult {
10780 APValue Val;
10781 bool Failed;
10782
10783 EvalResult() : Failed(false) { }
10784
10785 void swap(EvalResult &RHS) {
10786 Val.swap(RHS.Val);
10787 Failed = RHS.Failed;
10788 RHS.Failed = false;
10789 }
10790 };
10791
10792 struct Job {
10793 const Expr *E;
10794 EvalResult LHSResult; // meaningful only for binary operator expression.
10795 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10796
10797 Job() = default;
10798 Job(Job &&) = default;
10799
10800 void startSpeculativeEval(EvalInfo &Info) {
10801 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10802 }
10803
10804 private:
10805 SpeculativeEvaluationRAII SpecEvalRAII;
10806 };
10807
10808 SmallVector<Job, 16> Queue;
10809
10810 IntExprEvaluator &IntEval;
10811 EvalInfo &Info;
10812 APValue &FinalResult;
10813
10814public:
10815 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10816 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10817
10818 /// True if \param E is a binary operator that we are going to handle
10819 /// data recursively.
10820 /// We handle binary operators that are comma, logical, or that have operands
10821 /// with integral or enumeration type.
10822 static bool shouldEnqueue(const BinaryOperator *E) {
10823 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10824 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10825 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10826 E->getRHS()->getType()->isIntegralOrEnumerationType());
10827 }
10828
10829 bool Traverse(const BinaryOperator *E) {
10830 enqueue(E);
10831 EvalResult PrevResult;
10832 while (!Queue.empty())
10833 process(PrevResult);
10834
10835 if (PrevResult.Failed) return false;
10836
10837 FinalResult.swap(PrevResult.Val);
10838 return true;
10839 }
10840
10841private:
10842 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10843 return IntEval.Success(Value, E, Result);
10844 }
10845 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10846 return IntEval.Success(Value, E, Result);
10847 }
10848 bool Error(const Expr *E) {
10849 return IntEval.Error(E);
10850 }
10851 bool Error(const Expr *E, diag::kind D) {
10852 return IntEval.Error(E, D);
10853 }
10854
10855 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10856 return Info.CCEDiag(E, D);
10857 }
10858
10859 // Returns true if visiting the RHS is necessary, false otherwise.
10860 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10861 bool &SuppressRHSDiags);
10862
10863 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10864 const BinaryOperator *E, APValue &Result);
10865
10866 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10867 Result.Failed = !Evaluate(Result.Val, Info, E);
10868 if (Result.Failed)
10869 Result.Val = APValue();
10870 }
10871
10872 void process(EvalResult &Result);
10873
10874 void enqueue(const Expr *E) {
10875 E = E->IgnoreParens();
10876 Queue.resize(Queue.size()+1);
10877 Queue.back().E = E;
10878 Queue.back().Kind = Job::AnyExprKind;
10879 }
10880};
10881
10882}
10883
10884bool DataRecursiveIntBinOpEvaluator::
10885 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10886 bool &SuppressRHSDiags) {
10887 if (E->getOpcode() == BO_Comma) {
10888 // Ignore LHS but note if we could not evaluate it.
10889 if (LHSResult.Failed)
10890 return Info.noteSideEffect();
10891 return true;
10892 }
10893
10894 if (E->isLogicalOp()) {
10895 bool LHSAsBool;
10896 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10897 // We were able to evaluate the LHS, see if we can get away with not
10898 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10899 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10900 Success(LHSAsBool, E, LHSResult.Val);
10901 return false; // Ignore RHS
10902 }
10903 } else {
10904 LHSResult.Failed = true;
10905
10906 // Since we weren't able to evaluate the left hand side, it
10907 // might have had side effects.
10908 if (!Info.noteSideEffect())
10909 return false;
10910
10911 // We can't evaluate the LHS; however, sometimes the result
10912 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10913 // Don't ignore RHS and suppress diagnostics from this arm.
10914 SuppressRHSDiags = true;
10915 }
10916
10917 return true;
10918 }
10919
10920 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&((E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10921, __PRETTY_FUNCTION__))
10921 E->getRHS()->getType()->isIntegralOrEnumerationType())((E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10921, __PRETTY_FUNCTION__))
;
10922
10923 if (LHSResult.Failed && !Info.noteFailure())
10924 return false; // Ignore RHS;
10925
10926 return true;
10927}
10928
10929static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10930 bool IsSub) {
10931 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10932 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10933 // offsets.
10934 assert(!LVal.hasLValuePath() && "have designator for integer lvalue")((!LVal.hasLValuePath() && "have designator for integer lvalue"
) ? static_cast<void> (0) : __assert_fail ("!LVal.hasLValuePath() && \"have designator for integer lvalue\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10934, __PRETTY_FUNCTION__))
;
10935 CharUnits &Offset = LVal.getLValueOffset();
10936 uint64_t Offset64 = Offset.getQuantity();
10937 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10938 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10939 : Offset64 + Index64);
10940}
10941
10942bool DataRecursiveIntBinOpEvaluator::
10943 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10944 const BinaryOperator *E, APValue &Result) {
10945 if (E->getOpcode() == BO_Comma) {
10946 if (RHSResult.Failed)
10947 return false;
10948 Result = RHSResult.Val;
10949 return true;
10950 }
10951
10952 if (E->isLogicalOp()) {
10953 bool lhsResult, rhsResult;
10954 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10955 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10956
10957 if (LHSIsOK) {
10958 if (RHSIsOK) {
10959 if (E->getOpcode() == BO_LOr)
10960 return Success(lhsResult || rhsResult, E, Result);
10961 else
10962 return Success(lhsResult && rhsResult, E, Result);
10963 }
10964 } else {
10965 if (RHSIsOK) {
10966 // We can't evaluate the LHS; however, sometimes the result
10967 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10968 if (rhsResult == (E->getOpcode() == BO_LOr))
10969 return Success(rhsResult, E, Result);
10970 }
10971 }
10972
10973 return false;
10974 }
10975
10976 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&((E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10977, __PRETTY_FUNCTION__))
10977 E->getRHS()->getType()->isIntegralOrEnumerationType())((E->getLHS()->getType()->isIntegralOrEnumerationType
() && E->getRHS()->getType()->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 10977, __PRETTY_FUNCTION__))
;
10978
10979 if (LHSResult.Failed || RHSResult.Failed)
10980 return false;
10981
10982 const APValue &LHSVal = LHSResult.Val;
10983 const APValue &RHSVal = RHSResult.Val;
10984
10985 // Handle cases like (unsigned long)&a + 4.
10986 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10987 Result = LHSVal;
10988 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10989 return true;
10990 }
10991
10992 // Handle cases like 4 + (unsigned long)&a
10993 if (E->getOpcode() == BO_Add &&
10994 RHSVal.isLValue() && LHSVal.isInt()) {
10995 Result = RHSVal;
10996 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10997 return true;
10998 }
10999
11000 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11001 // Handle (intptr_t)&&A - (intptr_t)&&B.
11002 if (!LHSVal.getLValueOffset().isZero() ||
11003 !RHSVal.getLValueOffset().isZero())
11004 return false;
11005 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11006 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11007 if (!LHSExpr || !RHSExpr)
11008 return false;
11009 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11010 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11011 if (!LHSAddrExpr || !RHSAddrExpr)
11012 return false;
11013 // Make sure both labels come from the same function.
11014 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11015 RHSAddrExpr->getLabel()->getDeclContext())
11016 return false;
11017 Result = APValue(LHSAddrExpr, RHSAddrExpr);
11018 return true;
11019 }
11020
11021 // All the remaining cases expect both operands to be an integer
11022 if (!LHSVal.isInt() || !RHSVal.isInt())
11023 return Error(E);
11024
11025 // Set up the width and signedness manually, in case it can't be deduced
11026 // from the operation we're performing.
11027 // FIXME: Don't do this in the cases where we can deduce it.
11028 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11029 E->getType()->isUnsignedIntegerOrEnumerationType());
11030 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11031 RHSVal.getInt(), Value))
11032 return false;
11033 return Success(Value, E, Result);
11034}
11035
11036void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11037 Job &job = Queue.back();
11038
11039 switch (job.Kind) {
11040 case Job::AnyExprKind: {
11041 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11042 if (shouldEnqueue(Bop)) {
11043 job.Kind = Job::BinOpKind;
11044 enqueue(Bop->getLHS());
11045 return;
11046 }
11047 }
11048
11049 EvaluateExpr(job.E, Result);
11050 Queue.pop_back();
11051 return;
11052 }
11053
11054 case Job::BinOpKind: {
11055 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11056 bool SuppressRHSDiags = false;
11057 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11058 Queue.pop_back();
11059 return;
11060 }
11061 if (SuppressRHSDiags)
11062 job.startSpeculativeEval(Info);
11063 job.LHSResult.swap(Result);
11064 job.Kind = Job::BinOpVisitedLHSKind;
11065 enqueue(Bop->getRHS());
11066 return;
11067 }
11068
11069 case Job::BinOpVisitedLHSKind: {
11070 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11071 EvalResult RHS;
11072 RHS.swap(Result);
11073 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11074 Queue.pop_back();
11075 return;
11076 }
11077 }
11078
11079 llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11079)
;
11080}
11081
11082namespace {
11083/// Used when we determine that we should fail, but can keep evaluating prior to
11084/// noting that we had a failure.
11085class DelayedNoteFailureRAII {
11086 EvalInfo &Info;
11087 bool NoteFailure;
11088
11089public:
11090 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11091 : Info(Info), NoteFailure(NoteFailure) {}
11092 ~DelayedNoteFailureRAII() {
11093 if (NoteFailure) {
11094 bool ContinueAfterFailure = Info.noteFailure();
11095 (void)ContinueAfterFailure;
11096 assert(ContinueAfterFailure &&((ContinueAfterFailure && "Shouldn't have kept evaluating on failure."
) ? static_cast<void> (0) : __assert_fail ("ContinueAfterFailure && \"Shouldn't have kept evaluating on failure.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11097, __PRETTY_FUNCTION__))
11097 "Shouldn't have kept evaluating on failure.")((ContinueAfterFailure && "Shouldn't have kept evaluating on failure."
) ? static_cast<void> (0) : __assert_fail ("ContinueAfterFailure && \"Shouldn't have kept evaluating on failure.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11097, __PRETTY_FUNCTION__))
;
11098 }
11099 }
11100};
11101}
11102
11103template <class SuccessCB, class AfterCB>
11104static bool
11105EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11106 SuccessCB &&Success, AfterCB &&DoAfter) {
11107 assert(E->isComparisonOp() && "expected comparison operator")((E->isComparisonOp() && "expected comparison operator"
) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"expected comparison operator\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11107, __PRETTY_FUNCTION__))
;
11108 assert((E->getOpcode() == BO_Cmp ||(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType
()) && "unsupported binary expression evaluation") ? static_cast
<void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11110, __PRETTY_FUNCTION__))
11109 E->getType()->isIntegralOrEnumerationType()) &&(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType
()) && "unsupported binary expression evaluation") ? static_cast
<void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11110, __PRETTY_FUNCTION__))
11110 "unsupported binary expression evaluation")(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType
()) && "unsupported binary expression evaluation") ? static_cast
<void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11110, __PRETTY_FUNCTION__))
;
11111 auto Error = [&](const Expr *E) {
11112 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11113 return false;
11114 };
11115
11116 using CCR = ComparisonCategoryResult;
11117 bool IsRelational = E->isRelationalOp();
11118 bool IsEquality = E->isEqualityOp();
11119 if (E->getOpcode() == BO_Cmp) {
11120 const ComparisonCategoryInfo &CmpInfo =
11121 Info.Ctx.CompCategories.getInfoForType(E->getType());
11122 IsRelational = CmpInfo.isOrdered();
11123 IsEquality = CmpInfo.isEquality();
11124 }
11125
11126 QualType LHSTy = E->getLHS()->getType();
11127 QualType RHSTy = E->getRHS()->getType();
11128
11129 if (LHSTy->isIntegralOrEnumerationType() &&
11130 RHSTy->isIntegralOrEnumerationType()) {
11131 APSInt LHS, RHS;
11132 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11133 if (!LHSOK && !Info.noteFailure())
11134 return false;
11135 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11136 return false;
11137 if (LHS < RHS)
11138 return Success(CCR::Less, E);
11139 if (LHS > RHS)
11140 return Success(CCR::Greater, E);
11141 return Success(CCR::Equal, E);
11142 }
11143
11144 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11145 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11146 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11147
11148 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11149 if (!LHSOK && !Info.noteFailure())
11150 return false;
11151 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11152 return false;
11153 if (LHSFX < RHSFX)
11154 return Success(CCR::Less, E);
11155 if (LHSFX > RHSFX)
11156 return Success(CCR::Greater, E);
11157 return Success(CCR::Equal, E);
11158 }
11159
11160 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11161 ComplexValue LHS, RHS;
11162 bool LHSOK;
11163 if (E->isAssignmentOp()) {
11164 LValue LV;
11165 EvaluateLValue(E->getLHS(), LV, Info);
11166 LHSOK = false;
11167 } else if (LHSTy->isRealFloatingType()) {
11168 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11169 if (LHSOK) {
11170 LHS.makeComplexFloat();
11171 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11172 }
11173 } else {
11174 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11175 }
11176 if (!LHSOK && !Info.noteFailure())
11177 return false;
11178
11179 if (E->getRHS()->getType()->isRealFloatingType()) {
11180 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11181 return false;
11182 RHS.makeComplexFloat();
11183 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11184 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11185 return false;
11186
11187 if (LHS.isComplexFloat()) {
11188 APFloat::cmpResult CR_r =
11189 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11190 APFloat::cmpResult CR_i =
11191 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11192 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11193 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
11194 } else {
11195 assert(IsEquality && "invalid complex comparison")((IsEquality && "invalid complex comparison") ? static_cast
<void> (0) : __assert_fail ("IsEquality && \"invalid complex comparison\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11195, __PRETTY_FUNCTION__))
;
11196 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11197 LHS.getComplexIntImag() == RHS.getComplexIntImag();
11198 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
11199 }
11200 }
11201
11202 if (LHSTy->isRealFloatingType() &&
11203 RHSTy->isRealFloatingType()) {
11204 APFloat RHS(0.0), LHS(0.0);
11205
11206 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11207 if (!LHSOK && !Info.noteFailure())
11208 return false;
11209
11210 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11211 return false;
11212
11213 assert(E->isComparisonOp() && "Invalid binary operator!")((E->isComparisonOp() && "Invalid binary operator!"
) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"Invalid binary operator!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11213, __PRETTY_FUNCTION__))
;
11214 auto GetCmpRes = [&]() {
11215 switch (LHS.compare(RHS)) {
11216 case APFloat::cmpEqual:
11217 return CCR::Equal;
11218 case APFloat::cmpLessThan:
11219 return CCR::Less;
11220 case APFloat::cmpGreaterThan:
11221 return CCR::Greater;
11222 case APFloat::cmpUnordered:
11223 return CCR::Unordered;
11224 }
11225 llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11225)
;
11226 };
11227 return Success(GetCmpRes(), E);
11228 }
11229
11230 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11231 LValue LHSValue, RHSValue;
11232
11233 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11234 if (!LHSOK && !Info.noteFailure())
11235 return false;
11236
11237 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11238 return false;
11239
11240 // Reject differing bases from the normal codepath; we special-case
11241 // comparisons to null.
11242 if (!HasSameBase(LHSValue, RHSValue)) {
11243 // Inequalities and subtractions between unrelated pointers have
11244 // unspecified or undefined behavior.
11245 if (!IsEquality)
11246 return Error(E);
11247 // A constant address may compare equal to the address of a symbol.
11248 // The one exception is that address of an object cannot compare equal
11249 // to a null pointer constant.
11250 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11251 (!RHSValue.Base && !RHSValue.Offset.isZero()))
11252 return Error(E);
11253 // It's implementation-defined whether distinct literals will have
11254 // distinct addresses. In clang, the result of such a comparison is
11255 // unspecified, so it is not a constant expression. However, we do know
11256 // that the address of a literal will be non-null.
11257 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11258 LHSValue.Base && RHSValue.Base)
11259 return Error(E);
11260 // We can't tell whether weak symbols will end up pointing to the same
11261 // object.
11262 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11263 return Error(E);
11264 // We can't compare the address of the start of one object with the
11265 // past-the-end address of another object, per C++ DR1652.
11266 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11267 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11268 (RHSValue.Base && RHSValue.Offset.isZero() &&
11269 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11270 return Error(E);
11271 // We can't tell whether an object is at the same address as another
11272 // zero sized object.
11273 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11274 (LHSValue.Base && isZeroSized(RHSValue)))
11275 return Error(E);
11276 return Success(CCR::Nonequal, E);
11277 }
11278
11279 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11280 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11281
11282 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11283 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11284
11285 // C++11 [expr.rel]p3:
11286 // Pointers to void (after pointer conversions) can be compared, with a
11287 // result defined as follows: If both pointers represent the same
11288 // address or are both the null pointer value, the result is true if the
11289 // operator is <= or >= and false otherwise; otherwise the result is
11290 // unspecified.
11291 // We interpret this as applying to pointers to *cv* void.
11292 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11293 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11294
11295 // C++11 [expr.rel]p2:
11296 // - If two pointers point to non-static data members of the same object,
11297 // or to subobjects or array elements fo such members, recursively, the
11298 // pointer to the later declared member compares greater provided the
11299 // two members have the same access control and provided their class is
11300 // not a union.
11301 // [...]
11302 // - Otherwise pointer comparisons are unspecified.
11303 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11304 bool WasArrayIndex;
11305 unsigned Mismatch = FindDesignatorMismatch(
11306 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11307 // At the point where the designators diverge, the comparison has a
11308 // specified value if:
11309 // - we are comparing array indices
11310 // - we are comparing fields of a union, or fields with the same access
11311 // Otherwise, the result is unspecified and thus the comparison is not a
11312 // constant expression.
11313 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11314 Mismatch < RHSDesignator.Entries.size()) {
11315 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11316 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11317 if (!LF && !RF)
11318 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11319 else if (!LF)
11320 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11321 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11322 << RF->getParent() << RF;
11323 else if (!RF)
11324 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11325 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11326 << LF->getParent() << LF;
11327 else if (!LF->getParent()->isUnion() &&
11328 LF->getAccess() != RF->getAccess())
11329 Info.CCEDiag(E,
11330 diag::note_constexpr_pointer_comparison_differing_access)
11331 << LF << LF->getAccess() << RF << RF->getAccess()
11332 << LF->getParent();
11333 }
11334 }
11335
11336 // The comparison here must be unsigned, and performed with the same
11337 // width as the pointer.
11338 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11339 uint64_t CompareLHS = LHSOffset.getQuantity();
11340 uint64_t CompareRHS = RHSOffset.getQuantity();
11341 assert(PtrSize <= 64 && "Unexpected pointer width")((PtrSize <= 64 && "Unexpected pointer width") ? static_cast
<void> (0) : __assert_fail ("PtrSize <= 64 && \"Unexpected pointer width\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11341, __PRETTY_FUNCTION__))
;
11342 uint64_t Mask = ~0ULL >> (64 - PtrSize);
11343 CompareLHS &= Mask;
11344 CompareRHS &= Mask;
11345
11346 // If there is a base and this is a relational operator, we can only
11347 // compare pointers within the object in question; otherwise, the result
11348 // depends on where the object is located in memory.
11349 if (!LHSValue.Base.isNull() && IsRelational) {
11350 QualType BaseTy = getType(LHSValue.Base);
11351 if (BaseTy->isIncompleteType())
11352 return Error(E);
11353 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11354 uint64_t OffsetLimit = Size.getQuantity();
11355 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11356 return Error(E);
11357 }
11358
11359 if (CompareLHS < CompareRHS)
11360 return Success(CCR::Less, E);
11361 if (CompareLHS > CompareRHS)
11362 return Success(CCR::Greater, E);
11363 return Success(CCR::Equal, E);
11364 }
11365
11366 if (LHSTy->isMemberPointerType()) {
11367 assert(IsEquality && "unexpected member pointer operation")((IsEquality && "unexpected member pointer operation"
) ? static_cast<void> (0) : __assert_fail ("IsEquality && \"unexpected member pointer operation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11367, __PRETTY_FUNCTION__))
;
11368 assert(RHSTy->isMemberPointerType() && "invalid comparison")((RHSTy->isMemberPointerType() && "invalid comparison"
) ? static_cast<void> (0) : __assert_fail ("RHSTy->isMemberPointerType() && \"invalid comparison\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11368, __PRETTY_FUNCTION__))
;
11369
11370 MemberPtr LHSValue, RHSValue;
11371
11372 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
11373 if (!LHSOK && !Info.noteFailure())
11374 return false;
11375
11376 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11377 return false;
11378
11379 // C++11 [expr.eq]p2:
11380 // If both operands are null, they compare equal. Otherwise if only one is
11381 // null, they compare unequal.
11382 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11383 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
11384 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
11385 }
11386
11387 // Otherwise if either is a pointer to a virtual member function, the
11388 // result is unspecified.
11389 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11390 if (MD->isVirtual())
11391 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
11392 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11393 if (MD->isVirtual())
11394 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
11395
11396 // Otherwise they compare equal if and only if they would refer to the
11397 // same member of the same most derived object or the same subobject if
11398 // they were dereferenced with a hypothetical object of the associated
11399 // class type.
11400 bool Equal = LHSValue == RHSValue;
11401 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
11402 }
11403
11404 if (LHSTy->isNullPtrType()) {
11405 assert(E->isComparisonOp() && "unexpected nullptr operation")((E->isComparisonOp() && "unexpected nullptr operation"
) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"unexpected nullptr operation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11405, __PRETTY_FUNCTION__))
;
11406 assert(RHSTy->isNullPtrType() && "missing pointer conversion")((RHSTy->isNullPtrType() && "missing pointer conversion"
) ? static_cast<void> (0) : __assert_fail ("RHSTy->isNullPtrType() && \"missing pointer conversion\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11406, __PRETTY_FUNCTION__))
;
11407 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
11408 // are compared, the result is true of the operator is <=, >= or ==, and
11409 // false otherwise.
11410 return Success(CCR::Equal, E);
11411 }
11412
11413 return DoAfter();
11414}
11415
11416bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
11417 if (!CheckLiteralType(Info, E))
11418 return false;
11419
11420 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11421 const BinaryOperator *E) {
11422 // Evaluation succeeded. Lookup the information for the comparison category
11423 // type and fetch the VarDecl for the result.
11424 const ComparisonCategoryInfo &CmpInfo =
11425 Info.Ctx.CompCategories.getInfoForType(E->getType());
11426 const VarDecl *VD =
11427 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
11428 // Check and evaluate the result as a constant expression.
11429 LValue LV;
11430 LV.set(VD);
11431 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11432 return false;
11433 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11434 };
11435 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11436 return ExprEvaluatorBaseTy::VisitBinCmp(E);
11437 });
11438}
11439
11440bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11441 // We don't call noteFailure immediately because the assignment happens after
11442 // we evaluate LHS and RHS.
11443 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11444 return Error(E);
11445
11446 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11447 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11448 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11449
11450 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||(((!E->getLHS()->getType()->isIntegralOrEnumerationType
() || !E->getRHS()->getType()->isIntegralOrEnumerationType
()) && "DataRecursiveIntBinOpEvaluator should have handled integral types"
) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11452, __PRETTY_FUNCTION__))
11451 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&(((!E->getLHS()->getType()->isIntegralOrEnumerationType
() || !E->getRHS()->getType()->isIntegralOrEnumerationType
()) && "DataRecursiveIntBinOpEvaluator should have handled integral types"
) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11452, __PRETTY_FUNCTION__))
11452 "DataRecursiveIntBinOpEvaluator should have handled integral types")(((!E->getLHS()->getType()->isIntegralOrEnumerationType
() || !E->getRHS()->getType()->isIntegralOrEnumerationType
()) && "DataRecursiveIntBinOpEvaluator should have handled integral types"
) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11452, __PRETTY_FUNCTION__))
;
11453
11454 if (E->isComparisonOp()) {
11455 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11456 // comparisons and then translating the result.
11457 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11458 const BinaryOperator *E) {
11459 using CCR = ComparisonCategoryResult;
11460 bool IsEqual = ResKind == CCR::Equal,
11461 IsLess = ResKind == CCR::Less,
11462 IsGreater = ResKind == CCR::Greater;
11463 auto Op = E->getOpcode();
11464 switch (Op) {
11465 default:
11466 llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11466)
;
11467 case BO_EQ:
11468 case BO_NE:
11469 return Success(IsEqual == (Op == BO_EQ), E);
11470 case BO_LT: return Success(IsLess, E);
11471 case BO_GT: return Success(IsGreater, E);
11472 case BO_LE: return Success(IsEqual || IsLess, E);
11473 case BO_GE: return Success(IsEqual || IsGreater, E);
11474 }
11475 };
11476 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11477 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11478 });
11479 }
11480
11481 QualType LHSTy = E->getLHS()->getType();
11482 QualType RHSTy = E->getRHS()->getType();
11483
11484 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11485 E->getOpcode() == BO_Sub) {
11486 LValue LHSValue, RHSValue;
11487
11488 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11489 if (!LHSOK && !Info.noteFailure())
11490 return false;
11491
11492 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11493 return false;
11494
11495 // Reject differing bases from the normal codepath; we special-case
11496 // comparisons to null.
11497 if (!HasSameBase(LHSValue, RHSValue)) {
11498 // Handle &&A - &&B.
11499 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11500 return Error(E);
11501 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11502 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11503 if (!LHSExpr || !RHSExpr)
11504 return Error(E);
11505 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11506 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11507 if (!LHSAddrExpr || !RHSAddrExpr)
11508 return Error(E);
11509 // Make sure both labels come from the same function.
11510 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11511 RHSAddrExpr->getLabel()->getDeclContext())
11512 return Error(E);
11513 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11514 }
11515 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11516 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11517
11518 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11519 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11520
11521 // C++11 [expr.add]p6:
11522 // Unless both pointers point to elements of the same array object, or
11523 // one past the last element of the array object, the behavior is
11524 // undefined.
11525 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11526 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11527 RHSDesignator))
11528 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11529
11530 QualType Type = E->getLHS()->getType();
11531 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
11532
11533 CharUnits ElementSize;
11534 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11535 return false;
11536
11537 // As an extension, a type may have zero size (empty struct or union in
11538 // C, array of zero length). Pointer subtraction in such cases has
11539 // undefined behavior, so is not constant.
11540 if (ElementSize.isZero()) {
11541 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11542 << ElementType;
11543 return false;
11544 }
11545
11546 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11547 // and produce incorrect results when it overflows. Such behavior
11548 // appears to be non-conforming, but is common, so perhaps we should
11549 // assume the standard intended for such cases to be undefined behavior
11550 // and check for them.
11551
11552 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11553 // overflow in the final conversion to ptrdiff_t.
11554 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11555 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11556 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11557 false);
11558 APSInt TrueResult = (LHS - RHS) / ElemSize;
11559 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11560
11561 if (Result.extend(65) != TrueResult &&
11562 !HandleOverflow(Info, E, TrueResult, E->getType()))
11563 return false;
11564 return Success(Result, E);
11565 }
11566
11567 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11568}
11569
11570/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11571/// a result as the expression's type.
11572bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11573 const UnaryExprOrTypeTraitExpr *E) {
11574 switch(E->getKind()) {
11575 case UETT_PreferredAlignOf:
11576 case UETT_AlignOf: {
11577 if (E->isArgumentType())
11578 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11579 E);
11580 else
11581 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11582 E);
11583 }
11584
11585 case UETT_VecStep: {
11586 QualType Ty = E->getTypeOfArgument();
11587
11588 if (Ty->isVectorType()) {
11589 unsigned n = Ty->castAs<VectorType>()->getNumElements();
11590
11591 // The vec_step built-in functions that take a 3-component
11592 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11593 if (n == 3)
11594 n = 4;
11595
11596 return Success(n, E);
11597 } else
11598 return Success(1, E);
11599 }
11600
11601 case UETT_SizeOf: {
11602 QualType SrcTy = E->getTypeOfArgument();
11603 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11604 // the result is the size of the referenced type."
11605 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11606 SrcTy = Ref->getPointeeType();
11607
11608 CharUnits Sizeof;
11609 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
11610 return false;
11611 return Success(Sizeof, E);
11612 }
11613 case UETT_OpenMPRequiredSimdAlign:
11614 assert(E->isArgumentType())((E->isArgumentType()) ? static_cast<void> (0) : __assert_fail
("E->isArgumentType()", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11614, __PRETTY_FUNCTION__))
;
11615 return Success(
11616 Info.Ctx.toCharUnitsFromBits(
11617 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11618 .getQuantity(),
11619 E);
11620 }
11621
11622 llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11622)
;
11623}
11624
11625bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
11626 CharUnits Result;
11627 unsigned n = OOE->getNumComponents();
11628 if (n == 0)
11629 return Error(OOE);
11630 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
11631 for (unsigned i = 0; i != n; ++i) {
11632 OffsetOfNode ON = OOE->getComponent(i);
11633 switch (ON.getKind()) {
11634 case OffsetOfNode::Array: {
11635 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
11636 APSInt IdxResult;
11637 if (!EvaluateInteger(Idx, IdxResult, Info))
11638 return false;
11639 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11640 if (!AT)
11641 return Error(OOE);
11642 CurrentType = AT->getElementType();
11643 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11644 Result += IdxResult.getSExtValue() * ElementSize;
11645 break;
11646 }
11647
11648 case OffsetOfNode::Field: {
11649 FieldDecl *MemberDecl = ON.getField();
11650 const RecordType *RT = CurrentType->getAs<RecordType>();
11651 if (!RT)
11652 return Error(OOE);
11653 RecordDecl *RD = RT->getDecl();
11654 if (RD->isInvalidDecl()) return false;
11655 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11656 unsigned i = MemberDecl->getFieldIndex();
11657 assert(i < RL.getFieldCount() && "offsetof field in wrong type")((i < RL.getFieldCount() && "offsetof field in wrong type"
) ? static_cast<void> (0) : __assert_fail ("i < RL.getFieldCount() && \"offsetof field in wrong type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11657, __PRETTY_FUNCTION__))
;
11658 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
11659 CurrentType = MemberDecl->getType().getNonReferenceType();
11660 break;
11661 }
11662
11663 case OffsetOfNode::Identifier:
11664 llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11664)
;
11665
11666 case OffsetOfNode::Base: {
11667 CXXBaseSpecifier *BaseSpec = ON.getBase();
11668 if (BaseSpec->isVirtual())
11669 return Error(OOE);
11670
11671 // Find the layout of the class whose base we are looking into.
11672 const RecordType *RT = CurrentType->getAs<RecordType>();
11673 if (!RT)
11674 return Error(OOE);
11675 RecordDecl *RD = RT->getDecl();
11676 if (RD->isInvalidDecl()) return false;
11677 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
11678
11679 // Find the base class itself.
11680 CurrentType = BaseSpec->getType();
11681 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
11682 if (!BaseRT)
11683 return Error(OOE);
11684
11685 // Add the offset to the base.
11686 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
11687 break;
11688 }
11689 }
11690 }
11691 return Success(Result, OOE);
11692}
11693
11694bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11695 switch (E->getOpcode()) {
11696 default:
11697 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11698 // See C99 6.6p3.
11699 return Error(E);
11700 case UO_Extension:
11701 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11702 // If so, we could clear the diagnostic ID.
11703 return Visit(E->getSubExpr());
11704 case UO_Plus:
11705 // The result is just the value.
11706 return Visit(E->getSubExpr());
11707 case UO_Minus: {
11708 if (!Visit(E->getSubExpr()))
11709 return false;
11710 if (!Result.isInt()) return Error(E);
11711 const APSInt &Value = Result.getInt();
11712 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11713 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11714 E->getType()))
11715 return false;
11716 return Success(-Value, E);
11717 }
11718 case UO_Not: {
11719 if (!Visit(E->getSubExpr()))
11720 return false;
11721 if (!Result.isInt()) return Error(E);
11722 return Success(~Result.getInt(), E);
11723 }
11724 case UO_LNot: {
11725 bool bres;
11726 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11727 return false;
11728 return Success(!bres, E);
11729 }
11730 }
11731}
11732
11733/// HandleCast - This is used to evaluate implicit or explicit casts where the
11734/// result type is integer.
11735bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11736 const Expr *SubExpr = E->getSubExpr();
11737 QualType DestType = E->getType();
11738 QualType SrcType = SubExpr->getType();
11739
11740 switch (E->getCastKind()) {
11741 case CK_BaseToDerived:
11742 case CK_DerivedToBase:
11743 case CK_UncheckedDerivedToBase:
11744 case CK_Dynamic:
11745 case CK_ToUnion:
11746 case CK_ArrayToPointerDecay:
11747 case CK_FunctionToPointerDecay:
11748 case CK_NullToPointer:
11749 case CK_NullToMemberPointer:
11750 case CK_BaseToDerivedMemberPointer:
11751 case CK_DerivedToBaseMemberPointer:
11752 case CK_ReinterpretMemberPointer:
11753 case CK_ConstructorConversion:
11754 case CK_IntegralToPointer:
11755 case CK_ToVoid:
11756 case CK_VectorSplat:
11757 case CK_IntegralToFloating:
11758 case CK_FloatingCast:
11759 case CK_CPointerToObjCPointerCast:
11760 case CK_BlockPointerToObjCPointerCast:
11761 case CK_AnyPointerToBlockPointerCast:
11762 case CK_ObjCObjectLValueCast:
11763 case CK_FloatingRealToComplex:
11764 case CK_FloatingComplexToReal:
11765 case CK_FloatingComplexCast:
11766 case CK_FloatingComplexToIntegralComplex:
11767 case CK_IntegralRealToComplex:
11768 case CK_IntegralComplexCast:
11769 case CK_IntegralComplexToFloatingComplex:
11770 case CK_BuiltinFnToFnPtr:
11771 case CK_ZeroToOCLOpaqueType:
11772 case CK_NonAtomicToAtomic:
11773 case CK_AddressSpaceConversion:
11774 case CK_IntToOCLSampler:
11775 case CK_FixedPointCast:
11776 case CK_IntegralToFixedPoint:
11777 llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11777)
;
11778
11779 case CK_BitCast:
11780 case CK_Dependent:
11781 case CK_LValueBitCast:
11782 case CK_ARCProduceObject:
11783 case CK_ARCConsumeObject:
11784 case CK_ARCReclaimReturnedObject:
11785 case CK_ARCExtendBlockObject:
11786 case CK_CopyAndAutoreleaseBlockObject:
11787 return Error(E);
11788
11789 case CK_UserDefinedConversion:
11790 case CK_LValueToRValue:
11791 case CK_AtomicToNonAtomic:
11792 case CK_NoOp:
11793 case CK_LValueToRValueBitCast:
11794 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11795
11796 case CK_MemberPointerToBoolean:
11797 case CK_PointerToBoolean:
11798 case CK_IntegralToBoolean:
11799 case CK_FloatingToBoolean:
11800 case CK_BooleanToSignedIntegral:
11801 case CK_FloatingComplexToBoolean:
11802 case CK_IntegralComplexToBoolean: {
11803 bool BoolResult;
11804 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11805 return false;
11806 uint64_t IntResult = BoolResult;
11807 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11808 IntResult = (uint64_t)-1;
11809 return Success(IntResult, E);
11810 }
11811
11812 case CK_FixedPointToIntegral: {
11813 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11814 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11815 return false;
11816 bool Overflowed;
11817 llvm::APSInt Result = Src.convertToInt(
11818 Info.Ctx.getIntWidth(DestType),
11819 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11820 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11821 return false;
11822 return Success(Result, E);
11823 }
11824
11825 case CK_FixedPointToBoolean: {
11826 // Unsigned padding does not affect this.
11827 APValue Val;
11828 if (!Evaluate(Val, Info, SubExpr))
11829 return false;
11830 return Success(Val.getFixedPoint().getBoolValue(), E);
11831 }
11832
11833 case CK_IntegralCast: {
11834 if (!Visit(SubExpr))
11835 return false;
11836
11837 if (!Result.isInt()) {
11838 // Allow casts of address-of-label differences if they are no-ops
11839 // or narrowing. (The narrowing case isn't actually guaranteed to
11840 // be constant-evaluatable except in some narrow cases which are hard
11841 // to detect here. We let it through on the assumption the user knows
11842 // what they are doing.)
11843 if (Result.isAddrLabelDiff())
11844 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11845 // Only allow casts of lvalues if they are lossless.
11846 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11847 }
11848
11849 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11850 Result.getInt()), E);
11851 }
11852
11853 case CK_PointerToIntegral: {
11854 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11855
11856 LValue LV;
11857 if (!EvaluatePointer(SubExpr, LV, Info))
11858 return false;
11859
11860 if (LV.getLValueBase()) {
11861 // Only allow based lvalue casts if they are lossless.
11862 // FIXME: Allow a larger integer size than the pointer size, and allow
11863 // narrowing back down to pointer width in subsequent integral casts.
11864 // FIXME: Check integer type's active bits, not its type size.
11865 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11866 return Error(E);
11867
11868 LV.Designator.setInvalid();
11869 LV.moveInto(Result);
11870 return true;
11871 }
11872
11873 APSInt AsInt;
11874 APValue V;
11875 LV.moveInto(V);
11876 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11877 llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11877)
;
11878
11879 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11880 }
11881
11882 case CK_IntegralComplexToReal: {
11883 ComplexValue C;
11884 if (!EvaluateComplex(SubExpr, C, Info))
11885 return false;
11886 return Success(C.getComplexIntReal(), E);
11887 }
11888
11889 case CK_FloatingToIntegral: {
11890 APFloat F(0.0);
11891 if (!EvaluateFloat(SubExpr, F, Info))
11892 return false;
11893
11894 APSInt Value;
11895 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11896 return false;
11897 return Success(Value, E);
11898 }
11899 }
11900
11901 llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11901)
;
11902}
11903
11904bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11905 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11906 ComplexValue LV;
11907 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11908 return false;
11909 if (!LV.isComplexInt())
11910 return Error(E);
11911 return Success(LV.getComplexIntReal(), E);
11912 }
11913
11914 return Visit(E->getSubExpr());
11915}
11916
11917bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11918 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11919 ComplexValue LV;
11920 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11921 return false;
11922 if (!LV.isComplexInt())
11923 return Error(E);
11924 return Success(LV.getComplexIntImag(), E);
11925 }
11926
11927 VisitIgnoredValue(E->getSubExpr());
11928 return Success(0, E);
11929}
11930
11931bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11932 return Success(E->getPackLength(), E);
11933}
11934
11935bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11936 return Success(E->getValue(), E);
11937}
11938
11939bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11940 switch (E->getOpcode()) {
11941 default:
11942 // Invalid unary operators
11943 return Error(E);
11944 case UO_Plus:
11945 // The result is just the value.
11946 return Visit(E->getSubExpr());
11947 case UO_Minus: {
11948 if (!Visit(E->getSubExpr())) return false;
11949 if (!Result.isFixedPoint())
11950 return Error(E);
11951 bool Overflowed;
11952 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11953 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11954 return false;
11955 return Success(Negated, E);
11956 }
11957 case UO_LNot: {
11958 bool bres;
11959 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11960 return false;
11961 return Success(!bres, E);
11962 }
11963 }
11964}
11965
11966bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11967 const Expr *SubExpr = E->getSubExpr();
11968 QualType DestType = E->getType();
11969 assert(DestType->isFixedPointType() &&((DestType->isFixedPointType() && "Expected destination type to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11970, __PRETTY_FUNCTION__))
11970 "Expected destination type to be a fixed point type")((DestType->isFixedPointType() && "Expected destination type to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 11970, __PRETTY_FUNCTION__))
;
11971 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11972
11973 switch (E->getCastKind()) {
11974 case CK_FixedPointCast: {
11975 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11976 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11977 return false;
11978 bool Overflowed;
11979 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11980 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11981 return false;
11982 return Success(Result, E);
11983 }
11984 case CK_IntegralToFixedPoint: {
11985 APSInt Src;
11986 if (!EvaluateInteger(SubExpr, Src, Info))
11987 return false;
11988
11989 bool Overflowed;
11990 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11991 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11992
11993 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11994 return false;
11995
11996 return Success(IntResult, E);
11997 }
11998 case CK_NoOp:
11999 case CK_LValueToRValue:
12000 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12001 default:
12002 return Error(E);
12003 }
12004}
12005
12006bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12007 const Expr *LHS = E->getLHS();
12008 const Expr *RHS = E->getRHS();
12009 FixedPointSemantics ResultFXSema =
12010 Info.Ctx.getFixedPointSemantics(E->getType());
12011
12012 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12013 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12014 return false;
12015 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12016 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12017 return false;
12018
12019 switch (E->getOpcode()) {
12020 case BO_Add: {
12021 bool AddOverflow, ConversionOverflow;
12022 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12023 .convert(ResultFXSema, &ConversionOverflow);
12024 if ((AddOverflow || ConversionOverflow) &&
12025 !HandleOverflow(Info, E, Result, E->getType()))
12026 return false;
12027 return Success(Result, E);
12028 }
12029 default:
12030 return false;
12031 }
12032 llvm_unreachable("Should've exited before this")::llvm::llvm_unreachable_internal("Should've exited before this"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12032)
;
12033}
12034
12035//===----------------------------------------------------------------------===//
12036// Float Evaluation
12037//===----------------------------------------------------------------------===//
12038
12039namespace {
12040class FloatExprEvaluator
12041 : public ExprEvaluatorBase<FloatExprEvaluator> {
12042 APFloat &Result;
12043public:
12044 FloatExprEvaluator(EvalInfo &info, APFloat &result)
12045 : ExprEvaluatorBaseTy(info), Result(result) {}
12046
12047 bool Success(const APValue &V, const Expr *e) {
12048 Result = V.getFloat();
12049 return true;
12050 }
12051
12052 bool ZeroInitialization(const Expr *E) {
12053 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12054 return true;
12055 }
12056
12057 bool VisitCallExpr(const CallExpr *E);
12058
12059 bool VisitUnaryOperator(const UnaryOperator *E);
12060 bool VisitBinaryOperator(const BinaryOperator *E);
12061 bool VisitFloatingLiteral(const FloatingLiteral *E);
12062 bool VisitCastExpr(const CastExpr *E);
12063
12064 bool VisitUnaryReal(const UnaryOperator *E);
12065 bool VisitUnaryImag(const UnaryOperator *E);
12066
12067 // FIXME: Missing: array subscript of vector, member of vector
12068};
12069} // end anonymous namespace
12070
12071static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12072 assert(E->isRValue() && E->getType()->isRealFloatingType())((E->isRValue() && E->getType()->isRealFloatingType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRealFloatingType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12072, __PRETTY_FUNCTION__))
;
12073 return FloatExprEvaluator(Info, Result).Visit(E);
12074}
12075
12076static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12077 QualType ResultTy,
12078 const Expr *Arg,
12079 bool SNaN,
12080 llvm::APFloat &Result) {
12081 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12082 if (!S) return false;
12083
12084 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12085
12086 llvm::APInt fill;
12087
12088 // Treat empty strings as if they were zero.
12089 if (S->getString().empty())
12090 fill = llvm::APInt(32, 0);
12091 else if (S->getString().getAsInteger(0, fill))
12092 return false;
12093
12094 if (Context.getTargetInfo().isNan2008()) {
12095 if (SNaN)
12096 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12097 else
12098 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12099 } else {
12100 // Prior to IEEE 754-2008, architectures were allowed to choose whether
12101 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12102 // a different encoding to what became a standard in 2008, and for pre-
12103 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12104 // sNaN. This is now known as "legacy NaN" encoding.
12105 if (SNaN)
12106 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12107 else
12108 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12109 }
12110
12111 return true;
12112}
12113
12114bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12115 switch (E->getBuiltinCallee()) {
12116 default:
12117 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12118
12119 case Builtin::BI__builtin_huge_val:
12120 case Builtin::BI__builtin_huge_valf:
12121 case Builtin::BI__builtin_huge_vall:
12122 case Builtin::BI__builtin_huge_valf128:
12123 case Builtin::BI__builtin_inf:
12124 case Builtin::BI__builtin_inff:
12125 case Builtin::BI__builtin_infl:
12126 case Builtin::BI__builtin_inff128: {
12127 const llvm::fltSemantics &Sem =
12128 Info.Ctx.getFloatTypeSemantics(E->getType());
12129 Result = llvm::APFloat::getInf(Sem);
12130 return true;
12131 }
12132
12133 case Builtin::BI__builtin_nans:
12134 case Builtin::BI__builtin_nansf:
12135 case Builtin::BI__builtin_nansl:
12136 case Builtin::BI__builtin_nansf128:
12137 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12138 true, Result))
12139 return Error(E);
12140 return true;
12141
12142 case Builtin::BI__builtin_nan:
12143 case Builtin::BI__builtin_nanf:
12144 case Builtin::BI__builtin_nanl:
12145 case Builtin::BI__builtin_nanf128:
12146 // If this is __builtin_nan() turn this into a nan, otherwise we
12147 // can't constant fold it.
12148 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12149 false, Result))
12150 return Error(E);
12151 return true;
12152
12153 case Builtin::BI__builtin_fabs:
12154 case Builtin::BI__builtin_fabsf:
12155 case Builtin::BI__builtin_fabsl:
12156 case Builtin::BI__builtin_fabsf128:
12157 if (!EvaluateFloat(E->getArg(0), Result, Info))
12158 return false;
12159
12160 if (Result.isNegative())
12161 Result.changeSign();
12162 return true;
12163
12164 // FIXME: Builtin::BI__builtin_powi
12165 // FIXME: Builtin::BI__builtin_powif
12166 // FIXME: Builtin::BI__builtin_powil
12167
12168 case Builtin::BI__builtin_copysign:
12169 case Builtin::BI__builtin_copysignf:
12170 case Builtin::BI__builtin_copysignl:
12171 case Builtin::BI__builtin_copysignf128: {
12172 APFloat RHS(0.);
12173 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12174 !EvaluateFloat(E->getArg(1), RHS, Info))
12175 return false;
12176 Result.copySign(RHS);
12177 return true;
12178 }
12179 }
12180}
12181
12182bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12183 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12184 ComplexValue CV;
12185 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12186 return false;
12187 Result = CV.FloatReal;
12188 return true;
12189 }
12190
12191 return Visit(E->getSubExpr());
12192}
12193
12194bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12195 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12196 ComplexValue CV;
12197 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12198 return false;
12199 Result = CV.FloatImag;
12200 return true;
12201 }
12202
12203 VisitIgnoredValue(E->getSubExpr());
12204 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12205 Result = llvm::APFloat::getZero(Sem);
12206 return true;
12207}
12208
12209bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12210 switch (E->getOpcode()) {
12211 default: return Error(E);
12212 case UO_Plus:
12213 return EvaluateFloat(E->getSubExpr(), Result, Info);
12214 case UO_Minus:
12215 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12216 return false;
12217 Result.changeSign();
12218 return true;
12219 }
12220}
12221
12222bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12223 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12224 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12225
12226 APFloat RHS(0.0);
12227 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12228 if (!LHSOK && !Info.noteFailure())
12229 return false;
12230 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12231 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12232}
12233
12234bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12235 Result = E->getValue();
12236 return true;
12237}
12238
12239bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12240 const Expr* SubExpr = E->getSubExpr();
12241
12242 switch (E->getCastKind()) {
12243 default:
12244 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12245
12246 case CK_IntegralToFloating: {
12247 APSInt IntResult;
12248 return EvaluateInteger(SubExpr, IntResult, Info) &&
12249 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12250 E->getType(), Result);
12251 }
12252
12253 case CK_FloatingCast: {
12254 if (!Visit(SubExpr))
12255 return false;
12256 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12257 Result);
12258 }
12259
12260 case CK_FloatingComplexToReal: {
12261 ComplexValue V;
12262 if (!EvaluateComplex(SubExpr, V, Info))
12263 return false;
12264 Result = V.getComplexFloatReal();
12265 return true;
12266 }
12267 }
12268}
12269
12270//===----------------------------------------------------------------------===//
12271// Complex Evaluation (for float and integer)
12272//===----------------------------------------------------------------------===//
12273
12274namespace {
12275class ComplexExprEvaluator
12276 : public ExprEvaluatorBase<ComplexExprEvaluator> {
12277 ComplexValue &Result;
12278
12279public:
12280 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12281 : ExprEvaluatorBaseTy(info), Result(Result) {}
12282
12283 bool Success(const APValue &V, const Expr *e) {
12284 Result.setFrom(V);
12285 return true;
12286 }
12287
12288 bool ZeroInitialization(const Expr *E);
12289
12290 //===--------------------------------------------------------------------===//
12291 // Visitor Methods
12292 //===--------------------------------------------------------------------===//
12293
12294 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12295 bool VisitCastExpr(const CastExpr *E);
12296 bool VisitBinaryOperator(const BinaryOperator *E);
12297 bool VisitUnaryOperator(const UnaryOperator *E);
12298 bool VisitInitListExpr(const InitListExpr *E);
12299};
12300} // end anonymous namespace
12301
12302static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12303 EvalInfo &Info) {
12304 assert(E->isRValue() && E->getType()->isAnyComplexType())((E->isRValue() && E->getType()->isAnyComplexType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isAnyComplexType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12304, __PRETTY_FUNCTION__))
;
12305 return ComplexExprEvaluator(Info, Result).Visit(E);
12306}
12307
12308bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12309 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12310 if (ElemTy->isRealFloatingType()) {
12311 Result.makeComplexFloat();
12312 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12313 Result.FloatReal = Zero;
12314 Result.FloatImag = Zero;
12315 } else {
12316 Result.makeComplexInt();
12317 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12318 Result.IntReal = Zero;
12319 Result.IntImag = Zero;
12320 }
12321 return true;
12322}
12323
12324bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12325 const Expr* SubExpr = E->getSubExpr();
12326
12327 if (SubExpr->getType()->isRealFloatingType()) {
12328 Result.makeComplexFloat();
12329 APFloat &Imag = Result.FloatImag;
12330 if (!EvaluateFloat(SubExpr, Imag, Info))
12331 return false;
12332
12333 Result.FloatReal = APFloat(Imag.getSemantics());
12334 return true;
12335 } else {
12336 assert(SubExpr->getType()->isIntegerType() &&((SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal."
) ? static_cast<void> (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12337, __PRETTY_FUNCTION__))
12337 "Unexpected imaginary literal.")((SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal."
) ? static_cast<void> (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12337, __PRETTY_FUNCTION__))
;
12338
12339 Result.makeComplexInt();
12340 APSInt &Imag = Result.IntImag;
12341 if (!EvaluateInteger(SubExpr, Imag, Info))
12342 return false;
12343
12344 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12345 return true;
12346 }
12347}
12348
12349bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
12350
12351 switch (E->getCastKind()) {
12352 case CK_BitCast:
12353 case CK_BaseToDerived:
12354 case CK_DerivedToBase:
12355 case CK_UncheckedDerivedToBase:
12356 case CK_Dynamic:
12357 case CK_ToUnion:
12358 case CK_ArrayToPointerDecay:
12359 case CK_FunctionToPointerDecay:
12360 case CK_NullToPointer:
12361 case CK_NullToMemberPointer:
12362 case CK_BaseToDerivedMemberPointer:
12363 case CK_DerivedToBaseMemberPointer:
12364 case CK_MemberPointerToBoolean:
12365 case CK_ReinterpretMemberPointer:
12366 case CK_ConstructorConversion:
12367 case CK_IntegralToPointer:
12368 case CK_PointerToIntegral:
12369 case CK_PointerToBoolean:
12370 case CK_ToVoid:
12371 case CK_VectorSplat:
12372 case CK_IntegralCast:
12373 case CK_BooleanToSignedIntegral:
12374 case CK_IntegralToBoolean:
12375 case CK_IntegralToFloating:
12376 case CK_FloatingToIntegral:
12377 case CK_FloatingToBoolean:
12378 case CK_FloatingCast:
12379 case CK_CPointerToObjCPointerCast:
12380 case CK_BlockPointerToObjCPointerCast:
12381 case CK_AnyPointerToBlockPointerCast:
12382 case CK_ObjCObjectLValueCast:
12383 case CK_FloatingComplexToReal:
12384 case CK_FloatingComplexToBoolean:
12385 case CK_IntegralComplexToReal:
12386 case CK_IntegralComplexToBoolean:
12387 case CK_ARCProduceObject:
12388 case CK_ARCConsumeObject:
12389 case CK_ARCReclaimReturnedObject:
12390 case CK_ARCExtendBlockObject:
12391 case CK_CopyAndAutoreleaseBlockObject:
12392 case CK_BuiltinFnToFnPtr:
12393 case CK_ZeroToOCLOpaqueType:
12394 case CK_NonAtomicToAtomic:
12395 case CK_AddressSpaceConversion:
12396 case CK_IntToOCLSampler:
12397 case CK_FixedPointCast:
12398 case CK_FixedPointToBoolean:
12399 case CK_FixedPointToIntegral:
12400 case CK_IntegralToFixedPoint:
12401 llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12401)
;
12402
12403 case CK_LValueToRValue:
12404 case CK_AtomicToNonAtomic:
12405 case CK_NoOp:
12406 case CK_LValueToRValueBitCast:
12407 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12408
12409 case CK_Dependent:
12410 case CK_LValueBitCast:
12411 case CK_UserDefinedConversion:
12412 return Error(E);
12413
12414 case CK_FloatingRealToComplex: {
12415 APFloat &Real = Result.FloatReal;
12416 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
12417 return false;
12418
12419 Result.makeComplexFloat();
12420 Result.FloatImag = APFloat(Real.getSemantics());
12421 return true;
12422 }
12423
12424 case CK_FloatingComplexCast: {
12425 if (!Visit(E->getSubExpr()))
12426 return false;
12427
12428 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12429 QualType From
12430 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12431
12432 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
12433 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
12434 }
12435
12436 case CK_FloatingComplexToIntegralComplex: {
12437 if (!Visit(E->getSubExpr()))
12438 return false;
12439
12440 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12441 QualType From
12442 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12443 Result.makeComplexInt();
12444 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12445 To, Result.IntReal) &&
12446 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12447 To, Result.IntImag);
12448 }
12449
12450 case CK_IntegralRealToComplex: {
12451 APSInt &Real = Result.IntReal;
12452 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12453 return false;
12454
12455 Result.makeComplexInt();
12456 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12457 return true;
12458 }
12459
12460 case CK_IntegralComplexCast: {
12461 if (!Visit(E->getSubExpr()))
12462 return false;
12463
12464 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
12465 QualType From
12466 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
12467
12468 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12469 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
12470 return true;
12471 }
12472
12473 case CK_IntegralComplexToFloatingComplex: {
12474 if (!Visit(E->getSubExpr()))
12475 return false;
12476
12477 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
12478 QualType From
12479 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
12480 Result.makeComplexFloat();
12481 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12482 To, Result.FloatReal) &&
12483 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12484 To, Result.FloatImag);
12485 }
12486 }
12487
12488 llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12488)
;
12489}
12490
12491bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12492 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12493 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12494
12495 // Track whether the LHS or RHS is real at the type system level. When this is
12496 // the case we can simplify our evaluation strategy.
12497 bool LHSReal = false, RHSReal = false;
12498
12499 bool LHSOK;
12500 if (E->getLHS()->getType()->isRealFloatingType()) {
12501 LHSReal = true;
12502 APFloat &Real = Result.FloatReal;
12503 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12504 if (LHSOK) {
12505 Result.makeComplexFloat();
12506 Result.FloatImag = APFloat(Real.getSemantics());
12507 }
12508 } else {
12509 LHSOK = Visit(E->getLHS());
12510 }
12511 if (!LHSOK && !Info.noteFailure())
12512 return false;
12513
12514 ComplexValue RHS;
12515 if (E->getRHS()->getType()->isRealFloatingType()) {
12516 RHSReal = true;
12517 APFloat &Real = RHS.FloatReal;
12518 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12519 return false;
12520 RHS.makeComplexFloat();
12521 RHS.FloatImag = APFloat(Real.getSemantics());
12522 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12523 return false;
12524
12525 assert(!(LHSReal && RHSReal) &&((!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real."
) ? static_cast<void> (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12526, __PRETTY_FUNCTION__))
12526 "Cannot have both operands of a complex operation be real.")((!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real."
) ? static_cast<void> (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12526, __PRETTY_FUNCTION__))
;
12527 switch (E->getOpcode()) {
12528 default: return Error(E);
12529 case BO_Add:
12530 if (Result.isComplexFloat()) {
12531 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12532 APFloat::rmNearestTiesToEven);
12533 if (LHSReal)
12534 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12535 else if (!RHSReal)
12536 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12537 APFloat::rmNearestTiesToEven);
12538 } else {
12539 Result.getComplexIntReal() += RHS.getComplexIntReal();
12540 Result.getComplexIntImag() += RHS.getComplexIntImag();
12541 }
12542 break;
12543 case BO_Sub:
12544 if (Result.isComplexFloat()) {
12545 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12546 APFloat::rmNearestTiesToEven);
12547 if (LHSReal) {
12548 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12549 Result.getComplexFloatImag().changeSign();
12550 } else if (!RHSReal) {
12551 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12552 APFloat::rmNearestTiesToEven);
12553 }
12554 } else {
12555 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12556 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12557 }
12558 break;
12559 case BO_Mul:
12560 if (Result.isComplexFloat()) {
12561 // This is an implementation of complex multiplication according to the
12562 // constraints laid out in C11 Annex G. The implementation uses the
12563 // following naming scheme:
12564 // (a + ib) * (c + id)
12565 ComplexValue LHS = Result;
12566 APFloat &A = LHS.getComplexFloatReal();
12567 APFloat &B = LHS.getComplexFloatImag();
12568 APFloat &C = RHS.getComplexFloatReal();
12569 APFloat &D = RHS.getComplexFloatImag();
12570 APFloat &ResR = Result.getComplexFloatReal();
12571 APFloat &ResI = Result.getComplexFloatImag();
12572 if (LHSReal) {
12573 assert(!RHSReal && "Cannot have two real operands for a complex op!")((!RHSReal && "Cannot have two real operands for a complex op!"
) ? static_cast<void> (0) : __assert_fail ("!RHSReal && \"Cannot have two real operands for a complex op!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12573, __PRETTY_FUNCTION__))
;
12574 ResR = A * C;
12575 ResI = A * D;
12576 } else if (RHSReal) {
12577 ResR = C * A;
12578 ResI = C * B;
12579 } else {
12580 // In the fully general case, we need to handle NaNs and infinities
12581 // robustly.
12582 APFloat AC = A * C;
12583 APFloat BD = B * D;
12584 APFloat AD = A * D;
12585 APFloat BC = B * C;
12586 ResR = AC - BD;
12587 ResI = AD + BC;
12588 if (ResR.isNaN() && ResI.isNaN()) {
12589 bool Recalc = false;
12590 if (A.isInfinity() || B.isInfinity()) {
12591 A = APFloat::copySign(
12592 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12593 B = APFloat::copySign(
12594 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12595 if (C.isNaN())
12596 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12597 if (D.isNaN())
12598 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12599 Recalc = true;
12600 }
12601 if (C.isInfinity() || D.isInfinity()) {
12602 C = APFloat::copySign(
12603 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12604 D = APFloat::copySign(
12605 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12606 if (A.isNaN())
12607 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12608 if (B.isNaN())
12609 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12610 Recalc = true;
12611 }
12612 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12613 AD.isInfinity() || BC.isInfinity())) {
12614 if (A.isNaN())
12615 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12616 if (B.isNaN())
12617 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12618 if (C.isNaN())
12619 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12620 if (D.isNaN())
12621 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12622 Recalc = true;
12623 }
12624 if (Recalc) {
12625 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12626 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12627 }
12628 }
12629 }
12630 } else {
12631 ComplexValue LHS = Result;
12632 Result.getComplexIntReal() =
12633 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12634 LHS.getComplexIntImag() * RHS.getComplexIntImag());
12635 Result.getComplexIntImag() =
12636 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12637 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12638 }
12639 break;
12640 case BO_Div:
12641 if (Result.isComplexFloat()) {
12642 // This is an implementation of complex division according to the
12643 // constraints laid out in C11 Annex G. The implementation uses the
12644 // following naming scheme:
12645 // (a + ib) / (c + id)
12646 ComplexValue LHS = Result;
12647 APFloat &A = LHS.getComplexFloatReal();
12648 APFloat &B = LHS.getComplexFloatImag();
12649 APFloat &C = RHS.getComplexFloatReal();
12650 APFloat &D = RHS.getComplexFloatImag();
12651 APFloat &ResR = Result.getComplexFloatReal();
12652 APFloat &ResI = Result.getComplexFloatImag();
12653 if (RHSReal) {
12654 ResR = A / C;
12655 ResI = B / C;
12656 } else {
12657 if (LHSReal) {
12658 // No real optimizations we can do here, stub out with zero.
12659 B = APFloat::getZero(A.getSemantics());
12660 }
12661 int DenomLogB = 0;
12662 APFloat MaxCD = maxnum(abs(C), abs(D));
12663 if (MaxCD.isFinite()) {
12664 DenomLogB = ilogb(MaxCD);
12665 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
12666 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
12667 }
12668 APFloat Denom = C * C + D * D;
12669 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
12670 APFloat::rmNearestTiesToEven);
12671 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
12672 APFloat::rmNearestTiesToEven);
12673 if (ResR.isNaN() && ResI.isNaN()) {
12674 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
12675 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
12676 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
12677 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
12678 D.isFinite()) {
12679 A = APFloat::copySign(
12680 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12681 B = APFloat::copySign(
12682 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12683 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
12684 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
12685 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
12686 C = APFloat::copySign(
12687 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12688 D = APFloat::copySign(
12689 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12690 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
12691 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12692 }
12693 }
12694 }
12695 } else {
12696 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12697 return Error(E, diag::note_expr_divide_by_zero);
12698
12699 ComplexValue LHS = Result;
12700 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12701 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12702 Result.getComplexIntReal() =
12703 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12704 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12705 Result.getComplexIntImag() =
12706 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12707 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12708 }
12709 break;
12710 }
12711
12712 return true;
12713}
12714
12715bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12716 // Get the operand value into 'Result'.
12717 if (!Visit(E->getSubExpr()))
12718 return false;
12719
12720 switch (E->getOpcode()) {
12721 default:
12722 return Error(E);
12723 case UO_Extension:
12724 return true;
12725 case UO_Plus:
12726 // The result is always just the subexpr.
12727 return true;
12728 case UO_Minus:
12729 if (Result.isComplexFloat()) {
12730 Result.getComplexFloatReal().changeSign();
12731 Result.getComplexFloatImag().changeSign();
12732 }
12733 else {
12734 Result.getComplexIntReal() = -Result.getComplexIntReal();
12735 Result.getComplexIntImag() = -Result.getComplexIntImag();
12736 }
12737 return true;
12738 case UO_Not:
12739 if (Result.isComplexFloat())
12740 Result.getComplexFloatImag().changeSign();
12741 else
12742 Result.getComplexIntImag() = -Result.getComplexIntImag();
12743 return true;
12744 }
12745}
12746
12747bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12748 if (E->getNumInits() == 2) {
12749 if (E->getType()->isComplexType()) {
12750 Result.makeComplexFloat();
12751 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12752 return false;
12753 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12754 return false;
12755 } else {
12756 Result.makeComplexInt();
12757 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12758 return false;
12759 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12760 return false;
12761 }
12762 return true;
12763 }
12764 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12765}
12766
12767//===----------------------------------------------------------------------===//
12768// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12769// implicit conversion.
12770//===----------------------------------------------------------------------===//
12771
12772namespace {
12773class AtomicExprEvaluator :
12774 public ExprEvaluatorBase<AtomicExprEvaluator> {
12775 const LValue *This;
12776 APValue &Result;
12777public:
12778 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12779 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12780
12781 bool Success(const APValue &V, const Expr *E) {
12782 Result = V;
12783 return true;
12784 }
12785
12786 bool ZeroInitialization(const Expr *E) {
12787 ImplicitValueInitExpr VIE(
12788 E->getType()->castAs<AtomicType>()->getValueType());
12789 // For atomic-qualified class (and array) types in C++, initialize the
12790 // _Atomic-wrapped subobject directly, in-place.
12791 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12792 : Evaluate(Result, Info, &VIE);
12793 }
12794
12795 bool VisitCastExpr(const CastExpr *E) {
12796 switch (E->getCastKind()) {
12797 default:
12798 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12799 case CK_NonAtomicToAtomic:
12800 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12801 : Evaluate(Result, Info, E->getSubExpr());
12802 }
12803 }
12804};
12805} // end anonymous namespace
12806
12807static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12808 EvalInfo &Info) {
12809 assert(E->isRValue() && E->getType()->isAtomicType())((E->isRValue() && E->getType()->isAtomicType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isAtomicType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12809, __PRETTY_FUNCTION__))
;
12810 return AtomicExprEvaluator(Info, This, Result).Visit(E);
12811}
12812
12813//===----------------------------------------------------------------------===//
12814// Void expression evaluation, primarily for a cast to void on the LHS of a
12815// comma operator
12816//===----------------------------------------------------------------------===//
12817
12818namespace {
12819class VoidExprEvaluator
12820 : public ExprEvaluatorBase<VoidExprEvaluator> {
12821public:
12822 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12823
12824 bool Success(const APValue &V, const Expr *e) { return true; }
12825
12826 bool ZeroInitialization(const Expr *E) { return true; }
12827
12828 bool VisitCastExpr(const CastExpr *E) {
12829 switch (E->getCastKind()) {
12830 default:
12831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12832 case CK_ToVoid:
12833 VisitIgnoredValue(E->getSubExpr());
12834 return true;
12835 }
12836 }
12837
12838 bool VisitCallExpr(const CallExpr *E) {
12839 switch (E->getBuiltinCallee()) {
12840 default:
12841 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12842 case Builtin::BI__assume:
12843 case Builtin::BI__builtin_assume:
12844 // The argument is not evaluated!
12845 return true;
12846 }
12847 }
12848
12849 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
12850};
12851} // end anonymous namespace
12852
12853static bool hasVirtualDestructor(QualType T) {
12854 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
12855 if (CXXDestructorDecl *DD = RD->getDestructor())
12856 return DD->isVirtual();
12857 return false;
12858}
12859
12860bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
12861 // We cannot speculatively evaluate a delete expression.
12862 if (Info.SpeculativeEvaluationDepth)
12863 return false;
12864
12865 FunctionDecl *OperatorDelete = E->getOperatorDelete();
12866 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
12867 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
12868 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
12869 return false;
12870 }
12871
12872 const Expr *Arg = E->getArgument();
12873
12874 LValue Pointer;
12875 if (!EvaluatePointer(Arg, Pointer, Info))
12876 return false;
12877 if (Pointer.Designator.Invalid)
12878 return false;
12879
12880 // Deleting a null pointer has no effect.
12881 if (Pointer.isNullPointer()) {
12882 // This is the only case where we need to produce an extension warning:
12883 // the only other way we can succeed is if we find a dynamic allocation,
12884 // and we will have warned when we allocated it in that case.
12885 if (!Info.getLangOpts().CPlusPlus2a)
12886 Info.CCEDiag(E, diag::note_constexpr_new);
12887 return true;
12888 }
12889
12890 auto PointerAsString = [&] {
12891 APValue Printable;
12892 Pointer.moveInto(Printable);
12893 return Printable.getAsString(Info.Ctx, Arg->getType());
12894 };
12895
12896 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
12897 if (!DA) {
12898 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
12899 << PointerAsString();
12900 if (Pointer.Base)
12901 NoteLValueLocation(Info, Pointer.Base);
12902 return false;
12903 }
12904 QualType AllocType = Pointer.Base.getDynamicAllocType();
12905
12906 Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
12907 if (!Alloc) {
12908 Info.FFDiag(E, diag::note_constexpr_double_delete);
12909 return false;
12910 }
12911
12912 if (E->isArrayForm() != AllocType->isConstantArrayType()) {
12913 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
12914 << E->isArrayForm() << AllocType;
12915 NoteLValueLocation(Info, Pointer.Base);
12916 return false;
12917 }
12918
12919 bool Subobject = false;
12920 if (E->isArrayForm()) {
12921 Subobject = Pointer.Designator.Entries.size() != 1 ||
12922 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
12923 } else {
12924 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
12925 Pointer.Designator.isOnePastTheEnd();
12926 }
12927 if (Subobject) {
12928 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
12929 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
12930 return false;
12931 }
12932
12933 // For the non-array case, the designator must be empty if the static type
12934 // does not have a virtual destructor.
12935 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
12936 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
12937 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
12938 << Arg->getType()->getPointeeType() << AllocType;
12939 return false;
12940 }
12941
12942 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
12943 (*Alloc)->Value, AllocType))
12944 return false;
12945
12946 if (!Info.HeapAllocs.erase(DA)) {
12947 // The element was already erased. This means the destructor call also
12948 // deleted the object.
12949 // FIXME: This probably results in undefined behavior before we get this
12950 // far, and should be diagnosed elsewhere first.
12951 Info.FFDiag(E, diag::note_constexpr_double_delete);
12952 return false;
12953 }
12954
12955 return true;
12956}
12957
12958static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12959 assert(E->isRValue() && E->getType()->isVoidType())((E->isRValue() && E->getType()->isVoidType(
)) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isVoidType()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 12959, __PRETTY_FUNCTION__))
;
12960 return VoidExprEvaluator(Info).Visit(E);
12961}
12962
12963//===----------------------------------------------------------------------===//
12964// Top level Expr::EvaluateAsRValue method.
12965//===----------------------------------------------------------------------===//
12966
12967static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12968 // In C, function designators are not lvalues, but we evaluate them as if they
12969 // are.
12970 QualType T = E->getType();
12971 if (E->isGLValue() || T->isFunctionType()) {
12972 LValue LV;
12973 if (!EvaluateLValue(E, LV, Info))
12974 return false;
12975 LV.moveInto(Result);
12976 } else if (T->isVectorType()) {
12977 if (!EvaluateVector(E, Result, Info))
12978 return false;
12979 } else if (T->isIntegralOrEnumerationType()) {
12980 if (!IntExprEvaluator(Info, Result).Visit(E))
12981 return false;
12982 } else if (T->hasPointerRepresentation()) {
12983 LValue LV;
12984 if (!EvaluatePointer(E, LV, Info))
12985 return false;
12986 LV.moveInto(Result);
12987 } else if (T->isRealFloatingType()) {
12988 llvm::APFloat F(0.0);
12989 if (!EvaluateFloat(E, F, Info))
12990 return false;
12991 Result = APValue(F);
12992 } else if (T->isAnyComplexType()) {
12993 ComplexValue C;
12994 if (!EvaluateComplex(E, C, Info))
12995 return false;
12996 C.moveInto(Result);
12997 } else if (T->isFixedPointType()) {
12998 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12999 } else if (T->isMemberPointerType()) {
13000 MemberPtr P;
13001 if (!EvaluateMemberPointer(E, P, Info))
13002 return false;
13003 P.moveInto(Result);
13004 return true;
13005 } else if (T->isArrayType()) {
13006 LValue LV;
13007 APValue &Value =
13008 Info.CurrentCall->createTemporary(E, T, false, LV);
13009 if (!EvaluateArray(E, LV, Value, Info))
13010 return false;
13011 Result = Value;
13012 } else if (T->isRecordType()) {
13013 LValue LV;
13014 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13015 if (!EvaluateRecord(E, LV, Value, Info))
13016 return false;
13017 Result = Value;
13018 } else if (T->isVoidType()) {
13019 if (!Info.getLangOpts().CPlusPlus11)
13020 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13021 << E->getType();
13022 if (!EvaluateVoid(E, Info))
13023 return false;
13024 } else if (T->isAtomicType()) {
13025 QualType Unqual = T.getAtomicUnqualifiedType();
13026 if (Unqual->isArrayType() || Unqual->isRecordType()) {
13027 LValue LV;
13028 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13029 if (!EvaluateAtomic(E, &LV, Value, Info))
13030 return false;
13031 } else {
13032 if (!EvaluateAtomic(E, nullptr, Result, Info))
13033 return false;
13034 }
13035 } else if (Info.getLangOpts().CPlusPlus11) {
13036 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13037 return false;
13038 } else {
13039 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13040 return false;
13041 }
13042
13043 return true;
13044}
13045
13046/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13047/// cases, the in-place evaluation is essential, since later initializers for
13048/// an object can indirectly refer to subobjects which were initialized earlier.
13049static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13050 const Expr *E, bool AllowNonLiteralTypes) {
13051 assert(!E->isValueDependent())((!E->isValueDependent()) ? static_cast<void> (0) : __assert_fail
("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13051, __PRETTY_FUNCTION__))
;
13052
13053 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13054 return false;
13055
13056 if (E->isRValue()) {
13057 // Evaluate arrays and record types in-place, so that later initializers can
13058 // refer to earlier-initialized members of the object.
13059 QualType T = E->getType();
13060 if (T->isArrayType())
13061 return EvaluateArray(E, This, Result, Info);
13062 else if (T->isRecordType())
13063 return EvaluateRecord(E, This, Result, Info);
13064 else if (T->isAtomicType()) {
13065 QualType Unqual = T.getAtomicUnqualifiedType();
13066 if (Unqual->isArrayType() || Unqual->isRecordType())
13067 return EvaluateAtomic(E, &This, Result, Info);
13068 }
13069 }
13070
13071 // For any other type, in-place evaluation is unimportant.
13072 return Evaluate(Result, Info, E);
13073}
13074
13075/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13076/// lvalue-to-rvalue cast if it is an lvalue.
13077static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13078 if (Info.EnableNewConstInterp) {
13079 auto &InterpCtx = Info.Ctx.getInterpContext();
13080 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
13081 case interp::InterpResult::Success:
13082 return true;
13083 case interp::InterpResult::Fail:
13084 return false;
13085 case interp::InterpResult::Bail:
13086 break;
13087 }
13088 }
13089
13090 if (E->getType().isNull())
13091 return false;
13092
13093 if (!CheckLiteralType(Info, E))
13094 return false;
13095
13096 if (!::Evaluate(Result, Info, E))
13097 return false;
13098
13099 if (E->isGLValue()) {
13100 LValue LV;
13101 LV.setFrom(Info.Ctx, Result);
13102 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13103 return false;
13104 }
13105
13106 // Check this core constant expression is a constant expression.
13107 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13108 CheckMemoryLeaks(Info);
13109}
13110
13111static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13112 const ASTContext &Ctx, bool &IsConst) {
13113 // Fast-path evaluations of integer literals, since we sometimes see files
13114 // containing vast quantities of these.
13115 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13116 Result.Val = APValue(APSInt(L->getValue(),
13117 L->getType()->isUnsignedIntegerType()));
13118 IsConst = true;
13119 return true;
13120 }
13121
13122 // This case should be rare, but we need to check it before we check on
13123 // the type below.
13124 if (Exp->getType().isNull()) {
13125 IsConst = false;
13126 return true;
13127 }
13128
13129 // FIXME: Evaluating values of large array and record types can cause
13130 // performance problems. Only do so in C++11 for now.
13131 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13132 Exp->getType()->isRecordType()) &&
13133 !Ctx.getLangOpts().CPlusPlus11) {
13134 IsConst = false;
13135 return true;
13136 }
13137 return false;
13138}
13139
13140static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13141 Expr::SideEffectsKind SEK) {
13142 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13143 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13144}
13145
13146static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13147 const ASTContext &Ctx, EvalInfo &Info) {
13148 bool IsConst;
13149 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13150 return IsConst;
13151
13152 return EvaluateAsRValue(Info, E, Result.Val);
13153}
13154
13155static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13156 const ASTContext &Ctx,
13157 Expr::SideEffectsKind AllowSideEffects,
13158 EvalInfo &Info) {
13159 if (!E->getType()->isIntegralOrEnumerationType())
13160 return false;
13161
13162 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13163 !ExprResult.Val.isInt() ||
13164 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13165 return false;
13166
13167 return true;
13168}
13169
13170static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13171 const ASTContext &Ctx,
13172 Expr::SideEffectsKind AllowSideEffects,
13173 EvalInfo &Info) {
13174 if (!E->getType()->isFixedPointType())
13175 return false;
13176
13177 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13178 return false;
13179
13180 if (!ExprResult.Val.isFixedPoint() ||
13181 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13182 return false;
13183
13184 return true;
13185}
13186
13187/// EvaluateAsRValue - Return true if this is a constant which we can fold using
13188/// any crazy technique (that has nothing to do with language standards) that
13189/// we want to. If this function returns true, it returns the folded constant
13190/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13191/// will be applied to the result.
13192bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13193 bool InConstantContext) const {
13194 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13195, __PRETTY_FUNCTION__))
13195 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13195, __PRETTY_FUNCTION__))
;
13196 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13197 Info.InConstantContext = InConstantContext;
13198 return ::EvaluateAsRValue(this, Result, Ctx, Info);
13199}
13200
13201bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13202 bool InConstantContext) const {
13203 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13204, __PRETTY_FUNCTION__))
13204 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13204, __PRETTY_FUNCTION__))
;
13205 EvalResult Scratch;
13206 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13207 HandleConversionToBool(Scratch.Val, Result);
13208}
13209
13210bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13211 SideEffectsKind AllowSideEffects,
13212 bool InConstantContext) const {
13213 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13214, __PRETTY_FUNCTION__))
13214 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13214, __PRETTY_FUNCTION__))
;
13215 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13216 Info.InConstantContext = InConstantContext;
13217 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13218}
13219
13220bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13221 SideEffectsKind AllowSideEffects,
13222 bool InConstantContext) const {
13223 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13224, __PRETTY_FUNCTION__))
13224 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13224, __PRETTY_FUNCTION__))
;
13225 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13226 Info.InConstantContext = InConstantContext;
13227 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13228}
13229
13230bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13231 SideEffectsKind AllowSideEffects,
13232 bool InConstantContext) const {
13233 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13234, __PRETTY_FUNCTION__))
13234 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13234, __PRETTY_FUNCTION__))
;
13235
13236 if (!getType()->isRealFloatingType())
13237 return false;
13238
13239 EvalResult ExprResult;
13240 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13241 !ExprResult.Val.isFloat() ||
13242 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13243 return false;
13244
13245 Result = ExprResult.Val.getFloat();
13246 return true;
13247}
13248
13249bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13250 bool InConstantContext) const {
13251 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13252, __PRETTY_FUNCTION__))
13252 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13252, __PRETTY_FUNCTION__))
;
13253
13254 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13255 Info.InConstantContext = InConstantContext;
13256 LValue LV;
13257 CheckedTemporaries CheckedTemps;
13258 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13259 Result.HasSideEffects ||
13260 !CheckLValueConstantExpression(Info, getExprLoc(),
13261 Ctx.getLValueReferenceType(getType()), LV,
13262 Expr::EvaluateForCodeGen, CheckedTemps))
13263 return false;
13264
13265 LV.moveInto(Result.Val);
13266 return true;
13267}
13268
13269bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13270 const ASTContext &Ctx) const {
13271 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13272, __PRETTY_FUNCTION__))
13272 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13272, __PRETTY_FUNCTION__))
;
13273
13274 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13275 EvalInfo Info(Ctx, Result, EM);
13276 Info.InConstantContext = true;
13277
13278 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13279 return false;
13280
13281 if (!Info.discardCleanups())
13282 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13282)
;
13283
13284 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
13285 Usage) &&
13286 CheckMemoryLeaks(Info);
13287}
13288
13289bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13290 const VarDecl *VD,
13291 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13292 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13293, __PRETTY_FUNCTION__))
13293 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13293, __PRETTY_FUNCTION__))
;
13294
13295 // FIXME: Evaluating initializers for large array and record types can cause
13296 // performance problems. Only do so in C++11 for now.
13297 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13298 !Ctx.getLangOpts().CPlusPlus11)
13299 return false;
13300
13301 Expr::EvalStatus EStatus;
13302 EStatus.Diag = &Notes;
13303
13304 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13305 ? EvalInfo::EM_ConstantExpression
13306 : EvalInfo::EM_ConstantFold);
13307 Info.setEvaluatingDecl(VD, Value);
13308 Info.InConstantContext = true;
13309
13310 SourceLocation DeclLoc = VD->getLocation();
13311 QualType DeclTy = VD->getType();
13312
13313 if (Info.EnableNewConstInterp) {
13314 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13315 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
13316 case interp::InterpResult::Fail:
13317 // Bail out if an error was encountered.
13318 return false;
13319 case interp::InterpResult::Success:
13320 // Evaluation succeeded and value was set.
13321 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
13322 case interp::InterpResult::Bail:
13323 // Evaluate the value again for the tree evaluator to use.
13324 break;
13325 }
13326 }
13327
13328 LValue LVal;
13329 LVal.set(VD);
13330
13331 // C++11 [basic.start.init]p2:
13332 // Variables with static storage duration or thread storage duration shall be
13333 // zero-initialized before any other initialization takes place.
13334 // This behavior is not present in C.
13335 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
13336 !DeclTy->isReferenceType()) {
13337 ImplicitValueInitExpr VIE(DeclTy);
13338 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
13339 /*AllowNonLiteralTypes=*/true))
13340 return false;
13341 }
13342
13343 if (!EvaluateInPlace(Value, Info, LVal, this,
13344 /*AllowNonLiteralTypes=*/true) ||
13345 EStatus.HasSideEffects)
13346 return false;
13347
13348 // At this point, any lifetime-extended temporaries are completely
13349 // initialized.
13350 Info.performLifetimeExtension();
13351
13352 if (!Info.discardCleanups())
13353 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13353)
;
13354
13355 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13356 CheckMemoryLeaks(Info);
13357}
13358
13359bool VarDecl::evaluateDestruction(
13360 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13361 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&((getEvaluatedValue() && !getEvaluatedValue()->isAbsent
() && "cannot evaluate destruction of non-constant-initialized variable"
) ? static_cast<void> (0) : __assert_fail ("getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && \"cannot evaluate destruction of non-constant-initialized variable\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13362, __PRETTY_FUNCTION__))
13362 "cannot evaluate destruction of non-constant-initialized variable")((getEvaluatedValue() && !getEvaluatedValue()->isAbsent
() && "cannot evaluate destruction of non-constant-initialized variable"
) ? static_cast<void> (0) : __assert_fail ("getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && \"cannot evaluate destruction of non-constant-initialized variable\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13362, __PRETTY_FUNCTION__))
;
13363
13364 Expr::EvalStatus EStatus;
13365 EStatus.Diag = &Notes;
13366
13367 // Make a copy of the value for the destructor to mutate.
13368 APValue DestroyedValue = *getEvaluatedValue();
13369
13370 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13371 Info.setEvaluatingDecl(this, DestroyedValue,
13372 EvalInfo::EvaluatingDeclKind::Dtor);
13373 Info.InConstantContext = true;
13374
13375 SourceLocation DeclLoc = getLocation();
13376 QualType DeclTy = getType();
13377
13378 LValue LVal;
13379 LVal.set(this);
13380
13381 // FIXME: Consider storing whether this variable has constant destruction in
13382 // the EvaluatedStmt so that CodeGen can query it.
13383 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13384 EStatus.HasSideEffects)
13385 return false;
13386
13387 if (!Info.discardCleanups())
13388 llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13388)
;
13389
13390 ensureEvaluatedStmt()->HasConstantDestruction = true;
13391 return true;
13392}
13393
13394/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13395/// constant folded, but discard the result.
13396bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
13397 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13398, __PRETTY_FUNCTION__))
13398 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13398, __PRETTY_FUNCTION__))
;
13399
13400 EvalResult Result;
13401 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
13402 !hasUnacceptableSideEffect(Result, SEK);
13403}
13404
13405APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
13406 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
13407 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13408, __PRETTY_FUNCTION__))
13408 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13408, __PRETTY_FUNCTION__))
;
13409
13410 EvalResult EVResult;
13411 EVResult.Diag = Diag;
13412 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13413 Info.InConstantContext = true;
13414
13415 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
13416 (void)Result;
13417 assert(Result && "Could not evaluate expression")((Result && "Could not evaluate expression") ? static_cast
<void> (0) : __assert_fail ("Result && \"Could not evaluate expression\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13417, __PRETTY_FUNCTION__))
;
13418 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")((EVResult.Val.isInt() && "Expression did not evaluate to integer"
) ? static_cast<void> (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13418, __PRETTY_FUNCTION__))
;
13419
13420 return EVResult.Val.getInt();
13421}
13422
13423APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13424 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
13425 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13426, __PRETTY_FUNCTION__))
13426 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13426, __PRETTY_FUNCTION__))
;
13427
13428 EvalResult EVResult;
13429 EVResult.Diag = Diag;
13430 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13431 Info.InConstantContext = true;
13432 Info.CheckingForUndefinedBehavior = true;
13433
13434 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
13435 (void)Result;
13436 assert(Result && "Could not evaluate expression")((Result && "Could not evaluate expression") ? static_cast
<void> (0) : __assert_fail ("Result && \"Could not evaluate expression\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13436, __PRETTY_FUNCTION__))
;
13437 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")((EVResult.Val.isInt() && "Expression did not evaluate to integer"
) ? static_cast<void> (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13437, __PRETTY_FUNCTION__))
;
13438
13439 return EVResult.Val.getInt();
13440}
13441
13442void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
13443 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13444, __PRETTY_FUNCTION__))
13444 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13444, __PRETTY_FUNCTION__))
;
13445
13446 bool IsConst;
13447 EvalResult EVResult;
13448 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
13449 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13450 Info.CheckingForUndefinedBehavior = true;
13451 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
13452 }
13453}
13454
13455bool Expr::EvalResult::isGlobalLValue() const {
13456 assert(Val.isLValue())((Val.isLValue()) ? static_cast<void> (0) : __assert_fail
("Val.isLValue()", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13456, __PRETTY_FUNCTION__))
;
13457 return IsGlobalLValue(Val.getLValueBase());
13458}
13459
13460
13461/// isIntegerConstantExpr - this recursive routine will test if an expression is
13462/// an integer constant expression.
13463
13464/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
13465/// comma, etc
13466
13467// CheckICE - This function does the fundamental ICE checking: the returned
13468// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
13469// and a (possibly null) SourceLocation indicating the location of the problem.
13470//
13471// Note that to reduce code duplication, this helper does no evaluation
13472// itself; the caller checks whether the expression is evaluatable, and
13473// in the rare cases where CheckICE actually cares about the evaluated
13474// value, it calls into Evaluate.
13475
13476namespace {
13477
13478enum ICEKind {
13479 /// This expression is an ICE.
13480 IK_ICE,
13481 /// This expression is not an ICE, but if it isn't evaluated, it's
13482 /// a legal subexpression for an ICE. This return value is used to handle
13483 /// the comma operator in C99 mode, and non-constant subexpressions.
13484 IK_ICEIfUnevaluated,
13485 /// This expression is not an ICE, and is not a legal subexpression for one.
13486 IK_NotICE
13487};
13488
13489struct ICEDiag {
13490 ICEKind Kind;
13491 SourceLocation Loc;
13492
13493 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
13494};
13495
13496}
13497
13498static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
13499
13500static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
13501
13502static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
13503 Expr::EvalResult EVResult;
13504 Expr::EvalStatus Status;
13505 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13506
13507 Info.InConstantContext = true;
13508 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
13509 !EVResult.Val.isInt())
13510 return ICEDiag(IK_NotICE, E->getBeginLoc());
13511
13512 return NoDiag();
13513}
13514
13515static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
13516 assert(!E->isValueDependent() && "Should not see value dependent exprs!")((!E->isValueDependent() && "Should not see value dependent exprs!"
) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Should not see value dependent exprs!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13516, __PRETTY_FUNCTION__))
;
13517 if (!E->getType()->isIntegralOrEnumerationType())
13518 return ICEDiag(IK_NotICE, E->getBeginLoc());
13519
13520 switch (E->getStmtClass()) {
13521#define ABSTRACT_STMT(Node)
13522#define STMT(Node, Base) case Expr::Node##Class:
13523#define EXPR(Node, Base)
13524#include "clang/AST/StmtNodes.inc"
13525 case Expr::PredefinedExprClass:
13526 case Expr::FloatingLiteralClass:
13527 case Expr::ImaginaryLiteralClass:
13528 case Expr::StringLiteralClass:
13529 case Expr::ArraySubscriptExprClass:
13530 case Expr::OMPArraySectionExprClass:
13531 case Expr::MemberExprClass:
13532 case Expr::CompoundAssignOperatorClass:
13533 case Expr::CompoundLiteralExprClass:
13534 case Expr::ExtVectorElementExprClass:
13535 case Expr::DesignatedInitExprClass:
13536 case Expr::ArrayInitLoopExprClass:
13537 case Expr::ArrayInitIndexExprClass:
13538 case Expr::NoInitExprClass:
13539 case Expr::DesignatedInitUpdateExprClass:
13540 case Expr::ImplicitValueInitExprClass:
13541 case Expr::ParenListExprClass:
13542 case Expr::VAArgExprClass:
13543 case Expr::AddrLabelExprClass:
13544 case Expr::StmtExprClass:
13545 case Expr::CXXMemberCallExprClass:
13546 case Expr::CUDAKernelCallExprClass:
13547 case Expr::CXXDynamicCastExprClass:
13548 case Expr::CXXTypeidExprClass:
13549 case Expr::CXXUuidofExprClass:
13550 case Expr::MSPropertyRefExprClass:
13551 case Expr::MSPropertySubscriptExprClass:
13552 case Expr::CXXNullPtrLiteralExprClass:
13553 case Expr::UserDefinedLiteralClass:
13554 case Expr::CXXThisExprClass:
13555 case Expr::CXXThrowExprClass:
13556 case Expr::CXXNewExprClass:
13557 case Expr::CXXDeleteExprClass:
13558 case Expr::CXXPseudoDestructorExprClass:
13559 case Expr::UnresolvedLookupExprClass:
13560 case Expr::TypoExprClass:
13561 case Expr::DependentScopeDeclRefExprClass:
13562 case Expr::CXXConstructExprClass:
13563 case Expr::CXXInheritedCtorInitExprClass:
13564 case Expr::CXXStdInitializerListExprClass:
13565 case Expr::CXXBindTemporaryExprClass:
13566 case Expr::ExprWithCleanupsClass:
13567 case Expr::CXXTemporaryObjectExprClass:
13568 case Expr::CXXUnresolvedConstructExprClass:
13569 case Expr::CXXDependentScopeMemberExprClass:
13570 case Expr::UnresolvedMemberExprClass:
13571 case Expr::ObjCStringLiteralClass:
13572 case Expr::ObjCBoxedExprClass:
13573 case Expr::ObjCArrayLiteralClass:
13574 case Expr::ObjCDictionaryLiteralClass:
13575 case Expr::ObjCEncodeExprClass:
13576 case Expr::ObjCMessageExprClass:
13577 case Expr::ObjCSelectorExprClass:
13578 case Expr::ObjCProtocolExprClass:
13579 case Expr::ObjCIvarRefExprClass:
13580 case Expr::ObjCPropertyRefExprClass:
13581 case Expr::ObjCSubscriptRefExprClass:
13582 case Expr::ObjCIsaExprClass:
13583 case Expr::ObjCAvailabilityCheckExprClass:
13584 case Expr::ShuffleVectorExprClass:
13585 case Expr::ConvertVectorExprClass:
13586 case Expr::BlockExprClass:
13587 case Expr::NoStmtClass:
13588 case Expr::OpaqueValueExprClass:
13589 case Expr::PackExpansionExprClass:
13590 case Expr::SubstNonTypeTemplateParmPackExprClass:
13591 case Expr::FunctionParmPackExprClass:
13592 case Expr::AsTypeExprClass:
13593 case Expr::ObjCIndirectCopyRestoreExprClass:
13594 case Expr::MaterializeTemporaryExprClass:
13595 case Expr::PseudoObjectExprClass:
13596 case Expr::AtomicExprClass:
13597 case Expr::LambdaExprClass:
13598 case Expr::CXXFoldExprClass:
13599 case Expr::CoawaitExprClass:
13600 case Expr::DependentCoawaitExprClass:
13601 case Expr::CoyieldExprClass:
13602 return ICEDiag(IK_NotICE, E->getBeginLoc());
13603
13604 case Expr::InitListExprClass: {
13605 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13606 // form "T x = { a };" is equivalent to "T x = a;".
13607 // Unless we're initializing a reference, T is a scalar as it is known to be
13608 // of integral or enumeration type.
13609 if (E->isRValue())
13610 if (cast<InitListExpr>(E)->getNumInits() == 1)
13611 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
13612 return ICEDiag(IK_NotICE, E->getBeginLoc());
13613 }
13614
13615 case Expr::SizeOfPackExprClass:
13616 case Expr::GNUNullExprClass:
13617 case Expr::SourceLocExprClass:
13618 return NoDiag();
13619
13620 case Expr::SubstNonTypeTemplateParmExprClass:
13621 return
13622 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13623
13624 case Expr::ConstantExprClass:
13625 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13626
13627 case Expr::ParenExprClass:
13628 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
13629 case Expr::GenericSelectionExprClass:
13630 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
13631 case Expr::IntegerLiteralClass:
13632 case Expr::FixedPointLiteralClass:
13633 case Expr::CharacterLiteralClass:
13634 case Expr::ObjCBoolLiteralExprClass:
13635 case Expr::CXXBoolLiteralExprClass:
13636 case Expr::CXXScalarValueInitExprClass:
13637 case Expr::TypeTraitExprClass:
13638 case Expr::ArrayTypeTraitExprClass:
13639 case Expr::ExpressionTraitExprClass:
13640 case Expr::CXXNoexceptExprClass:
13641 return NoDiag();
13642 case Expr::CallExprClass:
13643 case Expr::CXXOperatorCallExprClass: {
13644 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13645 // constant expressions, but they can never be ICEs because an ICE cannot
13646 // contain an operand of (pointer to) function type.
13647 const CallExpr *CE = cast<CallExpr>(E);
13648 if (CE->getBuiltinCallee())
13649 return CheckEvalInICE(E, Ctx);
13650 return ICEDiag(IK_NotICE, E->getBeginLoc());
13651 }
13652 case Expr::DeclRefExprClass: {
13653 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13654 return NoDiag();
13655 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
13656 if (Ctx.getLangOpts().CPlusPlus &&
13657 D && IsConstNonVolatile(D->getType())) {
13658 // Parameter variables are never constants. Without this check,
13659 // getAnyInitializer() can find a default argument, which leads
13660 // to chaos.
13661 if (isa<ParmVarDecl>(D))
13662 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
13663
13664 // C++ 7.1.5.1p2
13665 // A variable of non-volatile const-qualified integral or enumeration
13666 // type initialized by an ICE can be used in ICEs.
13667 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
13668 if (!Dcl->getType()->isIntegralOrEnumerationType())
13669 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
13670
13671 const VarDecl *VD;
13672 // Look for a declaration of this variable that has an initializer, and
13673 // check whether it is an ICE.
13674 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13675 return NoDiag();
13676 else
13677 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
13678 }
13679 }
13680 return ICEDiag(IK_NotICE, E->getBeginLoc());
13681 }
13682 case Expr::UnaryOperatorClass: {
13683 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13684 switch (Exp->getOpcode()) {
13685 case UO_PostInc:
13686 case UO_PostDec:
13687 case UO_PreInc:
13688 case UO_PreDec:
13689 case UO_AddrOf:
13690 case UO_Deref:
13691 case UO_Coawait:
13692 // C99 6.6/3 allows increment and decrement within unevaluated
13693 // subexpressions of constant expressions, but they can never be ICEs
13694 // because an ICE cannot contain an lvalue operand.
13695 return ICEDiag(IK_NotICE, E->getBeginLoc());
13696 case UO_Extension:
13697 case UO_LNot:
13698 case UO_Plus:
13699 case UO_Minus:
13700 case UO_Not:
13701 case UO_Real:
13702 case UO_Imag:
13703 return CheckICE(Exp->getSubExpr(), Ctx);
13704 }
13705 llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13705)
;
13706 }
13707 case Expr::OffsetOfExprClass: {
13708 // Note that per C99, offsetof must be an ICE. And AFAIK, using
13709 // EvaluateAsRValue matches the proposed gcc behavior for cases like
13710 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
13711 // compliance: we should warn earlier for offsetof expressions with
13712 // array subscripts that aren't ICEs, and if the array subscripts
13713 // are ICEs, the value of the offsetof must be an integer constant.
13714 return CheckEvalInICE(E, Ctx);
13715 }
13716 case Expr::UnaryExprOrTypeTraitExprClass: {
13717 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
13718 if ((Exp->getKind() == UETT_SizeOf) &&
13719 Exp->getTypeOfArgument()->isVariableArrayType())
13720 return ICEDiag(IK_NotICE, E->getBeginLoc());
13721 return NoDiag();
13722 }
13723 case Expr::BinaryOperatorClass: {
13724 const BinaryOperator *Exp = cast<BinaryOperator>(E);
13725 switch (Exp->getOpcode()) {
13726 case BO_PtrMemD:
13727 case BO_PtrMemI:
13728 case BO_Assign:
13729 case BO_MulAssign:
13730 case BO_DivAssign:
13731 case BO_RemAssign:
13732 case BO_AddAssign:
13733 case BO_SubAssign:
13734 case BO_ShlAssign:
13735 case BO_ShrAssign:
13736 case BO_AndAssign:
13737 case BO_XorAssign:
13738 case BO_OrAssign:
13739 // C99 6.6/3 allows assignments within unevaluated subexpressions of
13740 // constant expressions, but they can never be ICEs because an ICE cannot
13741 // contain an lvalue operand.
13742 return ICEDiag(IK_NotICE, E->getBeginLoc());
13743
13744 case BO_Mul:
13745 case BO_Div:
13746 case BO_Rem:
13747 case BO_Add:
13748 case BO_Sub:
13749 case BO_Shl:
13750 case BO_Shr:
13751 case BO_LT:
13752 case BO_GT:
13753 case BO_LE:
13754 case BO_GE:
13755 case BO_EQ:
13756 case BO_NE:
13757 case BO_And:
13758 case BO_Xor:
13759 case BO_Or:
13760 case BO_Comma:
13761 case BO_Cmp: {
13762 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13763 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
13764 if (Exp->getOpcode() == BO_Div ||
13765 Exp->getOpcode() == BO_Rem) {
13766 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
13767 // we don't evaluate one.
13768 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
13769 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
13770 if (REval == 0)
13771 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
13772 if (REval.isSigned() && REval.isAllOnesValue()) {
13773 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
13774 if (LEval.isMinSignedValue())
13775 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
13776 }
13777 }
13778 }
13779 if (Exp->getOpcode() == BO_Comma) {
13780 if (Ctx.getLangOpts().C99) {
13781 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
13782 // if it isn't evaluated.
13783 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
13784 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
13785 } else {
13786 // In both C89 and C++, commas in ICEs are illegal.
13787 return ICEDiag(IK_NotICE, E->getBeginLoc());
13788 }
13789 }
13790 return Worst(LHSResult, RHSResult);
13791 }
13792 case BO_LAnd:
13793 case BO_LOr: {
13794 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
13795 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
13796 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
13797 // Rare case where the RHS has a comma "side-effect"; we need
13798 // to actually check the condition to see whether the side
13799 // with the comma is evaluated.
13800 if ((Exp->getOpcode() == BO_LAnd) !=
13801 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
13802 return RHSResult;
13803 return NoDiag();
13804 }
13805
13806 return Worst(LHSResult, RHSResult);
13807 }
13808 }
13809 llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13809)
;
13810 }
13811 case Expr::ImplicitCastExprClass:
13812 case Expr::CStyleCastExprClass:
13813 case Expr::CXXFunctionalCastExprClass:
13814 case Expr::CXXStaticCastExprClass:
13815 case Expr::CXXReinterpretCastExprClass:
13816 case Expr::CXXConstCastExprClass:
13817 case Expr::ObjCBridgedCastExprClass: {
13818 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
13819 if (isa<ExplicitCastExpr>(E)) {
13820 if (const FloatingLiteral *FL
13821 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
13822 unsigned DestWidth = Ctx.getIntWidth(E->getType());
13823 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
13824 APSInt IgnoredVal(DestWidth, !DestSigned);
13825 bool Ignored;
13826 // If the value does not fit in the destination type, the behavior is
13827 // undefined, so we are not required to treat it as a constant
13828 // expression.
13829 if (FL->getValue().convertToInteger(IgnoredVal,
13830 llvm::APFloat::rmTowardZero,
13831 &Ignored) & APFloat::opInvalidOp)
13832 return ICEDiag(IK_NotICE, E->getBeginLoc());
13833 return NoDiag();
13834 }
13835 }
13836 switch (cast<CastExpr>(E)->getCastKind()) {
13837 case CK_LValueToRValue:
13838 case CK_AtomicToNonAtomic:
13839 case CK_NonAtomicToAtomic:
13840 case CK_NoOp:
13841 case CK_IntegralToBoolean:
13842 case CK_IntegralCast:
13843 return CheckICE(SubExpr, Ctx);
13844 default:
13845 return ICEDiag(IK_NotICE, E->getBeginLoc());
13846 }
13847 }
13848 case Expr::BinaryConditionalOperatorClass: {
13849 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
13850 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
13851 if (CommonResult.Kind == IK_NotICE) return CommonResult;
13852 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
13853 if (FalseResult.Kind == IK_NotICE) return FalseResult;
13854 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
13855 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
13856 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
13857 return FalseResult;
13858 }
13859 case Expr::ConditionalOperatorClass: {
13860 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
13861 // If the condition (ignoring parens) is a __builtin_constant_p call,
13862 // then only the true side is actually considered in an integer constant
13863 // expression, and it is fully evaluated. This is an important GNU
13864 // extension. See GCC PR38377 for discussion.
13865 if (const CallExpr *CallCE
13866 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
13867 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
13868 return CheckEvalInICE(E, Ctx);
13869 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
13870 if (CondResult.Kind == IK_NotICE)
13871 return CondResult;
13872
13873 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
13874 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
13875
13876 if (TrueResult.Kind == IK_NotICE)
13877 return TrueResult;
13878 if (FalseResult.Kind == IK_NotICE)
13879 return FalseResult;
13880 if (CondResult.Kind == IK_ICEIfUnevaluated)
13881 return CondResult;
13882 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
13883 return NoDiag();
13884 // Rare case where the diagnostics depend on which side is evaluated
13885 // Note that if we get here, CondResult is 0, and at least one of
13886 // TrueResult and FalseResult is non-zero.
13887 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
13888 return FalseResult;
13889 return TrueResult;
13890 }
13891 case Expr::CXXDefaultArgExprClass:
13892 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
13893 case Expr::CXXDefaultInitExprClass:
13894 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
13895 case Expr::ChooseExprClass: {
13896 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
13897 }
13898 case Expr::BuiltinBitCastExprClass: {
13899 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13900 return ICEDiag(IK_NotICE, E->getBeginLoc());
13901 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13902 }
13903 }
13904
13905 llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13905)
;
13906}
13907
13908/// Evaluate an expression as a C++11 integral constant expression.
13909static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
13910 const Expr *E,
13911 llvm::APSInt *Value,
13912 SourceLocation *Loc) {
13913 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13914 if (Loc) *Loc = E->getExprLoc();
13915 return false;
13916 }
13917
13918 APValue Result;
13919 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
13920 return false;
13921
13922 if (!Result.isInt()) {
13923 if (Loc) *Loc = E->getExprLoc();
13924 return false;
13925 }
13926
13927 if (Value) *Value = Result.getInt();
13928 return true;
13929}
13930
13931bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13932 SourceLocation *Loc) const {
13933 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13934, __PRETTY_FUNCTION__))
13934 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13934, __PRETTY_FUNCTION__))
;
13935
13936 if (Ctx.getLangOpts().CPlusPlus11)
13937 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
13938
13939 ICEDiag D = CheckICE(this, Ctx);
13940 if (D.Kind != IK_ICE) {
13941 if (Loc) *Loc = D.Loc;
13942 return false;
13943 }
13944 return true;
13945}
13946
13947bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
13948 SourceLocation *Loc, bool isEvaluated) const {
13949 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13950, __PRETTY_FUNCTION__))
13950 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13950, __PRETTY_FUNCTION__))
;
13951
13952 if (Ctx.getLangOpts().CPlusPlus11)
13953 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13954
13955 if (!isIntegerConstantExpr(Ctx, Loc))
13956 return false;
13957
13958 // The only possible side-effects here are due to UB discovered in the
13959 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13960 // required to treat the expression as an ICE, so we produce the folded
13961 // value.
13962 EvalResult ExprResult;
13963 Expr::EvalStatus Status;
13964 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13965 Info.InConstantContext = true;
13966
13967 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13968 llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!",
"/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13968)
;
13969
13970 Value = ExprResult.Val.getInt();
13971 return true;
13972}
13973
13974bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
13975 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13976, __PRETTY_FUNCTION__))
13976 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13976, __PRETTY_FUNCTION__))
;
13977
13978 return CheckICE(this, Ctx).Kind == IK_ICE;
13979}
13980
13981bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
13982 SourceLocation *Loc) const {
13983 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13984, __PRETTY_FUNCTION__))
13984 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13984, __PRETTY_FUNCTION__))
;
13985
13986 // We support this checking in C++98 mode in order to diagnose compatibility
13987 // issues.
13988 assert(Ctx.getLangOpts().CPlusPlus)((Ctx.getLangOpts().CPlusPlus) ? static_cast<void> (0) :
__assert_fail ("Ctx.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 13988, __PRETTY_FUNCTION__))
;
13989
13990 // Build evaluation settings.
13991 Expr::EvalStatus Status;
13992 SmallVector<PartialDiagnosticAt, 8> Diags;
13993 Status.Diag = &Diags;
13994 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13995
13996 APValue Scratch;
13997 bool IsConstExpr =
13998 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
13999 // FIXME: We don't produce a diagnostic for this, but the callers that
14000 // call us on arbitrary full-expressions should generally not care.
14001 Info.discardCleanups() && !Status.HasSideEffects;
14002
14003 if (!Diags.empty()) {
14004 IsConstExpr = false;
14005 if (Loc) *Loc = Diags[0].first;
14006 } else if (!IsConstExpr) {
14007 // FIXME: This shouldn't happen.
14008 if (Loc) *Loc = getExprLoc();
14009 }
14010
14011 return IsConstExpr;
14012}
14013
14014bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14015 const FunctionDecl *Callee,
14016 ArrayRef<const Expr*> Args,
14017 const Expr *This) const {
14018 assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14019, __PRETTY_FUNCTION__))
14019 "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14019, __PRETTY_FUNCTION__))
;
14020
14021 Expr::EvalStatus Status;
14022 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14023 Info.InConstantContext = true;
14024
14025 LValue ThisVal;
14026 const LValue *ThisPtr = nullptr;
14027 if (This) {
14028#ifndef NDEBUG
14029 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14030 assert(MD && "Don't provide `this` for non-methods.")((MD && "Don't provide `this` for non-methods.") ? static_cast
<void> (0) : __assert_fail ("MD && \"Don't provide `this` for non-methods.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14030, __PRETTY_FUNCTION__))
;
14031 assert(!MD->isStatic() && "Don't provide `this` for static methods.")((!MD->isStatic() && "Don't provide `this` for static methods."
) ? static_cast<void> (0) : __assert_fail ("!MD->isStatic() && \"Don't provide `this` for static methods.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14031, __PRETTY_FUNCTION__))
;
14032#endif
14033 if (EvaluateObjectArgument(Info, This, ThisVal))
14034 ThisPtr = &ThisVal;
14035 if (Info.EvalStatus.HasSideEffects)
14036 return false;
14037 }
14038
14039 ArgVector ArgValues(Args.size());
14040 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14041 I != E; ++I) {
14042 if ((*I)->isValueDependent() ||
14043 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
14044 // If evaluation fails, throw away the argument entirely.
14045 ArgValues[I - Args.begin()] = APValue();
14046 if (Info.EvalStatus.HasSideEffects)
14047 return false;
14048 }
14049
14050 // Build fake call to Callee.
14051 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14052 ArgValues.data());
14053 return Evaluate(Value, Info, this) && Info.discardCleanups() &&
14054 !Info.EvalStatus.HasSideEffects;
14055}
14056
14057bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14058 SmallVectorImpl<
14059 PartialDiagnosticAt> &Diags) {
14060 // FIXME: It would be useful to check constexpr function templates, but at the
14061 // moment the constant expression evaluator cannot cope with the non-rigorous
14062 // ASTs which we build for dependent expressions.
14063 if (FD->isDependentContext())
14064 return true;
14065
14066 Expr::EvalStatus Status;
14067 Status.Diag = &Diags;
14068
14069 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14070 Info.InConstantContext = true;
14071 Info.CheckingPotentialConstantExpression = true;
14072
14073 // The constexpr VM attempts to compile all methods to bytecode here.
14074 if (Info.EnableNewConstInterp) {
14075 auto &InterpCtx = Info.Ctx.getInterpContext();
14076 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
14077 case interp::InterpResult::Success:
14078 case interp::InterpResult::Fail:
14079 return Diags.empty();
14080 case interp::InterpResult::Bail:
14081 break;
14082 }
14083 }
14084
14085 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14086 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14087
14088 // Fabricate an arbitrary expression on the stack and pretend that it
14089 // is a temporary being used as the 'this' pointer.
14090 LValue This;
14091 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14092 This.set({&VIE, Info.CurrentCall->Index});
14093
14094 ArrayRef<const Expr*> Args;
14095
14096 APValue Scratch;
14097 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14098 // Evaluate the call as a constant initializer, to allow the construction
14099 // of objects of non-literal types.
14100 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14101 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14102 } else {
14103 SourceLocation Loc = FD->getLocation();
14104 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14105 Args, FD->getBody(), Info, Scratch, nullptr);
14106 }
14107
14108 return Diags.empty();
14109}
14110
14111bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14112 const FunctionDecl *FD,
14113 SmallVectorImpl<
14114 PartialDiagnosticAt> &Diags) {
14115 assert(!E->isValueDependent() &&((!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14116, __PRETTY_FUNCTION__))
14116 "Expression evaluator can't be called on a dependent expression.")((!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14116, __PRETTY_FUNCTION__))
;
14117
14118 Expr::EvalStatus Status;
14119 Status.Diag = &Diags;
14120
14121 EvalInfo Info(FD->getASTContext(), Status,
14122 EvalInfo::EM_ConstantExpressionUnevaluated);
14123 Info.InConstantContext = true;
14124 Info.CheckingPotentialConstantExpression = true;
14125
14126 // Fabricate a call stack frame to give the arguments a plausible cover story.
14127 ArrayRef<const Expr*> Args;
14128 ArgVector ArgValues(0);
14129 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14130 (void)Success;
14131 assert(Success &&((Success && "Failed to set up arguments for potential constant evaluation"
) ? static_cast<void> (0) : __assert_fail ("Success && \"Failed to set up arguments for potential constant evaluation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14132, __PRETTY_FUNCTION__))
14132 "Failed to set up arguments for potential constant evaluation")((Success && "Failed to set up arguments for potential constant evaluation"
) ? static_cast<void> (0) : __assert_fail ("Success && \"Failed to set up arguments for potential constant evaluation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/lib/AST/ExprConstant.cpp"
, 14132, __PRETTY_FUNCTION__))
;
14133 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14134
14135 APValue ResultScratch;
14136 Evaluate(ResultScratch, Info, E);
14137 return Diags.empty();
14138}
14139
14140bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14141 unsigned Type) const {
14142 if (!getType()->isPointerType())
14143 return false;
14144
14145 Expr::EvalStatus Status;
14146 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14147 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14148}

/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
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 defines the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getBeginLoc().print(OS, SrcMgr);
85/// @endcode
86class alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 276, __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 /// Print only the nested name specifier part of a fully-qualified name,
314 /// including the '::' at the end. E.g.
315 /// when `printQualifiedName(D)` prints "A::B::i",
316 /// this function prints "A::B::".
317 void printNestedNameSpecifier(raw_ostream &OS) const;
318 void printNestedNameSpecifier(raw_ostream &OS,
319 const PrintingPolicy &Policy) const;
320
321 // FIXME: Remove string version.
322 std::string getQualifiedNameAsString() const;
323
324 /// Appends a human-readable name for this declaration into the given stream.
325 ///
326 /// This is the method invoked by Sema when displaying a NamedDecl
327 /// in a diagnostic. It does not necessarily produce the same
328 /// result as printName(); for example, class template
329 /// specializations are printed with their template arguments.
330 virtual void getNameForDiagnostic(raw_ostream &OS,
331 const PrintingPolicy &Policy,
332 bool Qualified) const;
333
334 /// Determine whether this declaration, if known to be well-formed within
335 /// its context, will replace the declaration OldD if introduced into scope.
336 ///
337 /// A declaration will replace another declaration if, for example, it is
338 /// a redeclaration of the same variable or function, but not if it is a
339 /// declaration of a different kind (function vs. class) or an overloaded
340 /// function.
341 ///
342 /// \param IsKnownNewer \c true if this declaration is known to be newer
343 /// than \p OldD (for instance, if this declaration is newly-created).
344 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
345
346 /// Determine whether this declaration has linkage.
347 bool hasLinkage() const;
348
349 using Decl::isModulePrivate;
350 using Decl::setModulePrivate;
351
352 /// Determine whether this declaration is a C++ class member.
353 bool isCXXClassMember() const {
354 const DeclContext *DC = getDeclContext();
355
356 // C++0x [class.mem]p1:
357 // The enumerators of an unscoped enumeration defined in
358 // the class are members of the class.
359 if (isa<EnumDecl>(DC))
360 DC = DC->getRedeclContext();
361
362 return DC->isRecord();
363 }
364
365 /// Determine whether the given declaration is an instance member of
366 /// a C++ class.
367 bool isCXXInstanceMember() const;
368
369 /// Determine what kind of linkage this entity has.
370 ///
371 /// This is not the linkage as defined by the standard or the codegen notion
372 /// of linkage. It is just an implementation detail that is used to compute
373 /// those.
374 Linkage getLinkageInternal() const;
375
376 /// Get the linkage from a semantic point of view. Entities in
377 /// anonymous namespaces are external (in c++98).
378 Linkage getFormalLinkage() const {
379 return clang::getFormalLinkage(getLinkageInternal());
380 }
381
382 /// True if this decl has external linkage.
383 bool hasExternalFormalLinkage() const {
384 return isExternalFormalLinkage(getLinkageInternal());
385 }
386
387 bool isExternallyVisible() const {
388 return clang::isExternallyVisible(getLinkageInternal());
389 }
390
391 /// Determine whether this declaration can be redeclared in a
392 /// different translation unit.
393 bool isExternallyDeclarable() const {
394 return isExternallyVisible() && !getOwningModuleForLinkage();
395 }
396
397 /// Determines the visibility of this entity.
398 Visibility getVisibility() const {
399 return getLinkageAndVisibility().getVisibility();
400 }
401
402 /// Determines the linkage and visibility of this entity.
403 LinkageInfo getLinkageAndVisibility() const;
404
405 /// Kinds of explicit visibility.
406 enum ExplicitVisibilityKind {
407 /// Do an LV computation for, ultimately, a type.
408 /// Visibility may be restricted by type visibility settings and
409 /// the visibility of template arguments.
410 VisibilityForType,
411
412 /// Do an LV computation for, ultimately, a non-type declaration.
413 /// Visibility may be restricted by value visibility settings and
414 /// the visibility of template arguments.
415 VisibilityForValue
416 };
417
418 /// If visibility was explicitly specified for this
419 /// declaration, return that visibility.
420 Optional<Visibility>
421 getExplicitVisibility(ExplicitVisibilityKind kind) const;
422
423 /// True if the computed linkage is valid. Used for consistency
424 /// checking. Should always return true.
425 bool isLinkageValid() const;
426
427 /// True if something has required us to compute the linkage
428 /// of this declaration.
429 ///
430 /// Language features which can retroactively change linkage (like a
431 /// typedef name for linkage purposes) may need to consider this,
432 /// but hopefully only in transitory ways during parsing.
433 bool hasLinkageBeenComputed() const {
434 return hasCachedLinkage();
435 }
436
437 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
438 /// the underlying named decl.
439 NamedDecl *getUnderlyingDecl() {
440 // Fast-path the common case.
441 if (this->getKind() != UsingShadow &&
442 this->getKind() != ConstructorUsingShadow &&
443 this->getKind() != ObjCCompatibleAlias &&
444 this->getKind() != NamespaceAlias)
445 return this;
446
447 return getUnderlyingDeclImpl();
448 }
449 const NamedDecl *getUnderlyingDecl() const {
450 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
451 }
452
453 NamedDecl *getMostRecentDecl() {
454 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
455 }
456 const NamedDecl *getMostRecentDecl() const {
457 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
458 }
459
460 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
461
462 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
463 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
464};
465
466inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
467 ND.printName(OS);
468 return OS;
469}
470
471/// Represents the declaration of a label. Labels also have a
472/// corresponding LabelStmt, which indicates the position that the label was
473/// defined at. For normal labels, the location of the decl is the same as the
474/// location of the statement. For GNU local labels (__label__), the decl
475/// location is where the __label__ is.
476class LabelDecl : public NamedDecl {
477 LabelStmt *TheStmt;
478 StringRef MSAsmName;
479 bool MSAsmNameResolved = false;
480
481 /// For normal labels, this is the same as the main declaration
482 /// label, i.e., the location of the identifier; for GNU local labels,
483 /// this is the location of the __label__ keyword.
484 SourceLocation LocStart;
485
486 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
487 LabelStmt *S, SourceLocation StartL)
488 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
489
490 void anchor() override;
491
492public:
493 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
494 SourceLocation IdentL, IdentifierInfo *II);
495 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
496 SourceLocation IdentL, IdentifierInfo *II,
497 SourceLocation GnuLabelL);
498 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
499
500 LabelStmt *getStmt() const { return TheStmt; }
501 void setStmt(LabelStmt *T) { TheStmt = T; }
502
503 bool isGnuLocal() const { return LocStart != getLocation(); }
504 void setLocStart(SourceLocation L) { LocStart = L; }
505
506 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
507 return SourceRange(LocStart, getLocation());
508 }
509
510 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
511 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
512 void setMSAsmLabel(StringRef Name);
513 StringRef getMSAsmLabel() const { return MSAsmName; }
514 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
515
516 // Implement isa/cast/dyncast/etc.
517 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
518 static bool classofKind(Kind K) { return K == Label; }
519};
520
521/// Represent a C++ namespace.
522class NamespaceDecl : public NamedDecl, public DeclContext,
523 public Redeclarable<NamespaceDecl>
524{
525 /// The starting location of the source range, pointing
526 /// to either the namespace or the inline keyword.
527 SourceLocation LocStart;
528
529 /// The ending location of the source range.
530 SourceLocation RBraceLoc;
531
532 /// A pointer to either the anonymous namespace that lives just inside
533 /// this namespace or to the first namespace in the chain (the latter case
534 /// only when this is not the first in the chain), along with a
535 /// boolean value indicating whether this is an inline namespace.
536 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
537
538 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
539 SourceLocation StartLoc, SourceLocation IdLoc,
540 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
541
542 using redeclarable_base = Redeclarable<NamespaceDecl>;
543
544 NamespaceDecl *getNextRedeclarationImpl() override;
545 NamespaceDecl *getPreviousDeclImpl() override;
546 NamespaceDecl *getMostRecentDeclImpl() override;
547
548public:
549 friend class ASTDeclReader;
550 friend class ASTDeclWriter;
551
552 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
553 bool Inline, SourceLocation StartLoc,
554 SourceLocation IdLoc, IdentifierInfo *Id,
555 NamespaceDecl *PrevDecl);
556
557 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
558
559 using redecl_range = redeclarable_base::redecl_range;
560 using redecl_iterator = redeclarable_base::redecl_iterator;
561
562 using redeclarable_base::redecls_begin;
563 using redeclarable_base::redecls_end;
564 using redeclarable_base::redecls;
565 using redeclarable_base::getPreviousDecl;
566 using redeclarable_base::getMostRecentDecl;
567 using redeclarable_base::isFirstDecl;
568
569 /// Returns true if this is an anonymous namespace declaration.
570 ///
571 /// For example:
572 /// \code
573 /// namespace {
574 /// ...
575 /// };
576 /// \endcode
577 /// q.v. C++ [namespace.unnamed]
578 bool isAnonymousNamespace() const {
579 return !getIdentifier();
580 }
581
582 /// Returns true if this is an inline namespace declaration.
583 bool isInline() const {
584 return AnonOrFirstNamespaceAndInline.getInt();
585 }
586
587 /// Set whether this is an inline namespace declaration.
588 void setInline(bool Inline) {
589 AnonOrFirstNamespaceAndInline.setInt(Inline);
590 }
591
592 /// Get the original (first) namespace declaration.
593 NamespaceDecl *getOriginalNamespace();
594
595 /// Get the original (first) namespace declaration.
596 const NamespaceDecl *getOriginalNamespace() const;
597
598 /// Return true if this declaration is an original (first) declaration
599 /// of the namespace. This is false for non-original (subsequent) namespace
600 /// declarations and anonymous namespaces.
601 bool isOriginalNamespace() const;
602
603 /// Retrieve the anonymous namespace nested inside this namespace,
604 /// if any.
605 NamespaceDecl *getAnonymousNamespace() const {
606 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
607 }
608
609 void setAnonymousNamespace(NamespaceDecl *D) {
610 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
611 }
612
613 /// Retrieves the canonical declaration of this namespace.
614 NamespaceDecl *getCanonicalDecl() override {
615 return getOriginalNamespace();
616 }
617 const NamespaceDecl *getCanonicalDecl() const {
618 return getOriginalNamespace();
619 }
620
621 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
622 return SourceRange(LocStart, RBraceLoc);
623 }
624
625 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
626 SourceLocation getRBraceLoc() const { return RBraceLoc; }
627 void setLocStart(SourceLocation L) { LocStart = L; }
628 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
629
630 // Implement isa/cast/dyncast/etc.
631 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
632 static bool classofKind(Kind K) { return K == Namespace; }
633 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
634 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
635 }
636 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
637 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
638 }
639};
640
641/// Represent the declaration of a variable (in which case it is
642/// an lvalue) a function (in which case it is a function designator) or
643/// an enum constant.
644class ValueDecl : public NamedDecl {
645 QualType DeclType;
646
647 void anchor() override;
648
649protected:
650 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
651 DeclarationName N, QualType T)
652 : NamedDecl(DK, DC, L, N), DeclType(T) {}
653
654public:
655 QualType getType() const { return DeclType; }
656 void setType(QualType newType) { DeclType = newType; }
657
658 /// Determine whether this symbol is weakly-imported,
659 /// or declared with the weak or weak-ref attr.
660 bool isWeak() const;
661
662 // Implement isa/cast/dyncast/etc.
663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
664 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
665};
666
667/// A struct with extended info about a syntactic
668/// name qualifier, to be used for the case of out-of-line declarations.
669struct QualifierInfo {
670 NestedNameSpecifierLoc QualifierLoc;
671
672 /// The number of "outer" template parameter lists.
673 /// The count includes all of the template parameter lists that were matched
674 /// against the template-ids occurring into the NNS and possibly (in the
675 /// case of an explicit specialization) a final "template <>".
676 unsigned NumTemplParamLists = 0;
677
678 /// A new-allocated array of size NumTemplParamLists,
679 /// containing pointers to the "outer" template parameter lists.
680 /// It includes all of the template parameter lists that were matched
681 /// against the template-ids occurring into the NNS and possibly (in the
682 /// case of an explicit specialization) a final "template <>".
683 TemplateParameterList** TemplParamLists = nullptr;
684
685 QualifierInfo() = default;
686 QualifierInfo(const QualifierInfo &) = delete;
687 QualifierInfo& operator=(const QualifierInfo &) = delete;
688
689 /// Sets info about "outer" template parameter lists.
690 void setTemplateParameterListsInfo(ASTContext &Context,
691 ArrayRef<TemplateParameterList *> TPLists);
692};
693
694/// Represents a ValueDecl that came out of a declarator.
695/// Contains type source information through TypeSourceInfo.
696class DeclaratorDecl : public ValueDecl {
697 // A struct representing both a TInfo and a syntactic qualifier,
698 // to be used for the (uncommon) case of out-of-line declarations.
699 struct ExtInfo : public QualifierInfo {
700 TypeSourceInfo *TInfo;
701 };
702
703 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
704
705 /// The start of the source range for this declaration,
706 /// ignoring outer template declarations.
707 SourceLocation InnerLocStart;
708
709 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
710 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
711 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
712
713protected:
714 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
715 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
716 SourceLocation StartL)
717 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
718
719public:
720 friend class ASTDeclReader;
721 friend class ASTDeclWriter;
722
723 TypeSourceInfo *getTypeSourceInfo() const {
724 return hasExtInfo()
725 ? getExtInfo()->TInfo
726 : DeclInfo.get<TypeSourceInfo*>();
727 }
728
729 void setTypeSourceInfo(TypeSourceInfo *TI) {
730 if (hasExtInfo())
731 getExtInfo()->TInfo = TI;
732 else
733 DeclInfo = TI;
734 }
735
736 /// Return start of source range ignoring outer template declarations.
737 SourceLocation getInnerLocStart() const { return InnerLocStart; }
738 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
739
740 /// Return start of source range taking into account any outer template
741 /// declarations.
742 SourceLocation getOuterLocStart() const;
743
744 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
745
746 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
747 return getOuterLocStart();
748 }
749
750 /// Retrieve the nested-name-specifier that qualifies the name of this
751 /// declaration, if it was present in the source.
752 NestedNameSpecifier *getQualifier() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
754 : nullptr;
755 }
756
757 /// Retrieve the nested-name-specifier (with source-location
758 /// information) that qualifies the name of this declaration, if it was
759 /// present in the source.
760 NestedNameSpecifierLoc getQualifierLoc() const {
761 return hasExtInfo() ? getExtInfo()->QualifierLoc
762 : NestedNameSpecifierLoc();
763 }
764
765 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
766
767 unsigned getNumTemplateParameterLists() const {
768 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
769 }
770
771 TemplateParameterList *getTemplateParameterList(unsigned index) const {
772 assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast<
void> (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 772, __PRETTY_FUNCTION__))
;
773 return getExtInfo()->TemplParamLists[index];
774 }
775
776 void setTemplateParameterListsInfo(ASTContext &Context,
777 ArrayRef<TemplateParameterList *> TPLists);
778
779 SourceLocation getTypeSpecStartLoc() const;
780
781 // Implement isa/cast/dyncast/etc.
782 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
783 static bool classofKind(Kind K) {
784 return K >= firstDeclarator && K <= lastDeclarator;
785 }
786};
787
788/// Structure used to store a statement, the constant value to
789/// which it was evaluated (if any), and whether or not the statement
790/// is an integral constant expression (if known).
791struct EvaluatedStmt {
792 /// Whether this statement was already evaluated.
793 bool WasEvaluated : 1;
794
795 /// Whether this statement is being evaluated.
796 bool IsEvaluating : 1;
797
798 /// Whether we already checked whether this statement was an
799 /// integral constant expression.
800 bool CheckedICE : 1;
801
802 /// Whether we are checking whether this statement is an
803 /// integral constant expression.
804 bool CheckingICE : 1;
805
806 /// Whether this statement is an integral constant expression,
807 /// or in C++11, whether the statement is a constant expression. Only
808 /// valid if CheckedICE is true.
809 bool IsICE : 1;
810
811 /// Whether this variable is known to have constant destruction. That is,
812 /// whether running the destructor on the initial value is a side-effect
813 /// (and doesn't inspect any state that might have changed during program
814 /// execution). This is currently only computed if the destructor is
815 /// non-trivial.
816 bool HasConstantDestruction : 1;
817
818 Stmt *Value;
819 APValue Evaluated;
820
821 EvaluatedStmt()
822 : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
823 CheckingICE(false), IsICE(false), HasConstantDestruction(false) {}
824};
825
826/// Represents a variable declaration or definition.
827class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
828public:
829 /// Initialization styles.
830 enum InitializationStyle {
831 /// C-style initialization with assignment
832 CInit,
833
834 /// Call-style initialization (C++98)
835 CallInit,
836
837 /// Direct list-initialization (C++11)
838 ListInit
839 };
840
841 /// Kinds of thread-local storage.
842 enum TLSKind {
843 /// Not a TLS variable.
844 TLS_None,
845
846 /// TLS with a known-constant initializer.
847 TLS_Static,
848
849 /// TLS with a dynamic initializer.
850 TLS_Dynamic
851 };
852
853 /// Return the string used to specify the storage class \p SC.
854 ///
855 /// It is illegal to call this function with SC == None.
856 static const char *getStorageClassSpecifierString(StorageClass SC);
857
858protected:
859 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
860 // have allocated the auxiliary struct of information there.
861 //
862 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
863 // this as *many* VarDecls are ParmVarDecls that don't have default
864 // arguments. We could save some space by moving this pointer union to be
865 // allocated in trailing space when necessary.
866 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
867
868 /// The initializer for this variable or, for a ParmVarDecl, the
869 /// C++ default argument.
870 mutable InitType Init;
871
872private:
873 friend class ASTDeclReader;
874 friend class ASTNodeImporter;
875 friend class StmtIteratorBase;
876
877 class VarDeclBitfields {
878 friend class ASTDeclReader;
879 friend class VarDecl;
880
881 unsigned SClass : 3;
882 unsigned TSCSpec : 2;
883 unsigned InitStyle : 2;
884
885 /// Whether this variable is an ARC pseudo-__strong variable; see
886 /// isARCPseudoStrong() for details.
887 unsigned ARCPseudoStrong : 1;
888 };
889 enum { NumVarDeclBits = 8 };
890
891protected:
892 enum { NumParameterIndexBits = 8 };
893
894 enum DefaultArgKind {
895 DAK_None,
896 DAK_Unparsed,
897 DAK_Uninstantiated,
898 DAK_Normal
899 };
900
901 class ParmVarDeclBitfields {
902 friend class ASTDeclReader;
903 friend class ParmVarDecl;
904
905 unsigned : NumVarDeclBits;
906
907 /// Whether this parameter inherits a default argument from a
908 /// prior declaration.
909 unsigned HasInheritedDefaultArg : 1;
910
911 /// Describes the kind of default argument for this parameter. By default
912 /// this is none. If this is normal, then the default argument is stored in
913 /// the \c VarDecl initializer expression unless we were unable to parse
914 /// (even an invalid) expression for the default argument.
915 unsigned DefaultArgKind : 2;
916
917 /// Whether this parameter undergoes K&R argument promotion.
918 unsigned IsKNRPromoted : 1;
919
920 /// Whether this parameter is an ObjC method parameter or not.
921 unsigned IsObjCMethodParam : 1;
922
923 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
924 /// Otherwise, the number of function parameter scopes enclosing
925 /// the function parameter scope in which this parameter was
926 /// declared.
927 unsigned ScopeDepthOrObjCQuals : 7;
928
929 /// The number of parameters preceding this parameter in the
930 /// function parameter scope in which it was declared.
931 unsigned ParameterIndex : NumParameterIndexBits;
932 };
933
934 class NonParmVarDeclBitfields {
935 friend class ASTDeclReader;
936 friend class ImplicitParamDecl;
937 friend class VarDecl;
938
939 unsigned : NumVarDeclBits;
940
941 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
942 /// Whether this variable is a definition which was demoted due to
943 /// module merge.
944 unsigned IsThisDeclarationADemotedDefinition : 1;
945
946 /// Whether this variable is the exception variable in a C++ catch
947 /// or an Objective-C @catch statement.
948 unsigned ExceptionVar : 1;
949
950 /// Whether this local variable could be allocated in the return
951 /// slot of its function, enabling the named return value optimization
952 /// (NRVO).
953 unsigned NRVOVariable : 1;
954
955 /// Whether this variable is the for-range-declaration in a C++0x
956 /// for-range statement.
957 unsigned CXXForRangeDecl : 1;
958
959 /// Whether this variable is the for-in loop declaration in Objective-C.
960 unsigned ObjCForDecl : 1;
961
962 /// Whether this variable is (C++1z) inline.
963 unsigned IsInline : 1;
964
965 /// Whether this variable has (C++1z) inline explicitly specified.
966 unsigned IsInlineSpecified : 1;
967
968 /// Whether this variable is (C++0x) constexpr.
969 unsigned IsConstexpr : 1;
970
971 /// Whether this variable is the implicit variable for a lambda
972 /// init-capture.
973 unsigned IsInitCapture : 1;
974
975 /// Whether this local extern variable's previous declaration was
976 /// declared in the same block scope. This controls whether we should merge
977 /// the type of this declaration with its previous declaration.
978 unsigned PreviousDeclInSameBlockScope : 1;
979
980 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
981 /// something else.
982 unsigned ImplicitParamKind : 3;
983
984 unsigned EscapingByref : 1;
985 };
986
987 union {
988 unsigned AllBits;
989 VarDeclBitfields VarDeclBits;
990 ParmVarDeclBitfields ParmVarDeclBits;
991 NonParmVarDeclBitfields NonParmVarDeclBits;
992 };
993
994 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
995 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
996 TypeSourceInfo *TInfo, StorageClass SC);
997
998 using redeclarable_base = Redeclarable<VarDecl>;
999
1000 VarDecl *getNextRedeclarationImpl() override {
1001 return getNextRedeclaration();
1002 }
1003
1004 VarDecl *getPreviousDeclImpl() override {
1005 return getPreviousDecl();
1006 }
1007
1008 VarDecl *getMostRecentDeclImpl() override {
1009 return getMostRecentDecl();
1010 }
1011
1012public:
1013 using redecl_range = redeclarable_base::redecl_range;
1014 using redecl_iterator = redeclarable_base::redecl_iterator;
1015
1016 using redeclarable_base::redecls_begin;
1017 using redeclarable_base::redecls_end;
1018 using redeclarable_base::redecls;
1019 using redeclarable_base::getPreviousDecl;
1020 using redeclarable_base::getMostRecentDecl;
1021 using redeclarable_base::isFirstDecl;
1022
1023 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1024 SourceLocation StartLoc, SourceLocation IdLoc,
1025 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1026 StorageClass S);
1027
1028 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1029
1030 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1031
1032 /// Returns the storage class as written in the source. For the
1033 /// computed linkage of symbol, see getLinkage.
1034 StorageClass getStorageClass() const {
1035 return (StorageClass) VarDeclBits.SClass;
1036 }
1037 void setStorageClass(StorageClass SC);
1038
1039 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1040 VarDeclBits.TSCSpec = TSC;
1041 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1041, __PRETTY_FUNCTION__))
;
1042 }
1043 ThreadStorageClassSpecifier getTSCSpec() const {
1044 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1045 }
1046 TLSKind getTLSKind() const;
1047
1048 /// Returns true if a variable with function scope is a non-static local
1049 /// variable.
1050 bool hasLocalStorage() const {
1051 if (getStorageClass() == SC_None) {
1052 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1053 // used to describe variables allocated in global memory and which are
1054 // accessed inside a kernel(s) as read-only variables. As such, variables
1055 // in constant address space cannot have local storage.
1056 if (getType().getAddressSpace() == LangAS::opencl_constant)
1057 return false;
1058 // Second check is for C++11 [dcl.stc]p4.
1059 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1060 }
1061
1062 // Global Named Register (GNU extension)
1063 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1064 return false;
1065
1066 // Return true for: Auto, Register.
1067 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1068
1069 return getStorageClass() >= SC_Auto;
1070 }
1071
1072 /// Returns true if a variable with function scope is a static local
1073 /// variable.
1074 bool isStaticLocal() const {
1075 return (getStorageClass() == SC_Static ||
1076 // C++11 [dcl.stc]p4
1077 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1078 && !isFileVarDecl();
1079 }
1080
1081 /// Returns true if a variable has extern or __private_extern__
1082 /// storage.
1083 bool hasExternalStorage() const {
1084 return getStorageClass() == SC_Extern ||
1085 getStorageClass() == SC_PrivateExtern;
1086 }
1087
1088 /// Returns true for all variables that do not have local storage.
1089 ///
1090 /// This includes all global variables as well as static variables declared
1091 /// within a function.
1092 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1093
1094 /// Get the storage duration of this variable, per C++ [basic.stc].
1095 StorageDuration getStorageDuration() const {
1096 return hasLocalStorage() ? SD_Automatic :
1097 getTSCSpec() ? SD_Thread : SD_Static;
1098 }
1099
1100 /// Compute the language linkage.
1101 LanguageLinkage getLanguageLinkage() const;
1102
1103 /// Determines whether this variable is a variable with external, C linkage.
1104 bool isExternC() const;
1105
1106 /// Determines whether this variable's context is, or is nested within,
1107 /// a C++ extern "C" linkage spec.
1108 bool isInExternCContext() const;
1109
1110 /// Determines whether this variable's context is, or is nested within,
1111 /// a C++ extern "C++" linkage spec.
1112 bool isInExternCXXContext() const;
1113
1114 /// Returns true for local variable declarations other than parameters.
1115 /// Note that this includes static variables inside of functions. It also
1116 /// includes variables inside blocks.
1117 ///
1118 /// void foo() { int x; static int y; extern int z; }
1119 bool isLocalVarDecl() const {
1120 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1121 return false;
1122 if (const DeclContext *DC = getLexicalDeclContext())
1123 return DC->getRedeclContext()->isFunctionOrMethod();
1124 return false;
1125 }
1126
1127 /// Similar to isLocalVarDecl but also includes parameters.
1128 bool isLocalVarDeclOrParm() const {
1129 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1130 }
1131
1132 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1133 bool isFunctionOrMethodVarDecl() const {
1134 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1135 return false;
1136 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1137 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1138 }
1139
1140 /// Determines whether this is a static data member.
1141 ///
1142 /// This will only be true in C++, and applies to, e.g., the
1143 /// variable 'x' in:
1144 /// \code
1145 /// struct S {
1146 /// static int x;
1147 /// };
1148 /// \endcode
1149 bool isStaticDataMember() const {
1150 // If it wasn't static, it would be a FieldDecl.
1151 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1152 }
1153
1154 VarDecl *getCanonicalDecl() override;
1155 const VarDecl *getCanonicalDecl() const {
1156 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1157 }
1158
1159 enum DefinitionKind {
1160 /// This declaration is only a declaration.
1161 DeclarationOnly,
1162
1163 /// This declaration is a tentative definition.
1164 TentativeDefinition,
1165
1166 /// This declaration is definitely a definition.
1167 Definition
1168 };
1169
1170 /// Check whether this declaration is a definition. If this could be
1171 /// a tentative definition (in C), don't check whether there's an overriding
1172 /// definition.
1173 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1174 DefinitionKind isThisDeclarationADefinition() const {
1175 return isThisDeclarationADefinition(getASTContext());
1176 }
1177
1178 /// Check whether this variable is defined in this translation unit.
1179 DefinitionKind hasDefinition(ASTContext &) const;
1180 DefinitionKind hasDefinition() const {
1181 return hasDefinition(getASTContext());
1182 }
1183
1184 /// Get the tentative definition that acts as the real definition in a TU.
1185 /// Returns null if there is a proper definition available.
1186 VarDecl *getActingDefinition();
1187 const VarDecl *getActingDefinition() const {
1188 return const_cast<VarDecl*>(this)->getActingDefinition();
1189 }
1190
1191 /// Get the real (not just tentative) definition for this declaration.
1192 VarDecl *getDefinition(ASTContext &);
1193 const VarDecl *getDefinition(ASTContext &C) const {
1194 return const_cast<VarDecl*>(this)->getDefinition(C);
1195 }
1196 VarDecl *getDefinition() {
1197 return getDefinition(getASTContext());
1198 }
1199 const VarDecl *getDefinition() const {
1200 return const_cast<VarDecl*>(this)->getDefinition();
1201 }
1202
1203 /// Determine whether this is or was instantiated from an out-of-line
1204 /// definition of a static data member.
1205 bool isOutOfLine() const override;
1206
1207 /// Returns true for file scoped variable declaration.
1208 bool isFileVarDecl() const {
1209 Kind K = getKind();
1210 if (K == ParmVar || K == ImplicitParam)
1211 return false;
1212
1213 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1214 return true;
1215
1216 if (isStaticDataMember())
1217 return true;
1218
1219 return false;
1220 }
1221
1222 /// Get the initializer for this variable, no matter which
1223 /// declaration it is attached to.
1224 const Expr *getAnyInitializer() const {
1225 const VarDecl *D;
1226 return getAnyInitializer(D);
1227 }
1228
1229 /// Get the initializer for this variable, no matter which
1230 /// declaration it is attached to. Also get that declaration.
1231 const Expr *getAnyInitializer(const VarDecl *&D) const;
1232
1233 bool hasInit() const;
1234 const Expr *getInit() const {
1235 return const_cast<VarDecl *>(this)->getInit();
1236 }
1237 Expr *getInit();
1238
1239 /// Retrieve the address of the initializer expression.
1240 Stmt **getInitAddress();
1241
1242 void setInit(Expr *I);
1243
1244 /// Get the initializing declaration of this variable, if any. This is
1245 /// usually the definition, except that for a static data member it can be
1246 /// the in-class declaration.
1247 VarDecl *getInitializingDeclaration();
1248 const VarDecl *getInitializingDeclaration() const {
1249 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1250 }
1251
1252 /// Determine whether this variable's value might be usable in a
1253 /// constant expression, according to the relevant language standard.
1254 /// This only checks properties of the declaration, and does not check
1255 /// whether the initializer is in fact a constant expression.
1256 bool mightBeUsableInConstantExpressions(ASTContext &C) const;
1257
1258 /// Determine whether this variable's value can be used in a
1259 /// constant expression, according to the relevant language standard,
1260 /// including checking whether it was initialized by a constant expression.
1261 bool isUsableInConstantExpressions(ASTContext &C) const;
1262
1263 EvaluatedStmt *ensureEvaluatedStmt() const;
1264
1265 /// Attempt to evaluate the value of the initializer attached to this
1266 /// declaration, and produce notes explaining why it cannot be evaluated or is
1267 /// not a constant expression. Returns a pointer to the value if evaluation
1268 /// succeeded, 0 otherwise.
1269 APValue *evaluateValue() const;
1270 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1271
1272 /// Return the already-evaluated value of this variable's
1273 /// initializer, or NULL if the value is not yet known. Returns pointer
1274 /// to untyped APValue if the value could not be evaluated.
1275 APValue *getEvaluatedValue() const;
1276
1277 /// Evaluate the destruction of this variable to determine if it constitutes
1278 /// constant destruction.
1279 ///
1280 /// \pre isInitICE()
1281 /// \return \c true if this variable has constant destruction, \c false if
1282 /// not.
1283 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1284
1285 /// Determines whether it is already known whether the
1286 /// initializer is an integral constant expression or not.
1287 bool isInitKnownICE() const;
1288
1289 /// Determines whether the initializer is an integral constant
1290 /// expression, or in C++11, whether the initializer is a constant
1291 /// expression.
1292 ///
1293 /// \pre isInitKnownICE()
1294 bool isInitICE() const;
1295
1296 /// Determine whether the value of the initializer attached to this
1297 /// declaration is an integral constant expression.
1298 bool checkInitIsICE() const;
1299
1300 void setInitStyle(InitializationStyle Style) {
1301 VarDeclBits.InitStyle = Style;
1302 }
1303
1304 /// The style of initialization for this declaration.
1305 ///
1306 /// C-style initialization is "int x = 1;". Call-style initialization is
1307 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1308 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1309 /// expression for class types. List-style initialization is C++11 syntax,
1310 /// e.g. "int x{1};". Clients can distinguish between different forms of
1311 /// initialization by checking this value. In particular, "int x = {1};" is
1312 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1313 /// Init expression in all three cases is an InitListExpr.
1314 InitializationStyle getInitStyle() const {
1315 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1316 }
1317
1318 /// Whether the initializer is a direct-initializer (list or call).
1319 bool isDirectInit() const {
1320 return getInitStyle() != CInit;
1321 }
1322
1323 /// If this definition should pretend to be a declaration.
1324 bool isThisDeclarationADemotedDefinition() const {
1325 return isa<ParmVarDecl>(this) ? false :
1326 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1327 }
1328
1329 /// This is a definition which should be demoted to a declaration.
1330 ///
1331 /// In some cases (mostly module merging) we can end up with two visible
1332 /// definitions one of which needs to be demoted to a declaration to keep
1333 /// the AST invariants.
1334 void demoteThisDefinitionToDeclaration() {
1335 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1335, __PRETTY_FUNCTION__))
;
1336 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1336, __PRETTY_FUNCTION__))
;
1337 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1338 }
1339
1340 /// Determine whether this variable is the exception variable in a
1341 /// C++ catch statememt or an Objective-C \@catch statement.
1342 bool isExceptionVariable() const {
1343 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1344 }
1345 void setExceptionVariable(bool EV) {
1346 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1346, __PRETTY_FUNCTION__))
;
1347 NonParmVarDeclBits.ExceptionVar = EV;
1348 }
1349
1350 /// Determine whether this local variable can be used with the named
1351 /// return value optimization (NRVO).
1352 ///
1353 /// The named return value optimization (NRVO) works by marking certain
1354 /// non-volatile local variables of class type as NRVO objects. These
1355 /// locals can be allocated within the return slot of their containing
1356 /// function, in which case there is no need to copy the object to the
1357 /// return slot when returning from the function. Within the function body,
1358 /// each return that returns the NRVO object will have this variable as its
1359 /// NRVO candidate.
1360 bool isNRVOVariable() const {
1361 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1362 }
1363 void setNRVOVariable(bool NRVO) {
1364 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1364, __PRETTY_FUNCTION__))
;
1365 NonParmVarDeclBits.NRVOVariable = NRVO;
1366 }
1367
1368 /// Determine whether this variable is the for-range-declaration in
1369 /// a C++0x for-range statement.
1370 bool isCXXForRangeDecl() const {
1371 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1372 }
1373 void setCXXForRangeDecl(bool FRD) {
1374 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1374, __PRETTY_FUNCTION__))
;
1375 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1376 }
1377
1378 /// Determine whether this variable is a for-loop declaration for a
1379 /// for-in statement in Objective-C.
1380 bool isObjCForDecl() const {
1381 return NonParmVarDeclBits.ObjCForDecl;
1382 }
1383
1384 void setObjCForDecl(bool FRD) {
1385 NonParmVarDeclBits.ObjCForDecl = FRD;
1386 }
1387
1388 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1389 /// pseudo-__strong variable has a __strong-qualified type but does not
1390 /// actually retain the object written into it. Generally such variables are
1391 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1392 /// the variable is annotated with the objc_externally_retained attribute, 2)
1393 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1394 /// loop.
1395 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1396 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1397
1398 /// Whether this variable is (C++1z) inline.
1399 bool isInline() const {
1400 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1401 }
1402 bool isInlineSpecified() const {
1403 return isa<ParmVarDecl>(this) ? false
1404 : NonParmVarDeclBits.IsInlineSpecified;
1405 }
1406 void setInlineSpecified() {
1407 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1407, __PRETTY_FUNCTION__))
;
1408 NonParmVarDeclBits.IsInline = true;
1409 NonParmVarDeclBits.IsInlineSpecified = true;
1410 }
1411 void setImplicitlyInline() {
1412 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1412, __PRETTY_FUNCTION__))
;
1413 NonParmVarDeclBits.IsInline = true;
1414 }
1415
1416 /// Whether this variable is (C++11) constexpr.
1417 bool isConstexpr() const {
1418 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1419 }
1420 void setConstexpr(bool IC) {
1421 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1421, __PRETTY_FUNCTION__))
;
1422 NonParmVarDeclBits.IsConstexpr = IC;
1423 }
1424
1425 /// Whether this variable is the implicit variable for a lambda init-capture.
1426 bool isInitCapture() const {
1427 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1428 }
1429 void setInitCapture(bool IC) {
1430 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1430, __PRETTY_FUNCTION__))
;
1431 NonParmVarDeclBits.IsInitCapture = IC;
1432 }
1433
1434 /// Determine whether this variable is actually a function parameter pack or
1435 /// init-capture pack.
1436 bool isParameterPack() const;
1437
1438 /// Whether this local extern variable declaration's previous declaration
1439 /// was declared in the same block scope. Only correct in C++.
1440 bool isPreviousDeclInSameBlockScope() const {
1441 return isa<ParmVarDecl>(this)
1442 ? false
1443 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1444 }
1445 void setPreviousDeclInSameBlockScope(bool Same) {
1446 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1446, __PRETTY_FUNCTION__))
;
1447 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1448 }
1449
1450 /// Indicates the capture is a __block variable that is captured by a block
1451 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1452 /// returns false).
1453 bool isEscapingByref() const;
1454
1455 /// Indicates the capture is a __block variable that is never captured by an
1456 /// escaping block.
1457 bool isNonEscapingByref() const;
1458
1459 void setEscapingByref() {
1460 NonParmVarDeclBits.EscapingByref = true;
1461 }
1462
1463 /// Retrieve the variable declaration from which this variable could
1464 /// be instantiated, if it is an instantiation (rather than a non-template).
1465 VarDecl *getTemplateInstantiationPattern() const;
1466
1467 /// If this variable is an instantiated static data member of a
1468 /// class template specialization, returns the templated static data member
1469 /// from which it was instantiated.
1470 VarDecl *getInstantiatedFromStaticDataMember() const;
1471
1472 /// If this variable is an instantiation of a variable template or a
1473 /// static data member of a class template, determine what kind of
1474 /// template specialization or instantiation this is.
1475 TemplateSpecializationKind getTemplateSpecializationKind() const;
1476
1477 /// Get the template specialization kind of this variable for the purposes of
1478 /// template instantiation. This differs from getTemplateSpecializationKind()
1479 /// for an instantiation of a class-scope explicit specialization.
1480 TemplateSpecializationKind
1481 getTemplateSpecializationKindForInstantiation() const;
1482
1483 /// If this variable is an instantiation of a variable template or a
1484 /// static data member of a class template, determine its point of
1485 /// instantiation.
1486 SourceLocation getPointOfInstantiation() const;
1487
1488 /// If this variable is an instantiation of a static data member of a
1489 /// class template specialization, retrieves the member specialization
1490 /// information.
1491 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1492
1493 /// For a static data member that was instantiated from a static
1494 /// data member of a class template, set the template specialiation kind.
1495 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1496 SourceLocation PointOfInstantiation = SourceLocation());
1497
1498 /// Specify that this variable is an instantiation of the
1499 /// static data member VD.
1500 void setInstantiationOfStaticDataMember(VarDecl *VD,
1501 TemplateSpecializationKind TSK);
1502
1503 /// Retrieves the variable template that is described by this
1504 /// variable declaration.
1505 ///
1506 /// Every variable template is represented as a VarTemplateDecl and a
1507 /// VarDecl. The former contains template properties (such as
1508 /// the template parameter lists) while the latter contains the
1509 /// actual description of the template's
1510 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1511 /// VarDecl that from a VarTemplateDecl, while
1512 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1513 /// a VarDecl.
1514 VarTemplateDecl *getDescribedVarTemplate() const;
1515
1516 void setDescribedVarTemplate(VarTemplateDecl *Template);
1517
1518 // Is this variable known to have a definition somewhere in the complete
1519 // program? This may be true even if the declaration has internal linkage and
1520 // has no definition within this source file.
1521 bool isKnownToBeDefined() const;
1522
1523 /// Is destruction of this variable entirely suppressed? If so, the variable
1524 /// need not have a usable destructor at all.
1525 bool isNoDestroy(const ASTContext &) const;
1526
1527 /// Do we need to emit an exit-time destructor for this variable, and if so,
1528 /// what kind?
1529 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1530
1531 // Implement isa/cast/dyncast/etc.
1532 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1533 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1534};
1535
1536class ImplicitParamDecl : public VarDecl {
1537 void anchor() override;
1538
1539public:
1540 /// Defines the kind of the implicit parameter: is this an implicit parameter
1541 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1542 /// context or something else.
1543 enum ImplicitParamKind : unsigned {
1544 /// Parameter for Objective-C 'self' argument
1545 ObjCSelf,
1546
1547 /// Parameter for Objective-C '_cmd' argument
1548 ObjCCmd,
1549
1550 /// Parameter for C++ 'this' argument
1551 CXXThis,
1552
1553 /// Parameter for C++ virtual table pointers
1554 CXXVTT,
1555
1556 /// Parameter for captured context
1557 CapturedContext,
1558
1559 /// Other implicit parameter
1560 Other,
1561 };
1562
1563 /// Create implicit parameter.
1564 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1565 SourceLocation IdLoc, IdentifierInfo *Id,
1566 QualType T, ImplicitParamKind ParamKind);
1567 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1568 ImplicitParamKind ParamKind);
1569
1570 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1571
1572 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1573 IdentifierInfo *Id, QualType Type,
1574 ImplicitParamKind ParamKind)
1575 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1576 /*TInfo=*/nullptr, SC_None) {
1577 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1578 setImplicit();
1579 }
1580
1581 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1582 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1583 SourceLocation(), /*Id=*/nullptr, Type,
1584 /*TInfo=*/nullptr, SC_None) {
1585 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1586 setImplicit();
1587 }
1588
1589 /// Returns the implicit parameter kind.
1590 ImplicitParamKind getParameterKind() const {
1591 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1592 }
1593
1594 // Implement isa/cast/dyncast/etc.
1595 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1596 static bool classofKind(Kind K) { return K == ImplicitParam; }
1597};
1598
1599/// Represents a parameter to a function.
1600class ParmVarDecl : public VarDecl {
1601public:
1602 enum { MaxFunctionScopeDepth = 255 };
1603 enum { MaxFunctionScopeIndex = 255 };
1604
1605protected:
1606 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1607 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1608 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1609 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1610 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast
<void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1610, __PRETTY_FUNCTION__))
;
1611 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1611, __PRETTY_FUNCTION__))
;
1612 assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void
> (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1612, __PRETTY_FUNCTION__))
;
1613 assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1613, __PRETTY_FUNCTION__))
;
1614 setDefaultArg(DefArg);
1615 }
1616
1617public:
1618 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1619 SourceLocation StartLoc,
1620 SourceLocation IdLoc, IdentifierInfo *Id,
1621 QualType T, TypeSourceInfo *TInfo,
1622 StorageClass S, Expr *DefArg);
1623
1624 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1625
1626 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1627
1628 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1629 ParmVarDeclBits.IsObjCMethodParam = true;
1630 setParameterIndex(parameterIndex);
1631 }
1632
1633 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1634 assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1634, __PRETTY_FUNCTION__))
;
1635
1636 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1637 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1638, __PRETTY_FUNCTION__))
1638 && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1638, __PRETTY_FUNCTION__))
;
1639
1640 setParameterIndex(parameterIndex);
1641 }
1642
1643 bool isObjCMethodParameter() const {
1644 return ParmVarDeclBits.IsObjCMethodParam;
1645 }
1646
1647 unsigned getFunctionScopeDepth() const {
1648 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1649 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1650 }
1651
1652 /// Returns the index of this parameter in its prototype or method scope.
1653 unsigned getFunctionScopeIndex() const {
1654 return getParameterIndex();
1655 }
1656
1657 ObjCDeclQualifier getObjCDeclQualifier() const {
1658 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1659 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1660 }
1661 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1662 assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1662, __PRETTY_FUNCTION__))
;
1663 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1664 }
1665
1666 /// True if the value passed to this parameter must undergo
1667 /// K&R-style default argument promotion:
1668 ///
1669 /// C99 6.5.2.2.
1670 /// If the expression that denotes the called function has a type
1671 /// that does not include a prototype, the integer promotions are
1672 /// performed on each argument, and arguments that have type float
1673 /// are promoted to double.
1674 bool isKNRPromoted() const {
1675 return ParmVarDeclBits.IsKNRPromoted;
1676 }
1677 void setKNRPromoted(bool promoted) {
1678 ParmVarDeclBits.IsKNRPromoted = promoted;
1679 }
1680
1681 Expr *getDefaultArg();
1682 const Expr *getDefaultArg() const {
1683 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1684 }
1685
1686 void setDefaultArg(Expr *defarg);
1687
1688 /// Retrieve the source range that covers the entire default
1689 /// argument.
1690 SourceRange getDefaultArgRange() const;
1691 void setUninstantiatedDefaultArg(Expr *arg);
1692 Expr *getUninstantiatedDefaultArg();
1693 const Expr *getUninstantiatedDefaultArg() const {
1694 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1695 }
1696
1697 /// Determines whether this parameter has a default argument,
1698 /// either parsed or not.
1699 bool hasDefaultArg() const;
1700
1701 /// Determines whether this parameter has a default argument that has not
1702 /// yet been parsed. This will occur during the processing of a C++ class
1703 /// whose member functions have default arguments, e.g.,
1704 /// @code
1705 /// class X {
1706 /// public:
1707 /// void f(int x = 17); // x has an unparsed default argument now
1708 /// }; // x has a regular default argument now
1709 /// @endcode
1710 bool hasUnparsedDefaultArg() const {
1711 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1712 }
1713
1714 bool hasUninstantiatedDefaultArg() const {
1715 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1716 }
1717
1718 /// Specify that this parameter has an unparsed default argument.
1719 /// The argument will be replaced with a real default argument via
1720 /// setDefaultArg when the class definition enclosing the function
1721 /// declaration that owns this default argument is completed.
1722 void setUnparsedDefaultArg() {
1723 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1724 }
1725
1726 bool hasInheritedDefaultArg() const {
1727 return ParmVarDeclBits.HasInheritedDefaultArg;
1728 }
1729
1730 void setHasInheritedDefaultArg(bool I = true) {
1731 ParmVarDeclBits.HasInheritedDefaultArg = I;
1732 }
1733
1734 QualType getOriginalType() const;
1735
1736 /// Sets the function declaration that owns this
1737 /// ParmVarDecl. Since ParmVarDecls are often created before the
1738 /// FunctionDecls that own them, this routine is required to update
1739 /// the DeclContext appropriately.
1740 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1741
1742 // Implement isa/cast/dyncast/etc.
1743 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1744 static bool classofKind(Kind K) { return K == ParmVar; }
1745
1746private:
1747 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1748
1749 void setParameterIndex(unsigned parameterIndex) {
1750 if (parameterIndex >= ParameterIndexSentinel) {
1751 setParameterIndexLarge(parameterIndex);
1752 return;
1753 }
1754
1755 ParmVarDeclBits.ParameterIndex = parameterIndex;
1756 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 1756, __PRETTY_FUNCTION__))
;
1757 }
1758 unsigned getParameterIndex() const {
1759 unsigned d = ParmVarDeclBits.ParameterIndex;
1760 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1761 }
1762
1763 void setParameterIndexLarge(unsigned parameterIndex);
1764 unsigned getParameterIndexLarge() const;
1765};
1766
1767enum class MultiVersionKind {
1768 None,
1769 Target,
1770 CPUSpecific,
1771 CPUDispatch
1772};
1773
1774/// Represents a function declaration or definition.
1775///
1776/// Since a given function can be declared several times in a program,
1777/// there may be several FunctionDecls that correspond to that
1778/// function. Only one of those FunctionDecls will be found when
1779/// traversing the list of declarations in the context of the
1780/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1781/// contains all of the information known about the function. Other,
1782/// previous declarations of the function are available via the
1783/// getPreviousDecl() chain.
1784class FunctionDecl : public DeclaratorDecl,
1785 public DeclContext,
1786 public Redeclarable<FunctionDecl> {
1787 // This class stores some data in DeclContext::FunctionDeclBits
1788 // to save some space. Use the provided accessors to access it.
1789public:
1790 /// The kind of templated function a FunctionDecl can be.
1791 enum TemplatedKind {
1792 // Not templated.
1793 TK_NonTemplate,
1794 // The pattern in a function template declaration.
1795 TK_FunctionTemplate,
1796 // A non-template function that is an instantiation or explicit
1797 // specialization of a member of a templated class.
1798 TK_MemberSpecialization,
1799 // An instantiation or explicit specialization of a function template.
1800 // Note: this might have been instantiated from a templated class if it
1801 // is a class-scope explicit specialization.
1802 TK_FunctionTemplateSpecialization,
1803 // A function template specialization that hasn't yet been resolved to a
1804 // particular specialized function template.
1805 TK_DependentFunctionTemplateSpecialization
1806 };
1807
1808private:
1809 /// A new[]'d array of pointers to VarDecls for the formal
1810 /// parameters of this function. This is null if a prototype or if there are
1811 /// no formals.
1812 ParmVarDecl **ParamInfo = nullptr;
1813
1814 LazyDeclStmtPtr Body;
1815
1816 unsigned ODRHash;
1817
1818 /// End part of this FunctionDecl's source range.
1819 ///
1820 /// We could compute the full range in getSourceRange(). However, when we're
1821 /// dealing with a function definition deserialized from a PCH/AST file,
1822 /// we can only compute the full range once the function body has been
1823 /// de-serialized, so it's far better to have the (sometimes-redundant)
1824 /// EndRangeLoc.
1825 SourceLocation EndRangeLoc;
1826
1827 /// The template or declaration that this declaration
1828 /// describes or was instantiated from, respectively.
1829 ///
1830 /// For non-templates, this value will be NULL. For function
1831 /// declarations that describe a function template, this will be a
1832 /// pointer to a FunctionTemplateDecl. For member functions
1833 /// of class template specializations, this will be a MemberSpecializationInfo
1834 /// pointer containing information about the specialization.
1835 /// For function template specializations, this will be a
1836 /// FunctionTemplateSpecializationInfo, which contains information about
1837 /// the template being specialized and the template arguments involved in
1838 /// that specialization.
1839 llvm::PointerUnion4<FunctionTemplateDecl *,
1840 MemberSpecializationInfo *,
1841 FunctionTemplateSpecializationInfo *,
1842 DependentFunctionTemplateSpecializationInfo *>
1843 TemplateOrSpecialization;
1844
1845 /// Provides source/type location info for the declaration name embedded in
1846 /// the DeclaratorDecl base class.
1847 DeclarationNameLoc DNLoc;
1848
1849 /// Specify that this function declaration is actually a function
1850 /// template specialization.
1851 ///
1852 /// \param C the ASTContext.
1853 ///
1854 /// \param Template the function template that this function template
1855 /// specialization specializes.
1856 ///
1857 /// \param TemplateArgs the template arguments that produced this
1858 /// function template specialization from the template.
1859 ///
1860 /// \param InsertPos If non-NULL, the position in the function template
1861 /// specialization set where the function template specialization data will
1862 /// be inserted.
1863 ///
1864 /// \param TSK the kind of template specialization this is.
1865 ///
1866 /// \param TemplateArgsAsWritten location info of template arguments.
1867 ///
1868 /// \param PointOfInstantiation point at which the function template
1869 /// specialization was first instantiated.
1870 void setFunctionTemplateSpecialization(ASTContext &C,
1871 FunctionTemplateDecl *Template,
1872 const TemplateArgumentList *TemplateArgs,
1873 void *InsertPos,
1874 TemplateSpecializationKind TSK,
1875 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1876 SourceLocation PointOfInstantiation);
1877
1878 /// Specify that this record is an instantiation of the
1879 /// member function FD.
1880 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1881 TemplateSpecializationKind TSK);
1882
1883 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1884
1885 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1886 // need to access this bit but we want to avoid making ASTDeclWriter
1887 // a friend of FunctionDeclBitfields just for this.
1888 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1889
1890 /// Whether an ODRHash has been stored.
1891 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1892
1893 /// State that an ODRHash has been stored.
1894 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1895
1896protected:
1897 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1898 const DeclarationNameInfo &NameInfo, QualType T,
1899 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1900 ConstexprSpecKind ConstexprKind);
1901
1902 using redeclarable_base = Redeclarable<FunctionDecl>;
1903
1904 FunctionDecl *getNextRedeclarationImpl() override {
1905 return getNextRedeclaration();
1906 }
1907
1908 FunctionDecl *getPreviousDeclImpl() override {
1909 return getPreviousDecl();
1910 }
1911
1912 FunctionDecl *getMostRecentDeclImpl() override {
1913 return getMostRecentDecl();
1914 }
1915
1916public:
1917 friend class ASTDeclReader;
1918 friend class ASTDeclWriter;
1919
1920 using redecl_range = redeclarable_base::redecl_range;
1921 using redecl_iterator = redeclarable_base::redecl_iterator;
1922
1923 using redeclarable_base::redecls_begin;
1924 using redeclarable_base::redecls_end;
1925 using redeclarable_base::redecls;
1926 using redeclarable_base::getPreviousDecl;
1927 using redeclarable_base::getMostRecentDecl;
1928 using redeclarable_base::isFirstDecl;
1929
1930 static FunctionDecl *
1931 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1932 SourceLocation NLoc, DeclarationName N, QualType T,
1933 TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
1934 bool hasWrittenPrototype = true,
1935 ConstexprSpecKind ConstexprKind = CSK_unspecified) {
1936 DeclarationNameInfo NameInfo(N, NLoc);
1937 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
1938 isInlineSpecified, hasWrittenPrototype,
1939 ConstexprKind);
1940 }
1941
1942 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1943 SourceLocation StartLoc,
1944 const DeclarationNameInfo &NameInfo, QualType T,
1945 TypeSourceInfo *TInfo, StorageClass SC,
1946 bool isInlineSpecified, bool hasWrittenPrototype,
1947 ConstexprSpecKind ConstexprKind);
1948
1949 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1950
1951 DeclarationNameInfo getNameInfo() const {
1952 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1953 }
1954
1955 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1956 bool Qualified) const override;
1957
1958 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1959
1960 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1961
1962 // Function definitions.
1963 //
1964 // A function declaration may be:
1965 // - a non defining declaration,
1966 // - a definition. A function may be defined because:
1967 // - it has a body, or will have it in the case of late parsing.
1968 // - it has an uninstantiated body. The body does not exist because the
1969 // function is not used yet, but the declaration is considered a
1970 // definition and does not allow other definition of this function.
1971 // - it does not have a user specified body, but it does not allow
1972 // redefinition, because it is deleted/defaulted or is defined through
1973 // some other mechanism (alias, ifunc).
1974
1975 /// Returns true if the function has a body.
1976 ///
1977 /// The function body might be in any of the (re-)declarations of this
1978 /// function. The variant that accepts a FunctionDecl pointer will set that
1979 /// function declaration to the actual declaration containing the body (if
1980 /// there is one).
1981 bool hasBody(const FunctionDecl *&Definition) const;
1982
1983 bool hasBody() const override {
1984 const FunctionDecl* Definition;
1985 return hasBody(Definition);
1986 }
1987
1988 /// Returns whether the function has a trivial body that does not require any
1989 /// specific codegen.
1990 bool hasTrivialBody() const;
1991
1992 /// Returns true if the function has a definition that does not need to be
1993 /// instantiated.
1994 ///
1995 /// The variant that accepts a FunctionDecl pointer will set that function
1996 /// declaration to the declaration that is a definition (if there is one).
1997 bool isDefined(const FunctionDecl *&Definition) const;
1998
1999 virtual bool isDefined() const {
2000 const FunctionDecl* Definition;
2001 return isDefined(Definition);
2002 }
2003
2004 /// Get the definition for this declaration.
2005 FunctionDecl *getDefinition() {
2006 const FunctionDecl *Definition;
2007 if (isDefined(Definition))
2008 return const_cast<FunctionDecl *>(Definition);
2009 return nullptr;
2010 }
2011 const FunctionDecl *getDefinition() const {
2012 return const_cast<FunctionDecl *>(this)->getDefinition();
2013 }
2014
2015 /// Retrieve the body (definition) of the function. The function body might be
2016 /// in any of the (re-)declarations of this function. The variant that accepts
2017 /// a FunctionDecl pointer will set that function declaration to the actual
2018 /// declaration containing the body (if there is one).
2019 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2020 /// unnecessary AST de-serialization of the body.
2021 Stmt *getBody(const FunctionDecl *&Definition) const;
2022
2023 Stmt *getBody() const override {
2024 const FunctionDecl* Definition;
2025 return getBody(Definition);
2026 }
2027
2028 /// Returns whether this specific declaration of the function is also a
2029 /// definition that does not contain uninstantiated body.
2030 ///
2031 /// This does not determine whether the function has been defined (e.g., in a
2032 /// previous definition); for that information, use isDefined.
2033 bool isThisDeclarationADefinition() const {
2034 return isDeletedAsWritten() || isDefaulted() || Body || hasSkippedBody() ||
2035 isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
2036 }
2037
2038 /// Returns whether this specific declaration of the function has a body.
2039 bool doesThisDeclarationHaveABody() const {
2040 return Body || isLateTemplateParsed();
2041 }
2042
2043 void setBody(Stmt *B);
2044 void setLazyBody(uint64_t Offset) { Body = Offset; }
2045
2046 /// Whether this function is variadic.
2047 bool isVariadic() const;
2048
2049 /// Whether this function is marked as virtual explicitly.
2050 bool isVirtualAsWritten() const {
2051 return FunctionDeclBits.IsVirtualAsWritten;
2052 }
2053
2054 /// State that this function is marked as virtual explicitly.
2055 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2056
2057 /// Whether this virtual function is pure, i.e. makes the containing class
2058 /// abstract.
2059 bool isPure() const { return FunctionDeclBits.IsPure; }
2060 void setPure(bool P = true);
2061
2062 /// Whether this templated function will be late parsed.
2063 bool isLateTemplateParsed() const {
2064 return FunctionDeclBits.IsLateTemplateParsed;
2065 }
2066
2067 /// State that this templated function will be late parsed.
2068 void setLateTemplateParsed(bool ILT = true) {
2069 FunctionDeclBits.IsLateTemplateParsed = ILT;
2070 }
2071
2072 /// Whether this function is "trivial" in some specialized C++ senses.
2073 /// Can only be true for default constructors, copy constructors,
2074 /// copy assignment operators, and destructors. Not meaningful until
2075 /// the class has been fully built by Sema.
2076 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2077 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2078
2079 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2080 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2081
2082 /// Whether this function is defaulted per C++0x. Only valid for
2083 /// special member functions.
2084 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2085 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2086
2087 /// Whether this function is explicitly defaulted per C++0x. Only valid
2088 /// for special member functions.
2089 bool isExplicitlyDefaulted() const {
2090 return FunctionDeclBits.IsExplicitlyDefaulted;
2091 }
2092
2093 /// State that this function is explicitly defaulted per C++0x. Only valid
2094 /// for special member functions.
2095 void setExplicitlyDefaulted(bool ED = true) {
2096 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2097 }
2098
2099 /// Whether falling off this function implicitly returns null/zero.
2100 /// If a more specific implicit return value is required, front-ends
2101 /// should synthesize the appropriate return statements.
2102 bool hasImplicitReturnZero() const {
2103 return FunctionDeclBits.HasImplicitReturnZero;
2104 }
2105
2106 /// State that falling off this function implicitly returns null/zero.
2107 /// If a more specific implicit return value is required, front-ends
2108 /// should synthesize the appropriate return statements.
2109 void setHasImplicitReturnZero(bool IRZ) {
2110 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2111 }
2112
2113 /// Whether this function has a prototype, either because one
2114 /// was explicitly written or because it was "inherited" by merging
2115 /// a declaration without a prototype with a declaration that has a
2116 /// prototype.
2117 bool hasPrototype() const {
2118 return hasWrittenPrototype() || hasInheritedPrototype();
2119 }
2120
2121 /// Whether this function has a written prototype.
2122 bool hasWrittenPrototype() const {
2123 return FunctionDeclBits.HasWrittenPrototype;
2124 }
2125
2126 /// State that this function has a written prototype.
2127 void setHasWrittenPrototype(bool P = true) {
2128 FunctionDeclBits.HasWrittenPrototype = P;
2129 }
2130
2131 /// Whether this function inherited its prototype from a
2132 /// previous declaration.
2133 bool hasInheritedPrototype() const {
2134 return FunctionDeclBits.HasInheritedPrototype;
2135 }
2136
2137 /// State that this function inherited its prototype from a
2138 /// previous declaration.
2139 void setHasInheritedPrototype(bool P = true) {
2140 FunctionDeclBits.HasInheritedPrototype = P;
2141 }
2142
2143 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2144 bool isConstexpr() const {
2145 return FunctionDeclBits.ConstexprKind != CSK_unspecified;
2146 }
2147 void setConstexprKind(ConstexprSpecKind CSK) {
2148 FunctionDeclBits.ConstexprKind = CSK;
2149 }
2150 ConstexprSpecKind getConstexprKind() const {
2151 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2152 }
2153 bool isConstexprSpecified() const {
2154 return FunctionDeclBits.ConstexprKind == CSK_constexpr;
2155 }
2156 bool isConsteval() const {
2157 return FunctionDeclBits.ConstexprKind == CSK_consteval;
2158 }
2159
2160 /// Whether the instantiation of this function is pending.
2161 /// This bit is set when the decision to instantiate this function is made
2162 /// and unset if and when the function body is created. That leaves out
2163 /// cases where instantiation did not happen because the template definition
2164 /// was not seen in this TU. This bit remains set in those cases, under the
2165 /// assumption that the instantiation will happen in some other TU.
2166 bool instantiationIsPending() const {
2167 return FunctionDeclBits.InstantiationIsPending;
2168 }
2169
2170 /// State that the instantiation of this function is pending.
2171 /// (see instantiationIsPending)
2172 void setInstantiationIsPending(bool IC) {
2173 FunctionDeclBits.InstantiationIsPending = IC;
2174 }
2175
2176 /// Indicates the function uses __try.
2177 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2178 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2179
2180 /// Whether this function has been deleted.
2181 ///
2182 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2183 /// acts like a normal function, except that it cannot actually be
2184 /// called or have its address taken. Deleted functions are
2185 /// typically used in C++ overload resolution to attract arguments
2186 /// whose type or lvalue/rvalue-ness would permit the use of a
2187 /// different overload that would behave incorrectly. For example,
2188 /// one might use deleted functions to ban implicit conversion from
2189 /// a floating-point number to an Integer type:
2190 ///
2191 /// @code
2192 /// struct Integer {
2193 /// Integer(long); // construct from a long
2194 /// Integer(double) = delete; // no construction from float or double
2195 /// Integer(long double) = delete; // no construction from long double
2196 /// };
2197 /// @endcode
2198 // If a function is deleted, its first declaration must be.
2199 bool isDeleted() const {
2200 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2201 }
2202
2203 bool isDeletedAsWritten() const {
2204 return FunctionDeclBits.IsDeleted && !isDefaulted();
2205 }
2206
2207 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2208
2209 /// Determines whether this function is "main", which is the
2210 /// entry point into an executable program.
2211 bool isMain() const;
2212
2213 /// Determines whether this function is a MSVCRT user defined entry
2214 /// point.
2215 bool isMSVCRTEntryPoint() const;
2216
2217 /// Determines whether this operator new or delete is one
2218 /// of the reserved global placement operators:
2219 /// void *operator new(size_t, void *);
2220 /// void *operator new[](size_t, void *);
2221 /// void operator delete(void *, void *);
2222 /// void operator delete[](void *, void *);
2223 /// These functions have special behavior under [new.delete.placement]:
2224 /// These functions are reserved, a C++ program may not define
2225 /// functions that displace the versions in the Standard C++ library.
2226 /// The provisions of [basic.stc.dynamic] do not apply to these
2227 /// reserved placement forms of operator new and operator delete.
2228 ///
2229 /// This function must be an allocation or deallocation function.
2230 bool isReservedGlobalPlacementOperator() const;
2231
2232 /// Determines whether this function is one of the replaceable
2233 /// global allocation functions:
2234 /// void *operator new(size_t);
2235 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2236 /// void *operator new[](size_t);
2237 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2238 /// void operator delete(void *) noexcept;
2239 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2240 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2241 /// void operator delete[](void *) noexcept;
2242 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2243 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2244 /// These functions have special behavior under C++1y [expr.new]:
2245 /// An implementation is allowed to omit a call to a replaceable global
2246 /// allocation function. [...]
2247 ///
2248 /// If this function is an aligned allocation/deallocation function, return
2249 /// true through IsAligned.
2250 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2251
2252 /// Determine whether this is a destroying operator delete.
2253 bool isDestroyingOperatorDelete() const;
2254
2255 /// Compute the language linkage.
2256 LanguageLinkage getLanguageLinkage() const;
2257
2258 /// Determines whether this function is a function with
2259 /// external, C linkage.
2260 bool isExternC() const;
2261
2262 /// Determines whether this function's context is, or is nested within,
2263 /// a C++ extern "C" linkage spec.
2264 bool isInExternCContext() const;
2265
2266 /// Determines whether this function's context is, or is nested within,
2267 /// a C++ extern "C++" linkage spec.
2268 bool isInExternCXXContext() const;
2269
2270 /// Determines whether this is a global function.
2271 bool isGlobal() const;
2272
2273 /// Determines whether this function is known to be 'noreturn', through
2274 /// an attribute on its declaration or its type.
2275 bool isNoReturn() const;
2276
2277 /// True if the function was a definition but its body was skipped.
2278 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2279 void setHasSkippedBody(bool Skipped = true) {
2280 FunctionDeclBits.HasSkippedBody = Skipped;
2281 }
2282
2283 /// True if this function will eventually have a body, once it's fully parsed.
2284 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2285 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2286
2287 /// True if this function is considered a multiversioned function.
2288 bool isMultiVersion() const {
2289 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2290 }
2291
2292 /// Sets the multiversion state for this declaration and all of its
2293 /// redeclarations.
2294 void setIsMultiVersion(bool V = true) {
2295 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2296 }
2297
2298 /// Gets the kind of multiversioning attribute this declaration has. Note that
2299 /// this can return a value even if the function is not multiversion, such as
2300 /// the case of 'target'.
2301 MultiVersionKind getMultiVersionKind() const;
2302
2303
2304 /// True if this function is a multiversioned dispatch function as a part of
2305 /// the cpu_specific/cpu_dispatch functionality.
2306 bool isCPUDispatchMultiVersion() const;
2307 /// True if this function is a multiversioned processor specific function as a
2308 /// part of the cpu_specific/cpu_dispatch functionality.
2309 bool isCPUSpecificMultiVersion() const;
2310
2311 /// True if this function is a multiversioned dispatch function as a part of
2312 /// the target functionality.
2313 bool isTargetMultiVersion() const;
2314
2315 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2316
2317 FunctionDecl *getCanonicalDecl() override;
2318 const FunctionDecl *getCanonicalDecl() const {
2319 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2320 }
2321
2322 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2323
2324 // ArrayRef interface to parameters.
2325 ArrayRef<ParmVarDecl *> parameters() const {
2326 return {ParamInfo, getNumParams()};
2327 }
2328 MutableArrayRef<ParmVarDecl *> parameters() {
2329 return {ParamInfo, getNumParams()};
2330 }
2331
2332 // Iterator access to formal parameters.
2333 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2334 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2335
2336 bool param_empty() const { return parameters().empty(); }
2337 param_iterator param_begin() { return parameters().begin(); }
2338 param_iterator param_end() { return parameters().end(); }
2339 param_const_iterator param_begin() const { return parameters().begin(); }
2340 param_const_iterator param_end() const { return parameters().end(); }
2341 size_t param_size() const { return parameters().size(); }
2342
2343 /// Return the number of parameters this function must have based on its
2344 /// FunctionType. This is the length of the ParamInfo array after it has been
2345 /// created.
2346 unsigned getNumParams() const;
2347
2348 const ParmVarDecl *getParamDecl(unsigned i) const {
2349 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2349, __PRETTY_FUNCTION__))
;
2350 return ParamInfo[i];
2351 }
2352 ParmVarDecl *getParamDecl(unsigned i) {
2353 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2353, __PRETTY_FUNCTION__))
;
2354 return ParamInfo[i];
2355 }
2356 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2357 setParams(getASTContext(), NewParamInfo);
2358 }
2359
2360 /// Returns the minimum number of arguments needed to call this function. This
2361 /// may be fewer than the number of function parameters, if some of the
2362 /// parameters have default arguments (in C++).
2363 unsigned getMinRequiredArguments() const;
2364
2365 QualType getReturnType() const {
2366 return getType()->castAs<FunctionType>()->getReturnType();
2367 }
2368
2369 /// Attempt to compute an informative source range covering the
2370 /// function return type. This may omit qualifiers and other information with
2371 /// limited representation in the AST.
2372 SourceRange getReturnTypeSourceRange() const;
2373
2374 /// Get the declared return type, which may differ from the actual return
2375 /// type if the return type is deduced.
2376 QualType getDeclaredReturnType() const {
2377 auto *TSI = getTypeSourceInfo();
2378 QualType T = TSI ? TSI->getType() : getType();
2379 return T->castAs<FunctionType>()->getReturnType();
2380 }
2381
2382 /// Gets the ExceptionSpecificationType as declared.
2383 ExceptionSpecificationType getExceptionSpecType() const {
2384 auto *TSI = getTypeSourceInfo();
2385 QualType T = TSI ? TSI->getType() : getType();
2386 const auto *FPT = T->getAs<FunctionProtoType>();
2387 return FPT ? FPT->getExceptionSpecType() : EST_None;
2388 }
2389
2390 /// Attempt to compute an informative source range covering the
2391 /// function exception specification, if any.
2392 SourceRange getExceptionSpecSourceRange() const;
2393
2394 /// Determine the type of an expression that calls this function.
2395 QualType getCallResultType() const {
2396 return getType()->castAs<FunctionType>()->getCallResultType(
2397 getASTContext());
2398 }
2399
2400 /// Returns the storage class as written in the source. For the
2401 /// computed linkage of symbol, see getLinkage.
2402 StorageClass getStorageClass() const {
2403 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2404 }
2405
2406 /// Sets the storage class as written in the source.
2407 void setStorageClass(StorageClass SClass) {
2408 FunctionDeclBits.SClass = SClass;
2409 }
2410
2411 /// Determine whether the "inline" keyword was specified for this
2412 /// function.
2413 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2414
2415 /// Set whether the "inline" keyword was specified for this function.
2416 void setInlineSpecified(bool I) {
2417 FunctionDeclBits.IsInlineSpecified = I;
2418 FunctionDeclBits.IsInline = I;
2419 }
2420
2421 /// Flag that this function is implicitly inline.
2422 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2423
2424 /// Determine whether this function should be inlined, because it is
2425 /// either marked "inline" or "constexpr" or is a member function of a class
2426 /// that was defined in the class body.
2427 bool isInlined() const { return FunctionDeclBits.IsInline; }
2428
2429 bool isInlineDefinitionExternallyVisible() const;
2430
2431 bool isMSExternInline() const;
2432
2433 bool doesDeclarationForceExternallyVisibleDefinition() const;
2434
2435 bool isStatic() const { return getStorageClass() == SC_Static; }
2436
2437 /// Whether this function declaration represents an C++ overloaded
2438 /// operator, e.g., "operator+".
2439 bool isOverloadedOperator() const {
2440 return getOverloadedOperator() != OO_None;
2441 }
2442
2443 OverloadedOperatorKind getOverloadedOperator() const;
2444
2445 const IdentifierInfo *getLiteralIdentifier() const;
2446
2447 /// If this function is an instantiation of a member function
2448 /// of a class template specialization, retrieves the function from
2449 /// which it was instantiated.
2450 ///
2451 /// This routine will return non-NULL for (non-templated) member
2452 /// functions of class templates and for instantiations of function
2453 /// templates. For example, given:
2454 ///
2455 /// \code
2456 /// template<typename T>
2457 /// struct X {
2458 /// void f(T);
2459 /// };
2460 /// \endcode
2461 ///
2462 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2463 /// whose parent is the class template specialization X<int>. For
2464 /// this declaration, getInstantiatedFromFunction() will return
2465 /// the FunctionDecl X<T>::A. When a complete definition of
2466 /// X<int>::A is required, it will be instantiated from the
2467 /// declaration returned by getInstantiatedFromMemberFunction().
2468 FunctionDecl *getInstantiatedFromMemberFunction() const;
2469
2470 /// What kind of templated function this is.
2471 TemplatedKind getTemplatedKind() const;
2472
2473 /// If this function is an instantiation of a member function of a
2474 /// class template specialization, retrieves the member specialization
2475 /// information.
2476 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2477
2478 /// Specify that this record is an instantiation of the
2479 /// member function FD.
2480 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2481 TemplateSpecializationKind TSK) {
2482 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2483 }
2484
2485 /// Retrieves the function template that is described by this
2486 /// function declaration.
2487 ///
2488 /// Every function template is represented as a FunctionTemplateDecl
2489 /// and a FunctionDecl (or something derived from FunctionDecl). The
2490 /// former contains template properties (such as the template
2491 /// parameter lists) while the latter contains the actual
2492 /// description of the template's
2493 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2494 /// FunctionDecl that describes the function template,
2495 /// getDescribedFunctionTemplate() retrieves the
2496 /// FunctionTemplateDecl from a FunctionDecl.
2497 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2498
2499 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2500
2501 /// Determine whether this function is a function template
2502 /// specialization.
2503 bool isFunctionTemplateSpecialization() const {
2504 return getPrimaryTemplate() != nullptr;
2505 }
2506
2507 /// If this function is actually a function template specialization,
2508 /// retrieve information about this function template specialization.
2509 /// Otherwise, returns NULL.
2510 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2511
2512 /// Determines whether this function is a function template
2513 /// specialization or a member of a class template specialization that can
2514 /// be implicitly instantiated.
2515 bool isImplicitlyInstantiable() const;
2516
2517 /// Determines if the given function was instantiated from a
2518 /// function template.
2519 bool isTemplateInstantiation() const;
2520
2521 /// Retrieve the function declaration from which this function could
2522 /// be instantiated, if it is an instantiation (rather than a non-template
2523 /// or a specialization, for example).
2524 FunctionDecl *getTemplateInstantiationPattern() const;
2525
2526 /// Retrieve the primary template that this function template
2527 /// specialization either specializes or was instantiated from.
2528 ///
2529 /// If this function declaration is not a function template specialization,
2530 /// returns NULL.
2531 FunctionTemplateDecl *getPrimaryTemplate() const;
2532
2533 /// Retrieve the template arguments used to produce this function
2534 /// template specialization from the primary template.
2535 ///
2536 /// If this function declaration is not a function template specialization,
2537 /// returns NULL.
2538 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2539
2540 /// Retrieve the template argument list as written in the sources,
2541 /// if any.
2542 ///
2543 /// If this function declaration is not a function template specialization
2544 /// or if it had no explicit template argument list, returns NULL.
2545 /// Note that it an explicit template argument list may be written empty,
2546 /// e.g., template<> void foo<>(char* s);
2547 const ASTTemplateArgumentListInfo*
2548 getTemplateSpecializationArgsAsWritten() const;
2549
2550 /// Specify that this function declaration is actually a function
2551 /// template specialization.
2552 ///
2553 /// \param Template the function template that this function template
2554 /// specialization specializes.
2555 ///
2556 /// \param TemplateArgs the template arguments that produced this
2557 /// function template specialization from the template.
2558 ///
2559 /// \param InsertPos If non-NULL, the position in the function template
2560 /// specialization set where the function template specialization data will
2561 /// be inserted.
2562 ///
2563 /// \param TSK the kind of template specialization this is.
2564 ///
2565 /// \param TemplateArgsAsWritten location info of template arguments.
2566 ///
2567 /// \param PointOfInstantiation point at which the function template
2568 /// specialization was first instantiated.
2569 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2570 const TemplateArgumentList *TemplateArgs,
2571 void *InsertPos,
2572 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2573 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2574 SourceLocation PointOfInstantiation = SourceLocation()) {
2575 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2576 InsertPos, TSK, TemplateArgsAsWritten,
2577 PointOfInstantiation);
2578 }
2579
2580 /// Specifies that this function declaration is actually a
2581 /// dependent function template specialization.
2582 void setDependentTemplateSpecialization(ASTContext &Context,
2583 const UnresolvedSetImpl &Templates,
2584 const TemplateArgumentListInfo &TemplateArgs);
2585
2586 DependentFunctionTemplateSpecializationInfo *
2587 getDependentSpecializationInfo() const;
2588
2589 /// Determine what kind of template instantiation this function
2590 /// represents.
2591 TemplateSpecializationKind getTemplateSpecializationKind() const;
2592
2593 /// Determine the kind of template specialization this function represents
2594 /// for the purpose of template instantiation.
2595 TemplateSpecializationKind
2596 getTemplateSpecializationKindForInstantiation() const;
2597
2598 /// Determine what kind of template instantiation this function
2599 /// represents.
2600 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2601 SourceLocation PointOfInstantiation = SourceLocation());
2602
2603 /// Retrieve the (first) point of instantiation of a function template
2604 /// specialization or a member of a class template specialization.
2605 ///
2606 /// \returns the first point of instantiation, if this function was
2607 /// instantiated from a template; otherwise, returns an invalid source
2608 /// location.
2609 SourceLocation getPointOfInstantiation() const;
2610
2611 /// Determine whether this is or was instantiated from an out-of-line
2612 /// definition of a member function.
2613 bool isOutOfLine() const override;
2614
2615 /// Identify a memory copying or setting function.
2616 /// If the given function is a memory copy or setting function, returns
2617 /// the corresponding Builtin ID. If the function is not a memory function,
2618 /// returns 0.
2619 unsigned getMemoryFunctionKind() const;
2620
2621 /// Returns ODRHash of the function. This value is calculated and
2622 /// stored on first call, then the stored value returned on the other calls.
2623 unsigned getODRHash();
2624
2625 /// Returns cached ODRHash of the function. This must have been previously
2626 /// computed and stored.
2627 unsigned getODRHash() const;
2628
2629 // Implement isa/cast/dyncast/etc.
2630 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2631 static bool classofKind(Kind K) {
2632 return K >= firstFunction && K <= lastFunction;
2633 }
2634 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2635 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2636 }
2637 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2638 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2639 }
2640};
2641
2642/// Represents a member of a struct/union/class.
2643class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2644 unsigned BitField : 1;
2645 unsigned Mutable : 1;
2646 mutable unsigned CachedFieldIndex : 30;
2647
2648 /// The kinds of value we can store in InitializerOrBitWidth.
2649 ///
2650 /// Note that this is compatible with InClassInitStyle except for
2651 /// ISK_CapturedVLAType.
2652 enum InitStorageKind {
2653 /// If the pointer is null, there's nothing special. Otherwise,
2654 /// this is a bitfield and the pointer is the Expr* storing the
2655 /// bit-width.
2656 ISK_NoInit = (unsigned) ICIS_NoInit,
2657
2658 /// The pointer is an (optional due to delayed parsing) Expr*
2659 /// holding the copy-initializer.
2660 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2661
2662 /// The pointer is an (optional due to delayed parsing) Expr*
2663 /// holding the list-initializer.
2664 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2665
2666 /// The pointer is a VariableArrayType* that's been captured;
2667 /// the enclosing context is a lambda or captured statement.
2668 ISK_CapturedVLAType,
2669 };
2670
2671 /// If this is a bitfield with a default member initializer, this
2672 /// structure is used to represent the two expressions.
2673 struct InitAndBitWidth {
2674 Expr *Init;
2675 Expr *BitWidth;
2676 };
2677
2678 /// Storage for either the bit-width, the in-class initializer, or
2679 /// both (via InitAndBitWidth), or the captured variable length array bound.
2680 ///
2681 /// If the storage kind is ISK_InClassCopyInit or
2682 /// ISK_InClassListInit, but the initializer is null, then this
2683 /// field has an in-class initializer that has not yet been parsed
2684 /// and attached.
2685 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2686 // overwhelmingly common case that we have none of these things.
2687 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2688
2689protected:
2690 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2691 SourceLocation IdLoc, IdentifierInfo *Id,
2692 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2693 InClassInitStyle InitStyle)
2694 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2695 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2696 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2697 if (BW)
2698 setBitWidth(BW);
2699 }
2700
2701public:
2702 friend class ASTDeclReader;
2703 friend class ASTDeclWriter;
2704
2705 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2706 SourceLocation StartLoc, SourceLocation IdLoc,
2707 IdentifierInfo *Id, QualType T,
2708 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2709 InClassInitStyle InitStyle);
2710
2711 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2712
2713 /// Returns the index of this field within its record,
2714 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2715 unsigned getFieldIndex() const;
2716
2717 /// Determines whether this field is mutable (C++ only).
2718 bool isMutable() const { return Mutable; }
2719
2720 /// Determines whether this field is a bitfield.
2721 bool isBitField() const { return BitField; }
2722
2723 /// Determines whether this is an unnamed bitfield.
2724 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2725
2726 /// Determines whether this field is a
2727 /// representative for an anonymous struct or union. Such fields are
2728 /// unnamed and are implicitly generated by the implementation to
2729 /// store the data for the anonymous union or struct.
2730 bool isAnonymousStructOrUnion() const;
2731
2732 Expr *getBitWidth() const {
2733 if (!BitField)
2734 return nullptr;
2735 void *Ptr = InitStorage.getPointer();
2736 if (getInClassInitStyle())
2737 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2738 return static_cast<Expr*>(Ptr);
2739 }
2740
2741 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2742
2743 /// Set the bit-field width for this member.
2744 // Note: used by some clients (i.e., do not remove it).
2745 void setBitWidth(Expr *Width) {
2746 assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2747, __PRETTY_FUNCTION__))
2747 "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2747, __PRETTY_FUNCTION__))
;
2748 assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast<
void> (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2748, __PRETTY_FUNCTION__))
;
2749 InitStorage.setPointer(
2750 InitStorage.getInt()
2751 ? new (getASTContext())
2752 InitAndBitWidth{getInClassInitializer(), Width}
2753 : static_cast<void*>(Width));
2754 BitField = true;
2755 }
2756
2757 /// Remove the bit-field width from this member.
2758 // Note: used by some clients (i.e., do not remove it).
2759 void removeBitWidth() {
2760 assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast
<void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2760, __PRETTY_FUNCTION__))
;
2761 InitStorage.setPointer(getInClassInitializer());
2762 BitField = false;
2763 }
2764
2765 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2766 /// at all and instead act as a separator between contiguous runs of other
2767 /// bit-fields.
2768 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2769
2770 /// Determine if this field is a subobject of zero size, that is, either a
2771 /// zero-length bit-field or a field of empty class type with the
2772 /// [[no_unique_address]] attribute.
2773 bool isZeroSize(const ASTContext &Ctx) const;
2774
2775 /// Get the kind of (C++11) default member initializer that this field has.
2776 InClassInitStyle getInClassInitStyle() const {
2777 InitStorageKind storageKind = InitStorage.getInt();
2778 return (storageKind == ISK_CapturedVLAType
2779 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2780 }
2781
2782 /// Determine whether this member has a C++11 default member initializer.
2783 bool hasInClassInitializer() const {
2784 return getInClassInitStyle() != ICIS_NoInit;
2785 }
2786
2787 /// Get the C++11 default member initializer for this member, or null if one
2788 /// has not been set. If a valid declaration has a default member initializer,
2789 /// but this returns null, then we have not parsed and attached it yet.
2790 Expr *getInClassInitializer() const {
2791 if (!hasInClassInitializer())
2792 return nullptr;
2793 void *Ptr = InitStorage.getPointer();
2794 if (BitField)
2795 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2796 return static_cast<Expr*>(Ptr);
2797 }
2798
2799 /// Set the C++11 in-class initializer for this member.
2800 void setInClassInitializer(Expr *Init) {
2801 assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer()
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2801, __PRETTY_FUNCTION__))
;
2802 if (BitField)
2803 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2804 else
2805 InitStorage.setPointer(Init);
2806 }
2807
2808 /// Remove the C++11 in-class initializer from this member.
2809 void removeInClassInitializer() {
2810 assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove"
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2810, __PRETTY_FUNCTION__))
;
2811 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2812 }
2813
2814 /// Determine whether this member captures the variable length array
2815 /// type.
2816 bool hasCapturedVLAType() const {
2817 return InitStorage.getInt() == ISK_CapturedVLAType;
2818 }
2819
2820 /// Get the captured variable length array type.
2821 const VariableArrayType *getCapturedVLAType() const {
2822 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2823 InitStorage.getPointer())
2824 : nullptr;
2825 }
2826
2827 /// Set the captured variable length array type for this field.
2828 void setCapturedVLAType(const VariableArrayType *VLAType);
2829
2830 /// Returns the parent of this field declaration, which
2831 /// is the struct in which this field is defined.
2832 const RecordDecl *getParent() const {
2833 return cast<RecordDecl>(getDeclContext());
2834 }
2835
2836 RecordDecl *getParent() {
2837 return cast<RecordDecl>(getDeclContext());
2838 }
2839
2840 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2841
2842 /// Retrieves the canonical declaration of this field.
2843 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2844 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2845
2846 // Implement isa/cast/dyncast/etc.
2847 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2848 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2849};
2850
2851/// An instance of this object exists for each enum constant
2852/// that is defined. For example, in "enum X {a,b}", each of a/b are
2853/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2854/// TagType for the X EnumDecl.
2855class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2856 Stmt *Init; // an integer constant expression
2857 llvm::APSInt Val; // The value.
2858
2859protected:
2860 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2861 IdentifierInfo *Id, QualType T, Expr *E,
2862 const llvm::APSInt &V)
2863 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2864
2865public:
2866 friend class StmtIteratorBase;
2867
2868 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2869 SourceLocation L, IdentifierInfo *Id,
2870 QualType T, Expr *E,
2871 const llvm::APSInt &V);
2872 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2873
2874 const Expr *getInitExpr() const { return (const Expr*) Init; }
2875 Expr *getInitExpr() { return (Expr*) Init; }
2876 const llvm::APSInt &getInitVal() const { return Val; }
2877
2878 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2879 void setInitVal(const llvm::APSInt &V) { Val = V; }
2880
2881 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2882
2883 /// Retrieves the canonical declaration of this enumerator.
2884 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2885 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2886
2887 // Implement isa/cast/dyncast/etc.
2888 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2889 static bool classofKind(Kind K) { return K == EnumConstant; }
2890};
2891
2892/// Represents a field injected from an anonymous union/struct into the parent
2893/// scope. These are always implicit.
2894class IndirectFieldDecl : public ValueDecl,
2895 public Mergeable<IndirectFieldDecl> {
2896 NamedDecl **Chaining;
2897 unsigned ChainingSize;
2898
2899 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2900 DeclarationName N, QualType T,
2901 MutableArrayRef<NamedDecl *> CH);
2902
2903 void anchor() override;
2904
2905public:
2906 friend class ASTDeclReader;
2907
2908 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2909 SourceLocation L, IdentifierInfo *Id,
2910 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2911
2912 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2913
2914 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2915
2916 ArrayRef<NamedDecl *> chain() const {
2917 return llvm::makeArrayRef(Chaining, ChainingSize);
2918 }
2919 chain_iterator chain_begin() const { return chain().begin(); }
2920 chain_iterator chain_end() const { return chain().end(); }
2921
2922 unsigned getChainingSize() const { return ChainingSize; }
2923
2924 FieldDecl *getAnonField() const {
2925 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2925, __PRETTY_FUNCTION__))
;
2926 return cast<FieldDecl>(chain().back());
2927 }
2928
2929 VarDecl *getVarDecl() const {
2930 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 2930, __PRETTY_FUNCTION__))
;
2931 return dyn_cast<VarDecl>(chain().front());
2932 }
2933
2934 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2935 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2936
2937 // Implement isa/cast/dyncast/etc.
2938 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2939 static bool classofKind(Kind K) { return K == IndirectField; }
2940};
2941
2942/// Represents a declaration of a type.
2943class TypeDecl : public NamedDecl {
2944 friend class ASTContext;
2945
2946 /// This indicates the Type object that represents
2947 /// this TypeDecl. It is a cache maintained by
2948 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2949 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2950 mutable const Type *TypeForDecl = nullptr;
2951
2952 /// The start of the source range for this declaration.
2953 SourceLocation LocStart;
2954
2955 void anchor() override;
2956
2957protected:
2958 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2959 SourceLocation StartL = SourceLocation())
2960 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2961
2962public:
2963 // Low-level accessor. If you just want the type defined by this node,
2964 // check out ASTContext::getTypeDeclType or one of
2965 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2966 // already know the specific kind of node this is.
2967 const Type *getTypeForDecl() const { return TypeForDecl; }
2968 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2969
2970 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2971 void setLocStart(SourceLocation L) { LocStart = L; }
2972 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2973 if (LocStart.isValid())
2974 return SourceRange(LocStart, getLocation());
2975 else
2976 return SourceRange(getLocation());
2977 }
2978
2979 // Implement isa/cast/dyncast/etc.
2980 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2981 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2982};
2983
2984/// Base class for declarations which introduce a typedef-name.
2985class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2986 struct alignas(8) ModedTInfo {
2987 TypeSourceInfo *first;
2988 QualType second;
2989 };
2990
2991 /// If int part is 0, we have not computed IsTransparentTag.
2992 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2993 mutable llvm::PointerIntPair<
2994 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2995 MaybeModedTInfo;
2996
2997 void anchor() override;
2998
2999protected:
3000 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3001 SourceLocation StartLoc, SourceLocation IdLoc,
3002 IdentifierInfo *Id, TypeSourceInfo *TInfo)
3003 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3004 MaybeModedTInfo(TInfo, 0) {}
3005
3006 using redeclarable_base = Redeclarable<TypedefNameDecl>;
3007
3008 TypedefNameDecl *getNextRedeclarationImpl() override {
3009 return getNextRedeclaration();
3010 }
3011
3012 TypedefNameDecl *getPreviousDeclImpl() override {
3013 return getPreviousDecl();
3014 }
3015
3016 TypedefNameDecl *getMostRecentDeclImpl() override {
3017 return getMostRecentDecl();
3018 }
3019
3020public:
3021 using redecl_range = redeclarable_base::redecl_range;
3022 using redecl_iterator = redeclarable_base::redecl_iterator;
3023
3024 using redeclarable_base::redecls_begin;
3025 using redeclarable_base::redecls_end;
3026 using redeclarable_base::redecls;
3027 using redeclarable_base::getPreviousDecl;
3028 using redeclarable_base::getMostRecentDecl;
3029 using redeclarable_base::isFirstDecl;
3030
3031 bool isModed() const {
3032 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3033 }
3034
3035 TypeSourceInfo *getTypeSourceInfo() const {
3036 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3037 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3038 }
3039
3040 QualType getUnderlyingType() const {
3041 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3042 : MaybeModedTInfo.getPointer()
3043 .get<TypeSourceInfo *>()
3044 ->getType();
3045 }
3046
3047 void setTypeSourceInfo(TypeSourceInfo *newType) {
3048 MaybeModedTInfo.setPointer(newType);
3049 }
3050
3051 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3052 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3053 ModedTInfo({unmodedTSI, modedTy}));
3054 }
3055
3056 /// Retrieves the canonical declaration of this typedef-name.
3057 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3058 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3059
3060 /// Retrieves the tag declaration for which this is the typedef name for
3061 /// linkage purposes, if any.
3062 ///
3063 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3064 /// this typedef declaration.
3065 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3066
3067 /// Determines if this typedef shares a name and spelling location with its
3068 /// underlying tag type, as is the case with the NS_ENUM macro.
3069 bool isTransparentTag() const {
3070 if (MaybeModedTInfo.getInt())
3071 return MaybeModedTInfo.getInt() & 0x2;
3072 return isTransparentTagSlow();
3073 }
3074
3075 // Implement isa/cast/dyncast/etc.
3076 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3077 static bool classofKind(Kind K) {
3078 return K >= firstTypedefName && K <= lastTypedefName;
3079 }
3080
3081private:
3082 bool isTransparentTagSlow() const;
3083};
3084
3085/// Represents the declaration of a typedef-name via the 'typedef'
3086/// type specifier.
3087class TypedefDecl : public TypedefNameDecl {
3088 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3089 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3090 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3091
3092public:
3093 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3094 SourceLocation StartLoc, SourceLocation IdLoc,
3095 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3096 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3097
3098 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3099
3100 // Implement isa/cast/dyncast/etc.
3101 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3102 static bool classofKind(Kind K) { return K == Typedef; }
3103};
3104
3105/// Represents the declaration of a typedef-name via a C++11
3106/// alias-declaration.
3107class TypeAliasDecl : public TypedefNameDecl {
3108 /// The template for which this is the pattern, if any.
3109 TypeAliasTemplateDecl *Template;
3110
3111 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3112 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3113 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3114 Template(nullptr) {}
3115
3116public:
3117 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3118 SourceLocation StartLoc, SourceLocation IdLoc,
3119 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3120 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3121
3122 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3123
3124 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3125 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3126
3127 // Implement isa/cast/dyncast/etc.
3128 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3129 static bool classofKind(Kind K) { return K == TypeAlias; }
3130};
3131
3132/// Represents the declaration of a struct/union/class/enum.
3133class TagDecl : public TypeDecl,
3134 public DeclContext,
3135 public Redeclarable<TagDecl> {
3136 // This class stores some data in DeclContext::TagDeclBits
3137 // to save some space. Use the provided accessors to access it.
3138public:
3139 // This is really ugly.
3140 using TagKind = TagTypeKind;
3141
3142private:
3143 SourceRange BraceRange;
3144
3145 // A struct representing syntactic qualifier info,
3146 // to be used for the (uncommon) case of out-of-line declarations.
3147 using ExtInfo = QualifierInfo;
3148
3149 /// If the (out-of-line) tag declaration name
3150 /// is qualified, it points to the qualifier info (nns and range);
3151 /// otherwise, if the tag declaration is anonymous and it is part of
3152 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3153 /// otherwise, if the tag declaration is anonymous and it is used as a
3154 /// declaration specifier for variables, it points to the first VarDecl (used
3155 /// for mangling);
3156 /// otherwise, it is a null (TypedefNameDecl) pointer.
3157 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3158
3159 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3160 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3161 const ExtInfo *getExtInfo() const {
3162 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3163 }
3164
3165protected:
3166 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3167 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3168 SourceLocation StartL);
3169
3170 using redeclarable_base = Redeclarable<TagDecl>;
3171
3172 TagDecl *getNextRedeclarationImpl() override {
3173 return getNextRedeclaration();
3174 }
3175
3176 TagDecl *getPreviousDeclImpl() override {
3177 return getPreviousDecl();
3178 }
3179
3180 TagDecl *getMostRecentDeclImpl() override {
3181 return getMostRecentDecl();
3182 }
3183
3184 /// Completes the definition of this tag declaration.
3185 ///
3186 /// This is a helper function for derived classes.
3187 void completeDefinition();
3188
3189 /// True if this decl is currently being defined.
3190 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3191
3192 /// Indicates whether it is possible for declarations of this kind
3193 /// to have an out-of-date definition.
3194 ///
3195 /// This option is only enabled when modules are enabled.
3196 void setMayHaveOutOfDateDef(bool V = true) {
3197 TagDeclBits.MayHaveOutOfDateDef = V;
3198 }
3199
3200public:
3201 friend class ASTDeclReader;
3202 friend class ASTDeclWriter;
3203
3204 using redecl_range = redeclarable_base::redecl_range;
3205 using redecl_iterator = redeclarable_base::redecl_iterator;
3206
3207 using redeclarable_base::redecls_begin;
3208 using redeclarable_base::redecls_end;
3209 using redeclarable_base::redecls;
3210 using redeclarable_base::getPreviousDecl;
3211 using redeclarable_base::getMostRecentDecl;
3212 using redeclarable_base::isFirstDecl;
3213
3214 SourceRange getBraceRange() const { return BraceRange; }
3215 void setBraceRange(SourceRange R) { BraceRange = R; }
3216
3217 /// Return SourceLocation representing start of source
3218 /// range ignoring outer template declarations.
3219 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3220
3221 /// Return SourceLocation representing start of source
3222 /// range taking into account any outer template declarations.
3223 SourceLocation getOuterLocStart() const;
3224 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3225
3226 TagDecl *getCanonicalDecl() override;
3227 const TagDecl *getCanonicalDecl() const {
3228 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3229 }
3230
3231 /// Return true if this declaration is a completion definition of the type.
3232 /// Provided for consistency.
3233 bool isThisDeclarationADefinition() const {
3234 return isCompleteDefinition();
3235 }
3236
3237 /// Return true if this decl has its body fully specified.
3238 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3239
3240 /// True if this decl has its body fully specified.
3241 void setCompleteDefinition(bool V = true) {
3242 TagDeclBits.IsCompleteDefinition = V;
3243 }
3244
3245 /// Return true if this complete decl is
3246 /// required to be complete for some existing use.
3247 bool isCompleteDefinitionRequired() const {
3248 return TagDeclBits.IsCompleteDefinitionRequired;
3249 }
3250
3251 /// True if this complete decl is
3252 /// required to be complete for some existing use.
3253 void setCompleteDefinitionRequired(bool V = true) {
3254 TagDeclBits.IsCompleteDefinitionRequired = V;
3255 }
3256
3257 /// Return true if this decl is currently being defined.
3258 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3259
3260 /// True if this tag declaration is "embedded" (i.e., defined or declared
3261 /// for the very first time) in the syntax of a declarator.
3262 bool isEmbeddedInDeclarator() const {
3263 return TagDeclBits.IsEmbeddedInDeclarator;
3264 }
3265
3266 /// True if this tag declaration is "embedded" (i.e., defined or declared
3267 /// for the very first time) in the syntax of a declarator.
3268 void setEmbeddedInDeclarator(bool isInDeclarator) {
3269 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3270 }
3271
3272 /// True if this tag is free standing, e.g. "struct foo;".
3273 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3274
3275 /// True if this tag is free standing, e.g. "struct foo;".
3276 void setFreeStanding(bool isFreeStanding = true) {
3277 TagDeclBits.IsFreeStanding = isFreeStanding;
3278 }
3279
3280 /// Indicates whether it is possible for declarations of this kind
3281 /// to have an out-of-date definition.
3282 ///
3283 /// This option is only enabled when modules are enabled.
3284 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3285
3286 /// Whether this declaration declares a type that is
3287 /// dependent, i.e., a type that somehow depends on template
3288 /// parameters.
3289 bool isDependentType() const { return isDependentContext(); }
3290
3291 /// Starts the definition of this tag declaration.
3292 ///
3293 /// This method should be invoked at the beginning of the definition
3294 /// of this tag declaration. It will set the tag type into a state
3295 /// where it is in the process of being defined.
3296 void startDefinition();
3297
3298 /// Returns the TagDecl that actually defines this
3299 /// struct/union/class/enum. When determining whether or not a
3300 /// struct/union/class/enum has a definition, one should use this
3301 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3302 /// whether or not a specific TagDecl is defining declaration, not
3303 /// whether or not the struct/union/class/enum type is defined.
3304 /// This method returns NULL if there is no TagDecl that defines
3305 /// the struct/union/class/enum.
3306 TagDecl *getDefinition() const;
3307
3308 StringRef getKindName() const {
3309 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3310 }
3311
3312 TagKind getTagKind() const {
3313 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3314 }
3315
3316 void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3317
3318 bool isStruct() const { return getTagKind() == TTK_Struct; }
3319 bool isInterface() const { return getTagKind() == TTK_Interface; }
3320 bool isClass() const { return getTagKind() == TTK_Class; }
3321 bool isUnion() const { return getTagKind() == TTK_Union; }
46
Assuming the condition is false
47
Returning zero, which participates in a condition later
3322 bool isEnum() const { return getTagKind() == TTK_Enum; }
3323
3324 /// Is this tag type named, either directly or via being defined in
3325 /// a typedef of this type?
3326 ///
3327 /// C++11 [basic.link]p8:
3328 /// A type is said to have linkage if and only if:
3329 /// - it is a class or enumeration type that is named (or has a
3330 /// name for linkage purposes) and the name has linkage; ...
3331 /// C++11 [dcl.typedef]p9:
3332 /// If the typedef declaration defines an unnamed class (or enum),
3333 /// the first typedef-name declared by the declaration to be that
3334 /// class type (or enum type) is used to denote the class type (or
3335 /// enum type) for linkage purposes only.
3336 ///
3337 /// C does not have an analogous rule, but the same concept is
3338 /// nonetheless useful in some places.
3339 bool hasNameForLinkage() const {
3340 return (getDeclName() || getTypedefNameForAnonDecl());
3341 }
3342
3343 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3344 return hasExtInfo() ? nullptr
3345 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3346 }
3347
3348 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3349
3350 /// Retrieve the nested-name-specifier that qualifies the name of this
3351 /// declaration, if it was present in the source.
3352 NestedNameSpecifier *getQualifier() const {
3353 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3354 : nullptr;
3355 }
3356
3357 /// Retrieve the nested-name-specifier (with source-location
3358 /// information) that qualifies the name of this declaration, if it was
3359 /// present in the source.
3360 NestedNameSpecifierLoc getQualifierLoc() const {
3361 return hasExtInfo() ? getExtInfo()->QualifierLoc
3362 : NestedNameSpecifierLoc();
3363 }
3364
3365 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3366
3367 unsigned getNumTemplateParameterLists() const {
3368 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3369 }
3370
3371 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3372 assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void
> (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 3372, __PRETTY_FUNCTION__))
;
3373 return getExtInfo()->TemplParamLists[i];
3374 }
3375
3376 void setTemplateParameterListsInfo(ASTContext &Context,
3377 ArrayRef<TemplateParameterList *> TPLists);
3378
3379 // Implement isa/cast/dyncast/etc.
3380 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3381 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3382
3383 static DeclContext *castToDeclContext(const TagDecl *D) {
3384 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3385 }
3386
3387 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3388 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3389 }
3390};
3391
3392/// Represents an enum. In C++11, enums can be forward-declared
3393/// with a fixed underlying type, and in C we allow them to be forward-declared
3394/// with no underlying type as an extension.
3395class EnumDecl : public TagDecl {
3396 // This class stores some data in DeclContext::EnumDeclBits
3397 // to save some space. Use the provided accessors to access it.
3398
3399 /// This represent the integer type that the enum corresponds
3400 /// to for code generation purposes. Note that the enumerator constants may
3401 /// have a different type than this does.
3402 ///
3403 /// If the underlying integer type was explicitly stated in the source
3404 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3405 /// was automatically deduced somehow, and this is a Type*.
3406 ///
3407 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3408 /// some cases it won't.
3409 ///
3410 /// The underlying type of an enumeration never has any qualifiers, so
3411 /// we can get away with just storing a raw Type*, and thus save an
3412 /// extra pointer when TypeSourceInfo is needed.
3413 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3414
3415 /// The integer type that values of this type should
3416 /// promote to. In C, enumerators are generally of an integer type
3417 /// directly, but gcc-style large enumerators (and all enumerators
3418 /// in C++) are of the enum type instead.
3419 QualType PromotionType;
3420
3421 /// If this enumeration is an instantiation of a member enumeration
3422 /// of a class template specialization, this is the member specialization
3423 /// information.
3424 MemberSpecializationInfo *SpecializationInfo = nullptr;
3425
3426 /// Store the ODRHash after first calculation.
3427 /// The corresponding flag HasODRHash is in EnumDeclBits
3428 /// and can be accessed with the provided accessors.
3429 unsigned ODRHash;
3430
3431 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3432 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3433 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3434
3435 void anchor() override;
3436
3437 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3438 TemplateSpecializationKind TSK);
3439
3440 /// Sets the width in bits required to store all the
3441 /// non-negative enumerators of this enum.
3442 void setNumPositiveBits(unsigned Num) {
3443 EnumDeclBits.NumPositiveBits = Num;
3444 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount"
) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 3444, __PRETTY_FUNCTION__))
;
3445 }
3446
3447 /// Returns the width in bits required to store all the
3448 /// negative enumerators of this enum. (see getNumNegativeBits)
3449 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3450
3451 /// True if this tag declaration is a scoped enumeration. Only
3452 /// possible in C++11 mode.
3453 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3454
3455 /// If this tag declaration is a scoped enum,
3456 /// then this is true if the scoped enum was declared using the class
3457 /// tag, false if it was declared with the struct tag. No meaning is
3458 /// associated if this tag declaration is not a scoped enum.
3459 void setScopedUsingClassTag(bool ScopedUCT = true) {
3460 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3461 }
3462
3463 /// True if this is an Objective-C, C++11, or
3464 /// Microsoft-style enumeration with a fixed underlying type.
3465 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3466
3467 /// True if a valid hash is stored in ODRHash.
3468 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3469 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3470
3471public:
3472 friend class ASTDeclReader;
3473
3474 EnumDecl *getCanonicalDecl() override {
3475 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3476 }
3477 const EnumDecl *getCanonicalDecl() const {
3478 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3479 }
3480
3481 EnumDecl *getPreviousDecl() {
3482 return cast_or_null<EnumDecl>(
3483 static_cast<TagDecl *>(this)->getPreviousDecl());
3484 }
3485 const EnumDecl *getPreviousDecl() const {
3486 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3487 }
3488
3489 EnumDecl *getMostRecentDecl() {
3490 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3491 }
3492 const EnumDecl *getMostRecentDecl() const {
3493 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3494 }
3495
3496 EnumDecl *getDefinition() const {
3497 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3498 }
3499
3500 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3501 SourceLocation StartLoc, SourceLocation IdLoc,
3502 IdentifierInfo *Id, EnumDecl *PrevDecl,
3503 bool IsScoped, bool IsScopedUsingClassTag,
3504 bool IsFixed);
3505 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3506
3507 /// When created, the EnumDecl corresponds to a
3508 /// forward-declared enum. This method is used to mark the
3509 /// declaration as being defined; its enumerators have already been
3510 /// added (via DeclContext::addDecl). NewType is the new underlying
3511 /// type of the enumeration type.
3512 void completeDefinition(QualType NewType,
3513 QualType PromotionType,
3514 unsigned NumPositiveBits,
3515 unsigned NumNegativeBits);
3516
3517 // Iterates through the enumerators of this enumeration.
3518 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3519 using enumerator_range =
3520 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3521
3522 enumerator_range enumerators() const {
3523 return enumerator_range(enumerator_begin(), enumerator_end());
3524 }
3525
3526 enumerator_iterator enumerator_begin() const {
3527 const EnumDecl *E = getDefinition();
3528 if (!E)
3529 E = this;
3530 return enumerator_iterator(E->decls_begin());
3531 }
3532
3533 enumerator_iterator enumerator_end() const {
3534 const EnumDecl *E = getDefinition();
3535 if (!E)
3536 E = this;
3537 return enumerator_iterator(E->decls_end());
3538 }
3539
3540 /// Return the integer type that enumerators should promote to.
3541 QualType getPromotionType() const { return PromotionType; }
3542
3543 /// Set the promotion type.
3544 void setPromotionType(QualType T) { PromotionType = T; }
3545
3546 /// Return the integer type this enum decl corresponds to.
3547 /// This returns a null QualType for an enum forward definition with no fixed
3548 /// underlying type.
3549 QualType getIntegerType() const {
3550 if (!IntegerType)
3551 return QualType();
3552 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3553 return QualType(T, 0);
3554 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3555 }
3556
3557 /// Set the underlying integer type.
3558 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3559
3560 /// Set the underlying integer type source info.
3561 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3562
3563 /// Return the type source info for the underlying integer type,
3564 /// if no type source info exists, return 0.
3565 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3566 return IntegerType.dyn_cast<TypeSourceInfo*>();
3567 }
3568
3569 /// Retrieve the source range that covers the underlying type if
3570 /// specified.
3571 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3572
3573 /// Returns the width in bits required to store all the
3574 /// non-negative enumerators of this enum.
3575 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3576
3577 /// Returns the width in bits required to store all the
3578 /// negative enumerators of this enum. These widths include
3579 /// the rightmost leading 1; that is:
3580 ///
3581 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3582 /// ------------------------ ------- -----------------
3583 /// -1 1111111 1
3584 /// -10 1110110 5
3585 /// -101 1001011 8
3586 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3587
3588 /// Returns true if this is a C++11 scoped enumeration.
3589 bool isScoped() const { return EnumDeclBits.IsScoped; }
3590
3591 /// Returns true if this is a C++11 scoped enumeration.
3592 bool isScopedUsingClassTag() const {
3593 return EnumDeclBits.IsScopedUsingClassTag;
3594 }
3595
3596 /// Returns true if this is an Objective-C, C++11, or
3597 /// Microsoft-style enumeration with a fixed underlying type.
3598 bool isFixed() const { return EnumDeclBits.IsFixed; }
3599
3600 unsigned getODRHash();
3601
3602 /// Returns true if this can be considered a complete type.
3603 bool isComplete() const {
3604 // IntegerType is set for fixed type enums and non-fixed but implicitly
3605 // int-sized Microsoft enums.
3606 return isCompleteDefinition() || IntegerType;
3607 }
3608
3609 /// Returns true if this enum is either annotated with
3610 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3611 bool isClosed() const;
3612
3613 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3614 /// with enum_extensibility(open).
3615 bool isClosedFlag() const;
3616
3617 /// Returns true if this enum is annotated with neither flag_enum nor
3618 /// enum_extensibility(open).
3619 bool isClosedNonFlag() const;
3620
3621 /// Retrieve the enum definition from which this enumeration could
3622 /// be instantiated, if it is an instantiation (rather than a non-template).
3623 EnumDecl *getTemplateInstantiationPattern() const;
3624
3625 /// Returns the enumeration (declared within the template)
3626 /// from which this enumeration type was instantiated, or NULL if
3627 /// this enumeration was not instantiated from any template.
3628 EnumDecl *getInstantiatedFromMemberEnum() const;
3629
3630 /// If this enumeration is a member of a specialization of a
3631 /// templated class, determine what kind of template specialization
3632 /// or instantiation this is.
3633 TemplateSpecializationKind getTemplateSpecializationKind() const;
3634
3635 /// For an enumeration member that was instantiated from a member
3636 /// enumeration of a templated class, set the template specialiation kind.
3637 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3638 SourceLocation PointOfInstantiation = SourceLocation());
3639
3640 /// If this enumeration is an instantiation of a member enumeration of
3641 /// a class template specialization, retrieves the member specialization
3642 /// information.
3643 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3644 return SpecializationInfo;
3645 }
3646
3647 /// Specify that this enumeration is an instantiation of the
3648 /// member enumeration ED.
3649 void setInstantiationOfMemberEnum(EnumDecl *ED,
3650 TemplateSpecializationKind TSK) {
3651 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3652 }
3653
3654 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3655 static bool classofKind(Kind K) { return K == Enum; }
3656};
3657
3658/// Represents a struct/union/class. For example:
3659/// struct X; // Forward declaration, no "body".
3660/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3661/// This decl will be marked invalid if *any* members are invalid.
3662class RecordDecl : public TagDecl {
3663 // This class stores some data in DeclContext::RecordDeclBits
3664 // to save some space. Use the provided accessors to access it.
3665public:
3666 friend class DeclContext;
3667 /// Enum that represents the different ways arguments are passed to and
3668 /// returned from function calls. This takes into account the target-specific
3669 /// and version-specific rules along with the rules determined by the
3670 /// language.
3671 enum ArgPassingKind : unsigned {
3672 /// The argument of this type can be passed directly in registers.
3673 APK_CanPassInRegs,
3674
3675 /// The argument of this type cannot be passed directly in registers.
3676 /// Records containing this type as a subobject are not forced to be passed
3677 /// indirectly. This value is used only in C++. This value is required by
3678 /// C++ because, in uncommon situations, it is possible for a class to have
3679 /// only trivial copy/move constructors even when one of its subobjects has
3680 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3681 /// constructor in the derived class is deleted).
3682 APK_CannotPassInRegs,
3683
3684 /// The argument of this type cannot be passed directly in registers.
3685 /// Records containing this type as a subobject are forced to be passed
3686 /// indirectly.
3687 APK_CanNeverPassInRegs
3688 };
3689
3690protected:
3691 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3692 SourceLocation StartLoc, SourceLocation IdLoc,
3693 IdentifierInfo *Id, RecordDecl *PrevDecl);
3694
3695public:
3696 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3697 SourceLocation StartLoc, SourceLocation IdLoc,
3698 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3699 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3700
3701 RecordDecl *getPreviousDecl() {
3702 return cast_or_null<RecordDecl>(
3703 static_cast<TagDecl *>(this)->getPreviousDecl());
3704 }
3705 const RecordDecl *getPreviousDecl() const {
3706 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3707 }
3708
3709 RecordDecl *getMostRecentDecl() {
3710 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3711 }
3712 const RecordDecl *getMostRecentDecl() const {
3713 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3714 }
3715
3716 bool hasFlexibleArrayMember() const {
3717 return RecordDeclBits.HasFlexibleArrayMember;
3718 }
3719
3720 void setHasFlexibleArrayMember(bool V) {
3721 RecordDeclBits.HasFlexibleArrayMember = V;
3722 }
3723
3724 /// Whether this is an anonymous struct or union. To be an anonymous
3725 /// struct or union, it must have been declared without a name and
3726 /// there must be no objects of this type declared, e.g.,
3727 /// @code
3728 /// union { int i; float f; };
3729 /// @endcode
3730 /// is an anonymous union but neither of the following are:
3731 /// @code
3732 /// union X { int i; float f; };
3733 /// union { int i; float f; } obj;
3734 /// @endcode
3735 bool isAnonymousStructOrUnion() const {
3736 return RecordDeclBits.AnonymousStructOrUnion;
3737 }
3738
3739 void setAnonymousStructOrUnion(bool Anon) {
3740 RecordDeclBits.AnonymousStructOrUnion = Anon;
3741 }
3742
3743 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3744 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3745
3746 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3747
3748 void setHasVolatileMember(bool val) {
3749 RecordDeclBits.HasVolatileMember = val;
3750 }
3751
3752 bool hasLoadedFieldsFromExternalStorage() const {
3753 return RecordDeclBits.LoadedFieldsFromExternalStorage;
3754 }
3755
3756 void setHasLoadedFieldsFromExternalStorage(bool val) const {
3757 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3758 }
3759
3760 /// Functions to query basic properties of non-trivial C structs.
3761 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3762 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3763 }
3764
3765 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3766 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3767 }
3768
3769 bool isNonTrivialToPrimitiveCopy() const {
3770 return RecordDeclBits.NonTrivialToPrimitiveCopy;
3771 }
3772
3773 void setNonTrivialToPrimitiveCopy(bool V) {
3774 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3775 }
3776
3777 bool isNonTrivialToPrimitiveDestroy() const {
3778 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3779 }
3780
3781 void setNonTrivialToPrimitiveDestroy(bool V) {
3782 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3783 }
3784
3785 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
3786 return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
3787 }
3788
3789 void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
3790 RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
3791 }
3792
3793 bool hasNonTrivialToPrimitiveDestructCUnion() const {
3794 return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
3795 }
3796
3797 void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
3798 RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
3799 }
3800
3801 bool hasNonTrivialToPrimitiveCopyCUnion() const {
3802 return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
3803 }
3804
3805 void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
3806 RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
3807 }
3808
3809 /// Determine whether this class can be passed in registers. In C++ mode,
3810 /// it must have at least one trivial, non-deleted copy or move constructor.
3811 /// FIXME: This should be set as part of completeDefinition.
3812 bool canPassInRegisters() const {
3813 return getArgPassingRestrictions() == APK_CanPassInRegs;
3814 }
3815
3816 ArgPassingKind getArgPassingRestrictions() const {
3817 return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3818 }
3819
3820 void setArgPassingRestrictions(ArgPassingKind Kind) {
3821 RecordDeclBits.ArgPassingRestrictions = Kind;
3822 }
3823
3824 bool isParamDestroyedInCallee() const {
3825 return RecordDeclBits.ParamDestroyedInCallee;
3826 }
3827
3828 void setParamDestroyedInCallee(bool V) {
3829 RecordDeclBits.ParamDestroyedInCallee = V;
3830 }
3831
3832 /// Determines whether this declaration represents the
3833 /// injected class name.
3834 ///
3835 /// The injected class name in C++ is the name of the class that
3836 /// appears inside the class itself. For example:
3837 ///
3838 /// \code
3839 /// struct C {
3840 /// // C is implicitly declared here as a synonym for the class name.
3841 /// };
3842 ///
3843 /// C::C c; // same as "C c;"
3844 /// \endcode
3845 bool isInjectedClassName() const;
3846
3847 /// Determine whether this record is a class describing a lambda
3848 /// function object.
3849 bool isLambda() const;
3850
3851 /// Determine whether this record is a record for captured variables in
3852 /// CapturedStmt construct.
3853 bool isCapturedRecord() const;
3854
3855 /// Mark the record as a record for captured variables in CapturedStmt
3856 /// construct.
3857 void setCapturedRecord();
3858
3859 /// Returns the RecordDecl that actually defines
3860 /// this struct/union/class. When determining whether or not a
3861 /// struct/union/class is completely defined, one should use this
3862 /// method as opposed to 'isCompleteDefinition'.
3863 /// 'isCompleteDefinition' indicates whether or not a specific
3864 /// RecordDecl is a completed definition, not whether or not the
3865 /// record type is defined. This method returns NULL if there is
3866 /// no RecordDecl that defines the struct/union/tag.
3867 RecordDecl *getDefinition() const {
3868 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3869 }
3870
3871 // Iterator access to field members. The field iterator only visits
3872 // the non-static data members of this class, ignoring any static
3873 // data members, functions, constructors, destructors, etc.
3874 using field_iterator = specific_decl_iterator<FieldDecl>;
3875 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3876
3877 field_range fields() const { return field_range(field_begin(), field_end()); }
3878 field_iterator field_begin() const;
3879
3880 field_iterator field_end() const {
3881 return field_iterator(decl_iterator());
3882 }
3883
3884 // Whether there are any fields (non-static data members) in this record.
3885 bool field_empty() const {
3886 return field_begin() == field_end();
3887 }
3888
3889 /// Note that the definition of this type is now complete.
3890 virtual void completeDefinition();
3891
3892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3893 static bool classofKind(Kind K) {
3894 return K >= firstRecord && K <= lastRecord;
3895 }
3896
3897 /// Get whether or not this is an ms_struct which can
3898 /// be turned on with an attribute, pragma, or -mms-bitfields
3899 /// commandline option.
3900 bool isMsStruct(const ASTContext &C) const;
3901
3902 /// Whether we are allowed to insert extra padding between fields.
3903 /// These padding are added to help AddressSanitizer detect
3904 /// intra-object-overflow bugs.
3905 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3906
3907 /// Finds the first data member which has a name.
3908 /// nullptr is returned if no named data member exists.
3909 const FieldDecl *findFirstNamedDataMember() const;
3910
3911private:
3912 /// Deserialize just the fields.
3913 void LoadFieldsFromExternalStorage() const;
3914};
3915
3916class FileScopeAsmDecl : public Decl {
3917 StringLiteral *AsmString;
3918 SourceLocation RParenLoc;
3919
3920 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3921 SourceLocation StartL, SourceLocation EndL)
3922 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3923
3924 virtual void anchor();
3925
3926public:
3927 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3928 StringLiteral *Str, SourceLocation AsmLoc,
3929 SourceLocation RParenLoc);
3930
3931 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3932
3933 SourceLocation getAsmLoc() const { return getLocation(); }
3934 SourceLocation getRParenLoc() const { return RParenLoc; }
3935 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3936 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3937 return SourceRange(getAsmLoc(), getRParenLoc());
3938 }
3939
3940 const StringLiteral *getAsmString() const { return AsmString; }
3941 StringLiteral *getAsmString() { return AsmString; }
3942 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3943
3944 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3945 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3946};
3947
3948/// Represents a block literal declaration, which is like an
3949/// unnamed FunctionDecl. For example:
3950/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3951class BlockDecl : public Decl, public DeclContext {
3952 // This class stores some data in DeclContext::BlockDeclBits
3953 // to save some space. Use the provided accessors to access it.
3954public:
3955 /// A class which contains all the information about a particular
3956 /// captured value.
3957 class Capture {
3958 enum {
3959 flag_isByRef = 0x1,
3960 flag_isNested = 0x2
3961 };
3962
3963 /// The variable being captured.
3964 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3965
3966 /// The copy expression, expressed in terms of a DeclRef (or
3967 /// BlockDeclRef) to the captured variable. Only required if the
3968 /// variable has a C++ class type.
3969 Expr *CopyExpr;
3970
3971 public:
3972 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3973 : VariableAndFlags(variable,
3974 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3975 CopyExpr(copy) {}
3976
3977 /// The variable being captured.
3978 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3979
3980 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3981 /// variable.
3982 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3983
3984 bool isEscapingByref() const {
3985 return getVariable()->isEscapingByref();
3986 }
3987
3988 bool isNonEscapingByref() const {
3989 return getVariable()->isNonEscapingByref();
3990 }
3991
3992 /// Whether this is a nested capture, i.e. the variable captured
3993 /// is not from outside the immediately enclosing function/block.
3994 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3995
3996 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3997 Expr *getCopyExpr() const { return CopyExpr; }
3998 void setCopyExpr(Expr *e) { CopyExpr = e; }
3999 };
4000
4001private:
4002 /// A new[]'d array of pointers to ParmVarDecls for the formal
4003 /// parameters of this function. This is null if a prototype or if there are
4004 /// no formals.
4005 ParmVarDecl **ParamInfo = nullptr;
4006 unsigned NumParams = 0;
4007
4008 Stmt *Body = nullptr;
4009 TypeSourceInfo *SignatureAsWritten = nullptr;
4010
4011 const Capture *Captures = nullptr;
4012 unsigned NumCaptures = 0;
4013
4014 unsigned ManglingNumber = 0;
4015 Decl *ManglingContextDecl = nullptr;
4016
4017protected:
4018 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4019
4020public:
4021 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4022 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4023
4024 SourceLocation getCaretLocation() const { return getLocation(); }
4025
4026 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4027 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4028
4029 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4030 Stmt *getBody() const override { return (Stmt*) Body; }
4031 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4032
4033 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4034 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4035
4036 // ArrayRef access to formal parameters.
4037 ArrayRef<ParmVarDecl *> parameters() const {
4038 return {ParamInfo, getNumParams()};
4039 }
4040 MutableArrayRef<ParmVarDecl *> parameters() {
4041 return {ParamInfo, getNumParams()};
4042 }
4043
4044 // Iterator access to formal parameters.
4045 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4046 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4047
4048 bool param_empty() const { return parameters().empty(); }
4049 param_iterator param_begin() { return parameters().begin(); }
4050 param_iterator param_end() { return parameters().end(); }
4051 param_const_iterator param_begin() const { return parameters().begin(); }
4052 param_const_iterator param_end() const { return parameters().end(); }
4053 size_t param_size() const { return parameters().size(); }
4054
4055 unsigned getNumParams() const { return NumParams; }
4056
4057 const ParmVarDecl *getParamDecl(unsigned i) const {
4058 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4058, __PRETTY_FUNCTION__))
;
4059 return ParamInfo[i];
4060 }
4061 ParmVarDecl *getParamDecl(unsigned i) {
4062 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4062, __PRETTY_FUNCTION__))
;
4063 return ParamInfo[i];
4064 }
4065
4066 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4067
4068 /// True if this block (or its nested blocks) captures
4069 /// anything of local storage from its enclosing scopes.
4070 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4071
4072 /// Returns the number of captured variables.
4073 /// Does not include an entry for 'this'.
4074 unsigned getNumCaptures() const { return NumCaptures; }
4075
4076 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4077
4078 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4079
4080 capture_const_iterator capture_begin() const { return captures().begin(); }
4081 capture_const_iterator capture_end() const { return captures().end(); }
4082
4083 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4084 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4085
4086 bool blockMissingReturnType() const {
4087 return BlockDeclBits.BlockMissingReturnType;
4088 }
4089
4090 void setBlockMissingReturnType(bool val = true) {
4091 BlockDeclBits.BlockMissingReturnType = val;
4092 }
4093
4094 bool isConversionFromLambda() const {
4095 return BlockDeclBits.IsConversionFromLambda;
4096 }
4097
4098 void setIsConversionFromLambda(bool val = true) {
4099 BlockDeclBits.IsConversionFromLambda = val;
4100 }
4101
4102 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4103 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4104
4105 bool canAvoidCopyToHeap() const {
4106 return BlockDeclBits.CanAvoidCopyToHeap;
4107 }
4108 void setCanAvoidCopyToHeap(bool B = true) {
4109 BlockDeclBits.CanAvoidCopyToHeap = B;
4110 }
4111
4112 bool capturesVariable(const VarDecl *var) const;
4113
4114 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4115 bool CapturesCXXThis);
4116
4117 unsigned getBlockManglingNumber() const {
4118 return ManglingNumber;
4119 }
4120
4121 Decl *getBlockManglingContextDecl() const {
4122 return ManglingContextDecl;
4123 }
4124
4125 void setBlockMangling(unsigned Number, Decl *Ctx) {
4126 ManglingNumber = Number;
4127 ManglingContextDecl = Ctx;
4128 }
4129
4130 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4131
4132 // Implement isa/cast/dyncast/etc.
4133 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4134 static bool classofKind(Kind K) { return K == Block; }
4135 static DeclContext *castToDeclContext(const BlockDecl *D) {
4136 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4137 }
4138 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4139 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4140 }
4141};
4142
4143/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4144class CapturedDecl final
4145 : public Decl,
4146 public DeclContext,
4147 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4148protected:
4149 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4150 return NumParams;
4151 }
4152
4153private:
4154 /// The number of parameters to the outlined function.
4155 unsigned NumParams;
4156
4157 /// The position of context parameter in list of parameters.
4158 unsigned ContextParam;
4159
4160 /// The body of the outlined function.
4161 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4162
4163 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4164
4165 ImplicitParamDecl *const *getParams() const {
4166 return getTrailingObjects<ImplicitParamDecl *>();
4167 }
4168
4169 ImplicitParamDecl **getParams() {
4170 return getTrailingObjects<ImplicitParamDecl *>();
4171 }
4172
4173public:
4174 friend class ASTDeclReader;
4175 friend class ASTDeclWriter;
4176 friend TrailingObjects;
4177
4178 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4179 unsigned NumParams);
4180 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4181 unsigned NumParams);
4182
4183 Stmt *getBody() const override;
4184 void setBody(Stmt *B);
4185
4186 bool isNothrow() const;
4187 void setNothrow(bool Nothrow = true);
4188
4189 unsigned getNumParams() const { return NumParams; }
4190
4191 ImplicitParamDecl *getParam(unsigned i) const {
4192 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4192, __PRETTY_FUNCTION__))
;
4193 return getParams()[i];
4194 }
4195 void setParam(unsigned i, ImplicitParamDecl *P) {
4196 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4196, __PRETTY_FUNCTION__))
;
4197 getParams()[i] = P;
4198 }
4199
4200 // ArrayRef interface to parameters.
4201 ArrayRef<ImplicitParamDecl *> parameters() const {
4202 return {getParams(), getNumParams()};
4203 }
4204 MutableArrayRef<ImplicitParamDecl *> parameters() {
4205 return {getParams(), getNumParams()};
4206 }
4207
4208 /// Retrieve the parameter containing captured variables.
4209 ImplicitParamDecl *getContextParam() const {
4210 assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) :
__assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4210, __PRETTY_FUNCTION__))
;
4211 return getParam(ContextParam);
4212 }
4213 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4214 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4214, __PRETTY_FUNCTION__))
;
4215 ContextParam = i;
4216 setParam(i, P);
4217 }
4218 unsigned getContextParamPosition() const { return ContextParam; }
4219
4220 using param_iterator = ImplicitParamDecl *const *;
4221 using param_range = llvm::iterator_range<param_iterator>;
4222
4223 /// Retrieve an iterator pointing to the first parameter decl.
4224 param_iterator param_begin() const { return getParams(); }
4225 /// Retrieve an iterator one past the last parameter decl.
4226 param_iterator param_end() const { return getParams() + NumParams; }
4227
4228 // Implement isa/cast/dyncast/etc.
4229 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4230 static bool classofKind(Kind K) { return K == Captured; }
4231 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4232 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4233 }
4234 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4235 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4236 }
4237};
4238
4239/// Describes a module import declaration, which makes the contents
4240/// of the named module visible in the current translation unit.
4241///
4242/// An import declaration imports the named module (or submodule). For example:
4243/// \code
4244/// @import std.vector;
4245/// \endcode
4246///
4247/// Import declarations can also be implicitly generated from
4248/// \#include/\#import directives.
4249class ImportDecl final : public Decl,
4250 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4251 friend class ASTContext;
4252 friend class ASTDeclReader;
4253 friend class ASTReader;
4254 friend TrailingObjects;
4255
4256 /// The imported module, along with a bit that indicates whether
4257 /// we have source-location information for each identifier in the module
4258 /// name.
4259 ///
4260 /// When the bit is false, we only have a single source location for the
4261 /// end of the import declaration.
4262 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4263
4264 /// The next import in the list of imports local to the translation
4265 /// unit being parsed (not loaded from an AST file).
4266 ImportDecl *NextLocalImport = nullptr;
4267
4268 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4269 ArrayRef<SourceLocation> IdentifierLocs);
4270
4271 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4272 SourceLocation EndLoc);
4273
4274 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4275
4276public:
4277 /// Create a new module import declaration.
4278 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4279 SourceLocation StartLoc, Module *Imported,
4280 ArrayRef<SourceLocation> IdentifierLocs);
4281
4282 /// Create a new module import declaration for an implicitly-generated
4283 /// import.
4284 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4285 SourceLocation StartLoc, Module *Imported,
4286 SourceLocation EndLoc);
4287
4288 /// Create a new, deserialized module import declaration.
4289 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4290 unsigned NumLocations);
4291
4292 /// Retrieve the module that was imported by the import declaration.
4293 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4294
4295 /// Retrieves the locations of each of the identifiers that make up
4296 /// the complete module name in the import declaration.
4297 ///
4298 /// This will return an empty array if the locations of the individual
4299 /// identifiers aren't available.
4300 ArrayRef<SourceLocation> getIdentifierLocs() const;
4301
4302 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4303
4304 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4305 static bool classofKind(Kind K) { return K == Import; }
4306};
4307
4308/// Represents a C++ Modules TS module export declaration.
4309///
4310/// For example:
4311/// \code
4312/// export void foo();
4313/// \endcode
4314class ExportDecl final : public Decl, public DeclContext {
4315 virtual void anchor();
4316
4317private:
4318 friend class ASTDeclReader;
4319
4320 /// The source location for the right brace (if valid).
4321 SourceLocation RBraceLoc;
4322
4323 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4324 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4325 RBraceLoc(SourceLocation()) {}
4326
4327public:
4328 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4329 SourceLocation ExportLoc);
4330 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4331
4332 SourceLocation getExportLoc() const { return getLocation(); }
4333 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4334 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4335
4336 bool hasBraces() const { return RBraceLoc.isValid(); }
4337
4338 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4339 if (hasBraces())
4340 return RBraceLoc;
4341 // No braces: get the end location of the (only) declaration in context
4342 // (if present).
4343 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4344 }
4345
4346 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4347 return SourceRange(getLocation(), getEndLoc());
4348 }
4349
4350 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4351 static bool classofKind(Kind K) { return K == Export; }
4352 static DeclContext *castToDeclContext(const ExportDecl *D) {
4353 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4354 }
4355 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4356 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4357 }
4358};
4359
4360/// Represents an empty-declaration.
4361class EmptyDecl : public Decl {
4362 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4363
4364 virtual void anchor();
4365
4366public:
4367 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4368 SourceLocation L);
4369 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4370
4371 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4372 static bool classofKind(Kind K) { return K == Empty; }
4373};
4374
4375/// Insertion operator for diagnostics. This allows sending NamedDecl's
4376/// into a diagnostic with <<.
4377inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4378 const NamedDecl* ND) {
4379 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4380 DiagnosticsEngine::ak_nameddecl);
4381 return DB;
4382}
4383inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4384 const NamedDecl* ND) {
4385 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4386 DiagnosticsEngine::ak_nameddecl);
4387 return PD;
4388}
4389
4390template<typename decl_type>
4391void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4392 // Note: This routine is implemented here because we need both NamedDecl
4393 // and Redeclarable to be defined.
4394 assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4395, __PRETTY_FUNCTION__))
4395 "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4395, __PRETTY_FUNCTION__))
;
4396
4397 if (PrevDecl) {
4398 // Point to previous. Make sure that this is actually the most recent
4399 // redeclaration, or we can build invalid chains. If the most recent
4400 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4401 First = PrevDecl->getFirstDecl();
4402 assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first")
? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4402, __PRETTY_FUNCTION__))
;
4403 decl_type *MostRecent = First->getNextRedeclaration();
4404 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4405
4406 // If the declaration was previously visible, a redeclaration of it remains
4407 // visible even if it wouldn't be visible by itself.
4408 static_cast<decl_type*>(this)->IdentifierNamespace |=
4409 MostRecent->getIdentifierNamespace() &
4410 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4411 } else {
4412 // Make this first.
4413 First = static_cast<decl_type*>(this);
4414 }
4415
4416 // First one will point to this one as latest.
4417 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4418
4419 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4420, __PRETTY_FUNCTION__))
4420 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-10~svn373253/tools/clang/include/clang/AST/Decl.h"
, 4420, __PRETTY_FUNCTION__))
;
4421}
4422
4423// Inline function definitions.
4424
4425/// Check if the given decl is complete.
4426///
4427/// We use this function to break a cycle between the inline definitions in
4428/// Type.h and Decl.h.
4429inline bool IsEnumDeclComplete(EnumDecl *ED) {
4430 return ED->isComplete();
4431}
4432
4433/// Check if the given decl is scoped.
4434///
4435/// We use this function to break a cycle between the inline definitions in
4436/// Type.h and Decl.h.
4437inline bool IsEnumDeclScoped(EnumDecl *ED) {
4438 return ED->isScoped();
4439}
4440
4441} // namespace clang
4442
4443#endif // LLVM_CLANG_AST_DECL_H

/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
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 defines the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/AlignOf.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include "llvm/Support/ErrorHandling.h"
23#include <algorithm>
24#include <cassert>
25#include <cstddef>
26#include <cstdlib>
27#include <cstring>
28#include <initializer_list>
29#include <iterator>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the non-templated stuff common to all SmallVectors.
38class SmallVectorBase {
39protected:
40 void *BeginX;
41 unsigned Size = 0, Capacity;
42
43 SmallVectorBase() = delete;
44 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
45 : BeginX(FirstEl), Capacity(TotalCapacity) {}
46
47 /// This is an implementation of the grow() method which only works
48 /// on POD-like data types and is out of line to reduce code duplication.
49 void grow_pod(void *FirstEl, size_t MinCapacity, size_t TSize);
50
51public:
52 size_t size() const { return Size; }
53 size_t capacity() const { return Capacity; }
54
55 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
68
Assuming field 'Size' is not equal to 0, which participates in a condition later
69
Returning zero, which participates in a condition later
56
57 /// Set the array size to \p N, which the current array must have enough
58 /// capacity for.
59 ///
60 /// This does not construct or destroy any elements in the vector.
61 ///
62 /// Clients can use this in conjunction with capacity() to write past the end
63 /// of the buffer when they know that more elements are available, and only
64 /// update the size later. This avoids the cost of value initializing elements
65 /// which will only be overwritten.
66 void set_size(size_t N) {
67 assert(N <= capacity())((N <= capacity()) ? static_cast<void> (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 67, __PRETTY_FUNCTION__))
;
68 Size = N;
69 }
70};
71
72/// Figure out the offset of the first element.
73template <class T, typename = void> struct SmallVectorAlignmentAndSize {
74 AlignedCharArrayUnion<SmallVectorBase> Base;
75 AlignedCharArrayUnion<T> FirstEl;
76};
77
78/// This is the part of SmallVectorTemplateBase which does not depend on whether
79/// the type T is a POD. The extra dummy template argument is used by ArrayRef
80/// to avoid unnecessarily requiring T to be complete.
81template <typename T, typename = void>
82class SmallVectorTemplateCommon : public SmallVectorBase {
83 /// Find the address of the first element. For this pointer math to be valid
84 /// with small-size of 0 for T with lots of alignment, it's important that
85 /// SmallVectorStorage is properly-aligned even for small-size of 0.
86 void *getFirstEl() const {
87 return const_cast<void *>(reinterpret_cast<const void *>(
88 reinterpret_cast<const char *>(this) +
89 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
90 }
91 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
92
93protected:
94 SmallVectorTemplateCommon(size_t Size)
95 : SmallVectorBase(getFirstEl(), Size) {}
96
97 void grow_pod(size_t MinCapacity, size_t TSize) {
98 SmallVectorBase::grow_pod(getFirstEl(), MinCapacity, TSize);
99 }
100
101 /// Return true if this is a smallvector which has not had dynamic
102 /// memory allocated for it.
103 bool isSmall() const { return BeginX == getFirstEl(); }
104
105 /// Put this vector in a state of being small.
106 void resetToSmall() {
107 BeginX = getFirstEl();
108 Size = Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
109 }
110
111public:
112 using size_type = size_t;
113 using difference_type = ptrdiff_t;
114 using value_type = T;
115 using iterator = T *;
116 using const_iterator = const T *;
117
118 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
119 using reverse_iterator = std::reverse_iterator<iterator>;
120
121 using reference = T &;
122 using const_reference = const T &;
123 using pointer = T *;
124 using const_pointer = const T *;
125
126 // forward iterator creation methods.
127 iterator begin() { return (iterator)this->BeginX; }
128 const_iterator begin() const { return (const_iterator)this->BeginX; }
129 iterator end() { return begin() + size(); }
130 const_iterator end() const { return begin() + size(); }
131
132 // reverse iterator creation methods.
133 reverse_iterator rbegin() { return reverse_iterator(end()); }
134 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
135 reverse_iterator rend() { return reverse_iterator(begin()); }
136 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
137
138 size_type size_in_bytes() const { return size() * sizeof(T); }
139 size_type max_size() const { return size_type(-1) / sizeof(T); }
140
141 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
142
143 /// Return a pointer to the vector's buffer, even if empty().
144 pointer data() { return pointer(begin()); }
145 /// Return a pointer to the vector's buffer, even if empty().
146 const_pointer data() const { return const_pointer(begin()); }
147
148 reference operator[](size_type idx) {
149 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 149, __PRETTY_FUNCTION__))
;
150 return begin()[idx];
151 }
152 const_reference operator[](size_type idx) const {
153 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 153, __PRETTY_FUNCTION__))
;
154 return begin()[idx];
155 }
156
157 reference front() {
158 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 158, __PRETTY_FUNCTION__))
;
159 return begin()[0];
160 }
161 const_reference front() const {
162 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 162, __PRETTY_FUNCTION__))
;
163 return begin()[0];
164 }
165
166 reference back() {
167 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 167, __PRETTY_FUNCTION__))
;
168 return end()[-1];
169 }
170 const_reference back() const {
171 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 171, __PRETTY_FUNCTION__))
;
172 return end()[-1];
173 }
174};
175
176/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put method
177/// implementations that are designed to work with non-POD-like T's.
178template <typename T, bool = is_trivially_copyable<T>::value>
179class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
180protected:
181 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
182
183 static void destroy_range(T *S, T *E) {
184 while (S != E) {
185 --E;
186 E->~T();
187 }
188 }
189
190 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
191 /// constructing elements as needed.
192 template<typename It1, typename It2>
193 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
194 std::uninitialized_copy(std::make_move_iterator(I),
195 std::make_move_iterator(E), Dest);
196 }
197
198 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
199 /// constructing elements as needed.
200 template<typename It1, typename It2>
201 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
202 std::uninitialized_copy(I, E, Dest);
203 }
204
205 /// Grow the allocated memory (without initializing new elements), doubling
206 /// the size of the allocated memory. Guarantees space for at least one more
207 /// element, or MinSize more elements if specified.
208 void grow(size_t MinSize = 0);
209
210public:
211 void push_back(const T &Elt) {
212 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
213 this->grow();
214 ::new ((void*) this->end()) T(Elt);
215 this->set_size(this->size() + 1);
216 }
217
218 void push_back(T &&Elt) {
219 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
220 this->grow();
221 ::new ((void*) this->end()) T(::std::move(Elt));
222 this->set_size(this->size() + 1);
223 }
224
225 void pop_back() {
226 this->set_size(this->size() - 1);
227 this->end()->~T();
228 }
229};
230
231// Define this out-of-line to dissuade the C++ compiler from inlining it.
232template <typename T, bool TriviallyCopyable>
233void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
234 if (MinSize > UINT32_MAX(4294967295U))
235 report_bad_alloc_error("SmallVector capacity overflow during allocation");
236
237 // Always grow, even from zero.
238 size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + 2));
239 NewCapacity = std::min(std::max(NewCapacity, MinSize), size_t(UINT32_MAX(4294967295U)));
240 T *NewElts = static_cast<T*>(llvm::safe_malloc(NewCapacity*sizeof(T)));
241
242 // Move the elements over.
243 this->uninitialized_move(this->begin(), this->end(), NewElts);
244
245 // Destroy the original elements.
246 destroy_range(this->begin(), this->end());
247
248 // If this wasn't grown from the inline copy, deallocate the old space.
249 if (!this->isSmall())
250 free(this->begin());
251
252 this->BeginX = NewElts;
253 this->Capacity = NewCapacity;
254}
255
256/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
257/// method implementations that are designed to work with POD-like T's.
258template <typename T>
259class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
260protected:
261 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
262
263 // No need to do a destroy loop for POD's.
264 static void destroy_range(T *, T *) {}
265
266 /// Move the range [I, E) onto the uninitialized memory
267 /// starting with "Dest", constructing elements into it as needed.
268 template<typename It1, typename It2>
269 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
270 // Just do a copy.
271 uninitialized_copy(I, E, Dest);
272 }
273
274 /// Copy the range [I, E) onto the uninitialized memory
275 /// starting with "Dest", constructing elements into it as needed.
276 template<typename It1, typename It2>
277 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
278 // Arbitrary iterator types; just use the basic implementation.
279 std::uninitialized_copy(I, E, Dest);
280 }
281
282 /// Copy the range [I, E) onto the uninitialized memory
283 /// starting with "Dest", constructing elements into it as needed.
284 template <typename T1, typename T2>
285 static void uninitialized_copy(
286 T1 *I, T1 *E, T2 *Dest,
287 typename std::enable_if<std::is_same<typename std::remove_const<T1>::type,
288 T2>::value>::type * = nullptr) {
289 // Use memcpy for PODs iterated by pointers (which includes SmallVector
290 // iterators): std::uninitialized_copy optimizes to memmove, but we can
291 // use memcpy here. Note that I and E are iterators and thus might be
292 // invalid for memcpy if they are equal.
293 if (I != E)
294 memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
295 }
296
297 /// Double the size of the allocated memory, guaranteeing space for at
298 /// least one more element or MinSize if specified.
299 void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
300
301public:
302 void push_back(const T &Elt) {
303 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
304 this->grow();
305 memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T));
306 this->set_size(this->size() + 1);
307 }
308
309 void pop_back() { this->set_size(this->size() - 1); }
310};
311
312/// This class consists of common code factored out of the SmallVector class to
313/// reduce code duplication based on the SmallVector 'N' template parameter.
314template <typename T>
315class SmallVectorImpl : public SmallVectorTemplateBase<T> {
316 using SuperClass = SmallVectorTemplateBase<T>;
317
318public:
319 using iterator = typename SuperClass::iterator;
320 using const_iterator = typename SuperClass::const_iterator;
321 using reference = typename SuperClass::reference;
322 using size_type = typename SuperClass::size_type;
323
324protected:
325 // Default ctor - Initialize to empty.
326 explicit SmallVectorImpl(unsigned N)
327 : SmallVectorTemplateBase<T>(N) {}
328
329public:
330 SmallVectorImpl(const SmallVectorImpl &) = delete;
331
332 ~SmallVectorImpl() {
333 // Subclass has already destructed this vector's elements.
334 // If this wasn't grown from the inline copy, deallocate the old space.
335 if (!this->isSmall())
336 free(this->begin());
337 }
338
339 void clear() {
340 this->destroy_range(this->begin(), this->end());
341 this->Size = 0;
342 }
343
344 void resize(size_type N) {
345 if (N < this->size()) {
346 this->destroy_range(this->begin()+N, this->end());
347 this->set_size(N);
348 } else if (N > this->size()) {
349 if (this->capacity() < N)
350 this->grow(N);
351 for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
352 new (&*I) T();
353 this->set_size(N);
354 }
355 }
356
357 void resize(size_type N, const T &NV) {
358 if (N < this->size()) {
359 this->destroy_range(this->begin()+N, this->end());
360 this->set_size(N);
361 } else if (N > this->size()) {
362 if (this->capacity() < N)
363 this->grow(N);
364 std::uninitialized_fill(this->end(), this->begin()+N, NV);
365 this->set_size(N);
366 }
367 }
368
369 void reserve(size_type N) {
370 if (this->capacity() < N)
371 this->grow(N);
372 }
373
374 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
375 T Result = ::std::move(this->back());
376 this->pop_back();
377 return Result;
378 }
379
380 void swap(SmallVectorImpl &RHS);
381
382 /// Add the specified range to the end of the SmallVector.
383 template <typename in_iter,
384 typename = typename std::enable_if<std::is_convertible<
385 typename std::iterator_traits<in_iter>::iterator_category,
386 std::input_iterator_tag>::value>::type>
387 void append(in_iter in_start, in_iter in_end) {
388 size_type NumInputs = std::distance(in_start, in_end);
389 if (NumInputs > this->capacity() - this->size())
390 this->grow(this->size()+NumInputs);
391
392 this->uninitialized_copy(in_start, in_end, this->end());
393 this->set_size(this->size() + NumInputs);
394 }
395
396 /// Append \p NumInputs copies of \p Elt to the end.
397 void append(size_type NumInputs, const T &Elt) {
398 if (NumInputs > this->capacity() - this->size())
399 this->grow(this->size()+NumInputs);
400
401 std::uninitialized_fill_n(this->end(), NumInputs, Elt);
402 this->set_size(this->size() + NumInputs);
403 }
404
405 void append(std::initializer_list<T> IL) {
406 append(IL.begin(), IL.end());
407 }
408
409 // FIXME: Consider assigning over existing elements, rather than clearing &
410 // re-initializing them - for all assign(...) variants.
411
412 void assign(size_type NumElts, const T &Elt) {
413 clear();
414 if (this->capacity() < NumElts)
415 this->grow(NumElts);
416 this->set_size(NumElts);
417 std::uninitialized_fill(this->begin(), this->end(), Elt);
418 }
419
420 template <typename in_iter,
421 typename = typename std::enable_if<std::is_convertible<
422 typename std::iterator_traits<in_iter>::iterator_category,
423 std::input_iterator_tag>::value>::type>
424 void assign(in_iter in_start, in_iter in_end) {
425 clear();
426 append(in_start, in_end);
427 }
428
429 void assign(std::initializer_list<T> IL) {
430 clear();
431 append(IL);
432 }
433
434 iterator erase(const_iterator CI) {
435 // Just cast away constness because this is a non-const member function.
436 iterator I = const_cast<iterator>(CI);
437
438 assert(I >= this->begin() && "Iterator to erase is out of bounds.")((I >= this->begin() && "Iterator to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Iterator to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 438, __PRETTY_FUNCTION__))
;
439 assert(I < this->end() && "Erasing at past-the-end iterator.")((I < this->end() && "Erasing at past-the-end iterator."
) ? static_cast<void> (0) : __assert_fail ("I < this->end() && \"Erasing at past-the-end iterator.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 439, __PRETTY_FUNCTION__))
;
440
441 iterator N = I;
442 // Shift all elts down one.
443 std::move(I+1, this->end(), I);
444 // Drop the last elt.
445 this->pop_back();
446 return(N);
447 }
448
449 iterator erase(const_iterator CS, const_iterator CE) {
450 // Just cast away constness because this is a non-const member function.
451 iterator S = const_cast<iterator>(CS);
452 iterator E = const_cast<iterator>(CE);
453
454 assert(S >= this->begin() && "Range to erase is out of bounds.")((S >= this->begin() && "Range to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("S >= this->begin() && \"Range to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 454, __PRETTY_FUNCTION__))
;
455 assert(S <= E && "Trying to erase invalid range.")((S <= E && "Trying to erase invalid range.") ? static_cast
<void> (0) : __assert_fail ("S <= E && \"Trying to erase invalid range.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(E <= this->end() && "Trying to erase past the end.")((E <= this->end() && "Trying to erase past the end."
) ? static_cast<void> (0) : __assert_fail ("E <= this->end() && \"Trying to erase past the end.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 456, __PRETTY_FUNCTION__))
;
457
458 iterator N = S;
459 // Shift all elts down.
460 iterator I = std::move(E, this->end(), S);
461 // Drop the last elts.
462 this->destroy_range(I, this->end());
463 this->set_size(I - this->begin());
464 return(N);
465 }
466
467 iterator insert(iterator I, T &&Elt) {
468 if (I == this->end()) { // Important special case for empty vector.
469 this->push_back(::std::move(Elt));
470 return this->end()-1;
471 }
472
473 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 473, __PRETTY_FUNCTION__))
;
474 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 474, __PRETTY_FUNCTION__))
;
475
476 if (this->size() >= this->capacity()) {
477 size_t EltNo = I-this->begin();
478 this->grow();
479 I = this->begin()+EltNo;
480 }
481
482 ::new ((void*) this->end()) T(::std::move(this->back()));
483 // Push everything else over.
484 std::move_backward(I, this->end()-1, this->end());
485 this->set_size(this->size() + 1);
486
487 // If we just moved the element we're inserting, be sure to update
488 // the reference.
489 T *EltPtr = &Elt;
490 if (I <= EltPtr && EltPtr < this->end())
491 ++EltPtr;
492
493 *I = ::std::move(*EltPtr);
494 return I;
495 }
496
497 iterator insert(iterator I, const T &Elt) {
498 if (I == this->end()) { // Important special case for empty vector.
499 this->push_back(Elt);
500 return this->end()-1;
501 }
502
503 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 503, __PRETTY_FUNCTION__))
;
504 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 504, __PRETTY_FUNCTION__))
;
505
506 if (this->size() >= this->capacity()) {
507 size_t EltNo = I-this->begin();
508 this->grow();
509 I = this->begin()+EltNo;
510 }
511 ::new ((void*) this->end()) T(std::move(this->back()));
512 // Push everything else over.
513 std::move_backward(I, this->end()-1, this->end());
514 this->set_size(this->size() + 1);
515
516 // If we just moved the element we're inserting, be sure to update
517 // the reference.
518 const T *EltPtr = &Elt;
519 if (I <= EltPtr && EltPtr < this->end())
520 ++EltPtr;
521
522 *I = *EltPtr;
523 return I;
524 }
525
526 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
527 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
528 size_t InsertElt = I - this->begin();
529
530 if (I == this->end()) { // Important special case for empty vector.
531 append(NumToInsert, Elt);
532 return this->begin()+InsertElt;
533 }
534
535 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 535, __PRETTY_FUNCTION__))
;
536 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 536, __PRETTY_FUNCTION__))
;
537
538 // Ensure there is enough space.
539 reserve(this->size() + NumToInsert);
540
541 // Uninvalidate the iterator.
542 I = this->begin()+InsertElt;
543
544 // If there are more elements between the insertion point and the end of the
545 // range than there are being inserted, we can use a simple approach to
546 // insertion. Since we already reserved space, we know that this won't
547 // reallocate the vector.
548 if (size_t(this->end()-I) >= NumToInsert) {
549 T *OldEnd = this->end();
550 append(std::move_iterator<iterator>(this->end() - NumToInsert),
551 std::move_iterator<iterator>(this->end()));
552
553 // Copy the existing elements that get replaced.
554 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
555
556 std::fill_n(I, NumToInsert, Elt);
557 return I;
558 }
559
560 // Otherwise, we're inserting more elements than exist already, and we're
561 // not inserting at the end.
562
563 // Move over the elements that we're about to overwrite.
564 T *OldEnd = this->end();
565 this->set_size(this->size() + NumToInsert);
566 size_t NumOverwritten = OldEnd-I;
567 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
568
569 // Replace the overwritten part.
570 std::fill_n(I, NumOverwritten, Elt);
571
572 // Insert the non-overwritten middle part.
573 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
574 return I;
575 }
576
577 template <typename ItTy,
578 typename = typename std::enable_if<std::is_convertible<
579 typename std::iterator_traits<ItTy>::iterator_category,
580 std::input_iterator_tag>::value>::type>
581 iterator insert(iterator I, ItTy From, ItTy To) {
582 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
583 size_t InsertElt = I - this->begin();
584
585 if (I == this->end()) { // Important special case for empty vector.
586 append(From, To);
587 return this->begin()+InsertElt;
588 }
589
590 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 590, __PRETTY_FUNCTION__))
;
591 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~svn373253/include/llvm/ADT/SmallVector.h"
, 591, __PRETTY_FUNCTION__))
;
592
593 size_t NumToInsert = std::distance(From, To);
594
595 // Ensure there is enough space.
596 reserve(this->size() + NumToInsert);
597
598 // Uninvalidate the iterator.
599 I = this->begin()+InsertElt;
600
601 // If there are more elements between the insertion point and the end of the
602 // range than there are being inserted, we can use a simple approach to
603 // insertion. Since we already reserved space, we know that this won't
604 // reallocate the vector.
605 if (size_t(this->end()-I) >= NumToInsert) {
606 T *OldEnd = this->end();
607 append(std::move_iterator<iterator>(this->end() - NumToInsert),
608 std::move_iterator<iterator>(this->end()));
609
610 // Copy the existing elements that get replaced.
611 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
612
613 std::copy(From, To, I);
614 return I;
615 }
616
617 // Otherwise, we're inserting more elements than exist already, and we're
618 // not inserting at the end.
619
620 // Move over the elements that we're about to overwrite.
621 T *OldEnd = this->end();
622 this->set_size(this->size() + NumToInsert);
623 size_t NumOverwritten = OldEnd-I;
624 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
625
626 // Replace the overwritten part.
627 for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
628 *J = *From;
629 ++J; ++From;
630 }
631
632 // Insert the non-overwritten middle part.
633 this->uninitialized_copy(From, To, OldEnd);
634 return I;
635 }
636
637 void insert(iterator I, std::initializer_list<T> IL) {
638 insert(I, IL.begin(), IL.end());
639 }
640
641 template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
642 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
643 this->grow();
644 ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
645 this->set_size(this->size() + 1);
646 return this->back();
647 }
648
649 SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
650
651 SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
652
653 bool operator==(const SmallVectorImpl &RHS) const {
654 if (this->size() != RHS.size()) return false;
655 return std::equal(this->begin(), this->end(), RHS.begin());
656 }
657 bool operator!=(const SmallVectorImpl &RHS) const {
658 return !(*this == RHS);
659 }
660
661 bool operator<(const SmallVectorImpl &RHS) const {
662 return std::lexicographical_compare(this->begin(), this->end(),
663 RHS.begin(), RHS.end());
664 }
665};
666
667template <typename T>
668void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
669 if (this == &RHS) return;
670
671 // We can only avoid copying elements if neither vector is small.
672 if (!this->isSmall() && !RHS.isSmall()) {
673 std::swap(this->BeginX, RHS.BeginX);
674 std::swap(this->Size, RHS.Size);
675 std::swap(this->Capacity, RHS.Capacity);
676 return;
677 }
678 if (RHS.size() > this->capacity())
679 this->grow(RHS.size());
680 if (this->size() > RHS.capacity())
681 RHS.grow(this->size());
682
683 // Swap the shared elements.
684 size_t NumShared = this->size();
685 if (NumShared > RHS.size()) NumShared = RHS.size();
686 for (size_type i = 0; i != NumShared; ++i)
687 std::swap((*this)[i], RHS[i]);
688
689 // Copy over the extra elts.
690 if (this->size() > RHS.size()) {
691 size_t EltDiff = this->size() - RHS.size();
692 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
693 RHS.set_size(RHS.size() + EltDiff);
694 this->destroy_range(this->begin()+NumShared, this->end());
695 this->set_size(NumShared);
696 } else if (RHS.size() > this->size()) {
697 size_t EltDiff = RHS.size() - this->size();
698 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
699 this->set_size(this->size() + EltDiff);
700 this->destroy_range(RHS.begin()+NumShared, RHS.end());
701 RHS.set_size(NumShared);
702 }
703}
704
705template <typename T>
706SmallVectorImpl<T> &SmallVectorImpl<T>::
707 operator=(const SmallVectorImpl<T> &RHS) {
708 // Avoid self-assignment.
709 if (this == &RHS) return *this;
710
711 // If we already have sufficient space, assign the common elements, then
712 // destroy any excess.
713 size_t RHSSize = RHS.size();
714 size_t CurSize = this->size();
715 if (CurSize >= RHSSize) {
716 // Assign common elements.
717 iterator NewEnd;
718 if (RHSSize)
719 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
720 else
721 NewEnd = this->begin();
722
723 // Destroy excess elements.
724 this->destroy_range(NewEnd, this->end());
725
726 // Trim.
727 this->set_size(RHSSize);
728 return *this;
729 }
730
731 // If we have to grow to have enough elements, destroy the current elements.
732 // This allows us to avoid copying them during the grow.
733 // FIXME: don't do this if they're efficiently moveable.
734 if (this->capacity() < RHSSize) {
735 // Destroy current elements.
736 this->destroy_range(this->begin(), this->end());
737 this->set_size(0);
738 CurSize = 0;
739 this->grow(RHSSize);
740 } else if (CurSize) {
741 // Otherwise, use assignment for the already-constructed elements.
742 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
743 }
744
745 // Copy construct the new elements in place.
746 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
747 this->begin()+CurSize);
748
749 // Set end.
750 this->set_size(RHSSize);
751 return *this;
752}
753
754template <typename T>
755SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
756 // Avoid self-assignment.
757 if (this == &RHS) return *this;
758
759 // If the RHS isn't small, clear this vector and then steal its buffer.
760 if (!RHS.isSmall()) {
761 this->destroy_range(this->begin(), this->end());
762 if (!this->isSmall()) free(this->begin());
763 this->BeginX = RHS.BeginX;
764 this->Size = RHS.Size;
765 this->Capacity = RHS.Capacity;
766 RHS.resetToSmall();
767 return *this;
768 }
769
770 // If we already have sufficient space, assign the common elements, then
771 // destroy any excess.
772 size_t RHSSize = RHS.size();
773 size_t CurSize = this->size();
774 if (CurSize >= RHSSize) {
775 // Assign common elements.
776 iterator NewEnd = this->begin();
777 if (RHSSize)
778 NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
779
780 // Destroy excess elements and trim the bounds.
781 this->destroy_range(NewEnd, this->end());
782 this->set_size(RHSSize);
783
784 // Clear the RHS.
785 RHS.clear();
786
787 return *this;
788 }
789
790 // If we have to grow to have enough elements, destroy the current elements.
791 // This allows us to avoid copying them during the grow.
792 // FIXME: this may not actually make any sense if we can efficiently move
793 // elements.
794 if (this->capacity() < RHSSize) {
795 // Destroy current elements.
796 this->destroy_range(this->begin(), this->end());
797 this->set_size(0);
798 CurSize = 0;
799 this->grow(RHSSize);
800 } else if (CurSize) {
801 // Otherwise, use assignment for the already-constructed elements.
802 std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
803 }
804
805 // Move-construct the new elements in place.
806 this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
807 this->begin()+CurSize);
808
809 // Set end.
810 this->set_size(RHSSize);
811
812 RHS.clear();
813 return *this;
814}
815
816/// Storage for the SmallVector elements. This is specialized for the N=0 case
817/// to avoid allocating unnecessary storage.
818template <typename T, unsigned N>
819struct SmallVectorStorage {
820 AlignedCharArrayUnion<T> InlineElts[N];
821};
822
823/// We need the storage to be properly aligned even for small-size of 0 so that
824/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
825/// well-defined.
826template <typename T> struct alignas(alignof(T)) SmallVectorStorage<T, 0> {};
827
828/// This is a 'vector' (really, a variable-sized array), optimized
829/// for the case when the array is small. It contains some number of elements
830/// in-place, which allows it to avoid heap allocation when the actual number of
831/// elements is below that threshold. This allows normal "small" cases to be
832/// fast without losing generality for large inputs.
833///
834/// Note that this does not attempt to be exception safe.
835///
836template <typename T, unsigned N>
837class SmallVector : public SmallVectorImpl<T>, SmallVectorStorage<T, N> {
838public:
839 SmallVector() : SmallVectorImpl<T>(N) {}
840
841 ~SmallVector() {
842 // Destroy the constructed elements in the vector.
843 this->destroy_range(this->begin(), this->end());
844 }
845
846 explicit SmallVector(size_t Size, const T &Value = T())
847 : SmallVectorImpl<T>(N) {
848 this->assign(Size, Value);
849 }
850
851 template <typename ItTy,
852 typename = typename std::enable_if<std::is_convertible<
853 typename std::iterator_traits<ItTy>::iterator_category,
854 std::input_iterator_tag>::value>::type>
855 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
856 this->append(S, E);
857 }
858
859 template <typename RangeTy>
860 explicit SmallVector(const iterator_range<RangeTy> &R)
861 : SmallVectorImpl<T>(N) {
862 this->append(R.begin(), R.end());
863 }
864
865 SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
866 this->assign(IL);
867 }
868
869 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
870 if (!RHS.empty())
871 SmallVectorImpl<T>::operator=(RHS);
872 }
873
874 const SmallVector &operator=(const SmallVector &RHS) {
875 SmallVectorImpl<T>::operator=(RHS);
876 return *this;
877 }
878
879 SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
880 if (!RHS.empty())
881 SmallVectorImpl<T>::operator=(::std::move(RHS));
882 }
883
884 SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
885 if (!RHS.empty())
886 SmallVectorImpl<T>::operator=(::std::move(RHS));
887 }
888
889 const SmallVector &operator=(SmallVector &&RHS) {
890 SmallVectorImpl<T>::operator=(::std::move(RHS));
891 return *this;
892 }
893
894 const SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
895 SmallVectorImpl<T>::operator=(::std::move(RHS));
896 return *this;
897 }
898
899 const SmallVector &operator=(std::initializer_list<T> IL) {
900 this->assign(IL);
901 return *this;
902 }
903};
904
905template <typename T, unsigned N>
906inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
907 return X.capacity_in_bytes();
908}
909
910} // end namespace llvm
911
912namespace std {
913
914 /// Implement std::swap in terms of SmallVector swap.
915 template<typename T>
916 inline void
917 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
918 LHS.swap(RHS);
919 }
920
921 /// Implement std::swap in terms of SmallVector swap.
922 template<typename T, unsigned N>
923 inline void
924 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
925 LHS.swap(RHS);
926 }
927
928} // end namespace std
929
930#endif // LLVM_ADT_SMALLVECTOR_H