Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaInit.cpp
Warning:line 7039, column 16
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaInit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaInit.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaInit.cpp

1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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 semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/AST/ExprOpenMP.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Basic/CharInfo.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Sema/Designator.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/SemaInternal.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/PointerIntPair.h"
28#include "llvm/ADT/SmallString.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Sema Initialization Checking
36//===----------------------------------------------------------------------===//
37
38/// Check whether T is compatible with a wide character type (wchar_t,
39/// char16_t or char32_t).
40static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
41 if (Context.typesAreCompatible(Context.getWideCharType(), T))
42 return true;
43 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
44 return Context.typesAreCompatible(Context.Char16Ty, T) ||
45 Context.typesAreCompatible(Context.Char32Ty, T);
46 }
47 return false;
48}
49
50enum StringInitFailureKind {
51 SIF_None,
52 SIF_NarrowStringIntoWideChar,
53 SIF_WideStringIntoChar,
54 SIF_IncompatWideStringIntoWideChar,
55 SIF_UTF8StringIntoPlainChar,
56 SIF_PlainStringIntoUTF8Char,
57 SIF_Other
58};
59
60/// Check whether the array of type AT can be initialized by the Init
61/// expression by means of string initialization. Returns SIF_None if so,
62/// otherwise returns a StringInitFailureKind that describes why the
63/// initialization would not work.
64static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
65 ASTContext &Context) {
66 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
67 return SIF_Other;
68
69 // See if this is a string literal or @encode.
70 Init = Init->IgnoreParens();
71
72 // Handle @encode, which is a narrow string.
73 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
74 return SIF_None;
75
76 // Otherwise we can only handle string literals.
77 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
78 if (!SL)
79 return SIF_Other;
80
81 const QualType ElemTy =
82 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
83
84 switch (SL->getKind()) {
85 case StringLiteral::UTF8:
86 // char8_t array can be initialized with a UTF-8 string.
87 if (ElemTy->isChar8Type())
88 return SIF_None;
89 LLVM_FALLTHROUGH[[gnu::fallthrough]];
90 case StringLiteral::Ascii:
91 // char array can be initialized with a narrow string.
92 // Only allow char x[] = "foo"; not char x[] = L"foo";
93 if (ElemTy->isCharType())
94 return (SL->getKind() == StringLiteral::UTF8 &&
95 Context.getLangOpts().Char8)
96 ? SIF_UTF8StringIntoPlainChar
97 : SIF_None;
98 if (ElemTy->isChar8Type())
99 return SIF_PlainStringIntoUTF8Char;
100 if (IsWideCharCompatible(ElemTy, Context))
101 return SIF_NarrowStringIntoWideChar;
102 return SIF_Other;
103 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
104 // "An array with element type compatible with a qualified or unqualified
105 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
106 // string literal with the corresponding encoding prefix (L, u, or U,
107 // respectively), optionally enclosed in braces.
108 case StringLiteral::UTF16:
109 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
110 return SIF_None;
111 if (ElemTy->isCharType() || ElemTy->isChar8Type())
112 return SIF_WideStringIntoChar;
113 if (IsWideCharCompatible(ElemTy, Context))
114 return SIF_IncompatWideStringIntoWideChar;
115 return SIF_Other;
116 case StringLiteral::UTF32:
117 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
118 return SIF_None;
119 if (ElemTy->isCharType() || ElemTy->isChar8Type())
120 return SIF_WideStringIntoChar;
121 if (IsWideCharCompatible(ElemTy, Context))
122 return SIF_IncompatWideStringIntoWideChar;
123 return SIF_Other;
124 case StringLiteral::Wide:
125 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
126 return SIF_None;
127 if (ElemTy->isCharType() || ElemTy->isChar8Type())
128 return SIF_WideStringIntoChar;
129 if (IsWideCharCompatible(ElemTy, Context))
130 return SIF_IncompatWideStringIntoWideChar;
131 return SIF_Other;
132 }
133
134 llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?"
, "clang/lib/Sema/SemaInit.cpp", 134)
;
135}
136
137static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
138 ASTContext &Context) {
139 const ArrayType *arrayType = Context.getAsArrayType(declType);
140 if (!arrayType)
141 return SIF_Other;
142 return IsStringInit(init, arrayType, Context);
143}
144
145bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
146 return ::IsStringInit(Init, AT, Context) == SIF_None;
147}
148
149/// Update the type of a string literal, including any surrounding parentheses,
150/// to match the type of the object which it is initializing.
151static void updateStringLiteralType(Expr *E, QualType Ty) {
152 while (true) {
153 E->setType(Ty);
154 E->setValueKind(VK_PRValue);
155 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
156 break;
157 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
158 E = PE->getSubExpr();
159 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
160 assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension
) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension"
, "clang/lib/Sema/SemaInit.cpp", 160, __extension__ __PRETTY_FUNCTION__
))
;
161 E = UO->getSubExpr();
162 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
163 E = GSE->getResultExpr();
164 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
165 E = CE->getChosenSubExpr();
166 } else {
167 llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init"
, "clang/lib/Sema/SemaInit.cpp", 167)
;
168 }
169 }
170}
171
172/// Fix a compound literal initializing an array so it's correctly marked
173/// as an rvalue.
174static void updateGNUCompoundLiteralRValue(Expr *E) {
175 while (true) {
176 E->setValueKind(VK_PRValue);
177 if (isa<CompoundLiteralExpr>(E)) {
178 break;
179 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
180 E = PE->getSubExpr();
181 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
182 assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension
) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension"
, "clang/lib/Sema/SemaInit.cpp", 182, __extension__ __PRETTY_FUNCTION__
))
;
183 E = UO->getSubExpr();
184 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
185 E = GSE->getResultExpr();
186 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
187 E = CE->getChosenSubExpr();
188 } else {
189 llvm_unreachable("unexpected expr in array compound literal init")::llvm::llvm_unreachable_internal("unexpected expr in array compound literal init"
, "clang/lib/Sema/SemaInit.cpp", 189)
;
190 }
191 }
192}
193
194static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
195 Sema &S) {
196 // Get the length of the string as parsed.
197 auto *ConstantArrayTy =
198 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
199 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
200
201 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
202 // C99 6.7.8p14. We have an array of character type with unknown size
203 // being initialized to a string literal.
204 llvm::APInt ConstVal(32, StrLength);
205 // Return a new array type (C99 6.7.8p22).
206 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
207 ConstVal, nullptr,
208 ArrayType::Normal, 0);
209 updateStringLiteralType(Str, DeclT);
210 return;
211 }
212
213 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
214
215 // We have an array of character type with known size. However,
216 // the size may be smaller or larger than the string we are initializing.
217 // FIXME: Avoid truncation for 64-bit length strings.
218 if (S.getLangOpts().CPlusPlus) {
219 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
220 // For Pascal strings it's OK to strip off the terminating null character,
221 // so the example below is valid:
222 //
223 // unsigned char a[2] = "\pa";
224 if (SL->isPascal())
225 StrLength--;
226 }
227
228 // [dcl.init.string]p2
229 if (StrLength > CAT->getSize().getZExtValue())
230 S.Diag(Str->getBeginLoc(),
231 diag::err_initializer_string_for_char_array_too_long)
232 << Str->getSourceRange();
233 } else {
234 // C99 6.7.8p14.
235 if (StrLength-1 > CAT->getSize().getZExtValue())
236 S.Diag(Str->getBeginLoc(),
237 diag::ext_initializer_string_for_char_array_too_long)
238 << Str->getSourceRange();
239 }
240
241 // Set the type to the actual size that we are initializing. If we have
242 // something like:
243 // char x[1] = "foo";
244 // then this will set the string literal's type to char[1].
245 updateStringLiteralType(Str, DeclT);
246}
247
248//===----------------------------------------------------------------------===//
249// Semantic checking for initializer lists.
250//===----------------------------------------------------------------------===//
251
252namespace {
253
254/// Semantic checking for initializer lists.
255///
256/// The InitListChecker class contains a set of routines that each
257/// handle the initialization of a certain kind of entity, e.g.,
258/// arrays, vectors, struct/union types, scalars, etc. The
259/// InitListChecker itself performs a recursive walk of the subobject
260/// structure of the type to be initialized, while stepping through
261/// the initializer list one element at a time. The IList and Index
262/// parameters to each of the Check* routines contain the active
263/// (syntactic) initializer list and the index into that initializer
264/// list that represents the current initializer. Each routine is
265/// responsible for moving that Index forward as it consumes elements.
266///
267/// Each Check* routine also has a StructuredList/StructuredIndex
268/// arguments, which contains the current "structured" (semantic)
269/// initializer list and the index into that initializer list where we
270/// are copying initializers as we map them over to the semantic
271/// list. Once we have completed our recursive walk of the subobject
272/// structure, we will have constructed a full semantic initializer
273/// list.
274///
275/// C99 designators cause changes in the initializer list traversal,
276/// because they make the initialization "jump" into a specific
277/// subobject and then continue the initialization from that
278/// point. CheckDesignatedInitializer() recursively steps into the
279/// designated subobject and manages backing out the recursion to
280/// initialize the subobjects after the one designated.
281///
282/// If an initializer list contains any designators, we build a placeholder
283/// structured list even in 'verify only' mode, so that we can track which
284/// elements need 'empty' initializtion.
285class InitListChecker {
286 Sema &SemaRef;
287 bool hadError = false;
288 bool VerifyOnly; // No diagnostics.
289 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
290 bool InOverloadResolution;
291 InitListExpr *FullyStructuredList = nullptr;
292 NoInitExpr *DummyExpr = nullptr;
293
294 NoInitExpr *getDummyInit() {
295 if (!DummyExpr)
296 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
297 return DummyExpr;
298 }
299
300 void CheckImplicitInitList(const InitializedEntity &Entity,
301 InitListExpr *ParentIList, QualType T,
302 unsigned &Index, InitListExpr *StructuredList,
303 unsigned &StructuredIndex);
304 void CheckExplicitInitList(const InitializedEntity &Entity,
305 InitListExpr *IList, QualType &T,
306 InitListExpr *StructuredList,
307 bool TopLevelObject = false);
308 void CheckListElementTypes(const InitializedEntity &Entity,
309 InitListExpr *IList, QualType &DeclType,
310 bool SubobjectIsDesignatorContext,
311 unsigned &Index,
312 InitListExpr *StructuredList,
313 unsigned &StructuredIndex,
314 bool TopLevelObject = false);
315 void CheckSubElementType(const InitializedEntity &Entity,
316 InitListExpr *IList, QualType ElemType,
317 unsigned &Index,
318 InitListExpr *StructuredList,
319 unsigned &StructuredIndex,
320 bool DirectlyDesignated = false);
321 void CheckComplexType(const InitializedEntity &Entity,
322 InitListExpr *IList, QualType DeclType,
323 unsigned &Index,
324 InitListExpr *StructuredList,
325 unsigned &StructuredIndex);
326 void CheckScalarType(const InitializedEntity &Entity,
327 InitListExpr *IList, QualType DeclType,
328 unsigned &Index,
329 InitListExpr *StructuredList,
330 unsigned &StructuredIndex);
331 void CheckReferenceType(const InitializedEntity &Entity,
332 InitListExpr *IList, QualType DeclType,
333 unsigned &Index,
334 InitListExpr *StructuredList,
335 unsigned &StructuredIndex);
336 void CheckVectorType(const InitializedEntity &Entity,
337 InitListExpr *IList, QualType DeclType, unsigned &Index,
338 InitListExpr *StructuredList,
339 unsigned &StructuredIndex);
340 void CheckStructUnionTypes(const InitializedEntity &Entity,
341 InitListExpr *IList, QualType DeclType,
342 CXXRecordDecl::base_class_range Bases,
343 RecordDecl::field_iterator Field,
344 bool SubobjectIsDesignatorContext, unsigned &Index,
345 InitListExpr *StructuredList,
346 unsigned &StructuredIndex,
347 bool TopLevelObject = false);
348 void CheckArrayType(const InitializedEntity &Entity,
349 InitListExpr *IList, QualType &DeclType,
350 llvm::APSInt elementIndex,
351 bool SubobjectIsDesignatorContext, unsigned &Index,
352 InitListExpr *StructuredList,
353 unsigned &StructuredIndex);
354 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
355 InitListExpr *IList, DesignatedInitExpr *DIE,
356 unsigned DesigIdx,
357 QualType &CurrentObjectType,
358 RecordDecl::field_iterator *NextField,
359 llvm::APSInt *NextElementIndex,
360 unsigned &Index,
361 InitListExpr *StructuredList,
362 unsigned &StructuredIndex,
363 bool FinishSubobjectInit,
364 bool TopLevelObject);
365 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
366 QualType CurrentObjectType,
367 InitListExpr *StructuredList,
368 unsigned StructuredIndex,
369 SourceRange InitRange,
370 bool IsFullyOverwritten = false);
371 void UpdateStructuredListElement(InitListExpr *StructuredList,
372 unsigned &StructuredIndex,
373 Expr *expr);
374 InitListExpr *createInitListExpr(QualType CurrentObjectType,
375 SourceRange InitRange,
376 unsigned ExpectedNumInits);
377 int numArrayElements(QualType DeclType);
378 int numStructUnionElements(QualType DeclType);
379
380 ExprResult PerformEmptyInit(SourceLocation Loc,
381 const InitializedEntity &Entity);
382
383 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
384 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
385 bool FullyOverwritten = true) {
386 // Overriding an initializer via a designator is valid with C99 designated
387 // initializers, but ill-formed with C++20 designated initializers.
388 unsigned DiagID = SemaRef.getLangOpts().CPlusPlus
389 ? diag::ext_initializer_overrides
390 : diag::warn_initializer_overrides;
391
392 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
393 // In overload resolution, we have to strictly enforce the rules, and so
394 // don't allow any overriding of prior initializers. This matters for a
395 // case such as:
396 //
397 // union U { int a, b; };
398 // struct S { int a, b; };
399 // void f(U), f(S);
400 //
401 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
402 // consistency, we disallow all overriding of prior initializers in
403 // overload resolution, not only overriding of union members.
404 hadError = true;
405 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
406 // If we'll be keeping around the old initializer but overwriting part of
407 // the object it initialized, and that object is not trivially
408 // destructible, this can leak. Don't allow that, not even as an
409 // extension.
410 //
411 // FIXME: It might be reasonable to allow this in cases where the part of
412 // the initializer that we're overriding has trivial destruction.
413 DiagID = diag::err_initializer_overrides_destructed;
414 } else if (!OldInit->getSourceRange().isValid()) {
415 // We need to check on source range validity because the previous
416 // initializer does not have to be an explicit initializer. e.g.,
417 //
418 // struct P { int a, b; };
419 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
420 //
421 // There is an overwrite taking place because the first braced initializer
422 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
423 //
424 // Such overwrites are harmless, so we don't diagnose them. (Note that in
425 // C++, this cannot be reached unless we've already seen and diagnosed a
426 // different conformance issue, such as a mixture of designated and
427 // non-designated initializers or a multi-level designator.)
428 return;
429 }
430
431 if (!VerifyOnly) {
432 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
433 << NewInitRange << FullyOverwritten << OldInit->getType();
434 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
435 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
436 << OldInit->getSourceRange();
437 }
438 }
439
440 // Explanation on the "FillWithNoInit" mode:
441 //
442 // Assume we have the following definitions (Case#1):
443 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
444 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
445 //
446 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
447 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
448 //
449 // But if we have (Case#2):
450 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
451 //
452 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
453 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
454 //
455 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
456 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
457 // initializers but with special "NoInitExpr" place holders, which tells the
458 // CodeGen not to generate any initializers for these parts.
459 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
460 const InitializedEntity &ParentEntity,
461 InitListExpr *ILE, bool &RequiresSecondPass,
462 bool FillWithNoInit);
463 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
464 const InitializedEntity &ParentEntity,
465 InitListExpr *ILE, bool &RequiresSecondPass,
466 bool FillWithNoInit = false);
467 void FillInEmptyInitializations(const InitializedEntity &Entity,
468 InitListExpr *ILE, bool &RequiresSecondPass,
469 InitListExpr *OuterILE, unsigned OuterIndex,
470 bool FillWithNoInit = false);
471 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
472 Expr *InitExpr, FieldDecl *Field,
473 bool TopLevelObject);
474 void CheckEmptyInitializable(const InitializedEntity &Entity,
475 SourceLocation Loc);
476
477public:
478 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
479 QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
480 bool InOverloadResolution = false);
481 bool HadError() { return hadError; }
482
483 // Retrieves the fully-structured initializer list used for
484 // semantic analysis and code generation.
485 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
486};
487
488} // end anonymous namespace
489
490ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
491 const InitializedEntity &Entity) {
492 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
493 true);
494 MultiExprArg SubInit;
495 Expr *InitExpr;
496 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
497
498 // C++ [dcl.init.aggr]p7:
499 // If there are fewer initializer-clauses in the list than there are
500 // members in the aggregate, then each member not explicitly initialized
501 // ...
502 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
503 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
504 if (EmptyInitList) {
505 // C++1y / DR1070:
506 // shall be initialized [...] from an empty initializer list.
507 //
508 // We apply the resolution of this DR to C++11 but not C++98, since C++98
509 // does not have useful semantics for initialization from an init list.
510 // We treat this as copy-initialization, because aggregate initialization
511 // always performs copy-initialization on its elements.
512 //
513 // Only do this if we're initializing a class type, to avoid filling in
514 // the initializer list where possible.
515 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
516 InitListExpr(SemaRef.Context, Loc, None, Loc);
517 InitExpr->setType(SemaRef.Context.VoidTy);
518 SubInit = InitExpr;
519 Kind = InitializationKind::CreateCopy(Loc, Loc);
520 } else {
521 // C++03:
522 // shall be value-initialized.
523 }
524
525 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
526 // libstdc++4.6 marks the vector default constructor as explicit in
527 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
528 // stlport does so too. Look for std::__debug for libstdc++, and for
529 // std:: for stlport. This is effectively a compiler-side implementation of
530 // LWG2193.
531 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
532 InitializationSequence::FK_ExplicitConstructor) {
533 OverloadCandidateSet::iterator Best;
534 OverloadingResult O =
535 InitSeq.getFailedCandidateSet()
536 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
537 (void)O;
538 assert(O == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (O == OR_Success && "Inconsistent overload resolution"
) ? void (0) : __assert_fail ("O == OR_Success && \"Inconsistent overload resolution\""
, "clang/lib/Sema/SemaInit.cpp", 538, __extension__ __PRETTY_FUNCTION__
))
;
539 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
540 CXXRecordDecl *R = CtorDecl->getParent();
541
542 if (CtorDecl->getMinRequiredArguments() == 0 &&
543 CtorDecl->isExplicit() && R->getDeclName() &&
544 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
545 bool IsInStd = false;
546 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
547 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
548 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
549 IsInStd = true;
550 }
551
552 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
553 .Cases("basic_string", "deque", "forward_list", true)
554 .Cases("list", "map", "multimap", "multiset", true)
555 .Cases("priority_queue", "queue", "set", "stack", true)
556 .Cases("unordered_map", "unordered_set", "vector", true)
557 .Default(false)) {
558 InitSeq.InitializeFrom(
559 SemaRef, Entity,
560 InitializationKind::CreateValue(Loc, Loc, Loc, true),
561 MultiExprArg(), /*TopLevelOfInitList=*/false,
562 TreatUnavailableAsInvalid);
563 // Emit a warning for this. System header warnings aren't shown
564 // by default, but people working on system headers should see it.
565 if (!VerifyOnly) {
566 SemaRef.Diag(CtorDecl->getLocation(),
567 diag::warn_invalid_initializer_from_system_header);
568 if (Entity.getKind() == InitializedEntity::EK_Member)
569 SemaRef.Diag(Entity.getDecl()->getLocation(),
570 diag::note_used_in_initialization_here);
571 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
572 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
573 }
574 }
575 }
576 }
577 if (!InitSeq) {
578 if (!VerifyOnly) {
579 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
580 if (Entity.getKind() == InitializedEntity::EK_Member)
581 SemaRef.Diag(Entity.getDecl()->getLocation(),
582 diag::note_in_omitted_aggregate_initializer)
583 << /*field*/1 << Entity.getDecl();
584 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
585 bool IsTrailingArrayNewMember =
586 Entity.getParent() &&
587 Entity.getParent()->isVariableLengthArrayNew();
588 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
589 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
590 << Entity.getElementIndex();
591 }
592 }
593 hadError = true;
594 return ExprError();
595 }
596
597 return VerifyOnly ? ExprResult()
598 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
599}
600
601void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
602 SourceLocation Loc) {
603 // If we're building a fully-structured list, we'll check this at the end
604 // once we know which elements are actually initialized. Otherwise, we know
605 // that there are no designators so we can just check now.
606 if (FullyStructuredList)
607 return;
608 PerformEmptyInit(Loc, Entity);
609}
610
611void InitListChecker::FillInEmptyInitForBase(
612 unsigned Init, const CXXBaseSpecifier &Base,
613 const InitializedEntity &ParentEntity, InitListExpr *ILE,
614 bool &RequiresSecondPass, bool FillWithNoInit) {
615 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
616 SemaRef.Context, &Base, false, &ParentEntity);
617
618 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
619 ExprResult BaseInit = FillWithNoInit
620 ? new (SemaRef.Context) NoInitExpr(Base.getType())
621 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
622 if (BaseInit.isInvalid()) {
623 hadError = true;
624 return;
625 }
626
627 if (!VerifyOnly) {
628 assert(Init < ILE->getNumInits() && "should have been expanded")(static_cast <bool> (Init < ILE->getNumInits() &&
"should have been expanded") ? void (0) : __assert_fail ("Init < ILE->getNumInits() && \"should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 628, __extension__ __PRETTY_FUNCTION__
))
;
629 ILE->setInit(Init, BaseInit.getAs<Expr>());
630 }
631 } else if (InitListExpr *InnerILE =
632 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
633 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
634 ILE, Init, FillWithNoInit);
635 } else if (DesignatedInitUpdateExpr *InnerDIUE =
636 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
637 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
638 RequiresSecondPass, ILE, Init,
639 /*FillWithNoInit =*/true);
640 }
641}
642
643void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
644 const InitializedEntity &ParentEntity,
645 InitListExpr *ILE,
646 bool &RequiresSecondPass,
647 bool FillWithNoInit) {
648 SourceLocation Loc = ILE->getEndLoc();
649 unsigned NumInits = ILE->getNumInits();
650 InitializedEntity MemberEntity
651 = InitializedEntity::InitializeMember(Field, &ParentEntity);
652
653 if (Init >= NumInits || !ILE->getInit(Init)) {
654 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
655 if (!RType->getDecl()->isUnion())
656 assert((Init < NumInits || VerifyOnly) &&(static_cast <bool> ((Init < NumInits || VerifyOnly)
&& "This ILE should have been expanded") ? void (0) :
__assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 657, __extension__ __PRETTY_FUNCTION__
))
657 "This ILE should have been expanded")(static_cast <bool> ((Init < NumInits || VerifyOnly)
&& "This ILE should have been expanded") ? void (0) :
__assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 657, __extension__ __PRETTY_FUNCTION__
))
;
658
659 if (FillWithNoInit) {
660 assert(!VerifyOnly && "should not fill with no-init in verify-only mode")(static_cast <bool> (!VerifyOnly && "should not fill with no-init in verify-only mode"
) ? void (0) : __assert_fail ("!VerifyOnly && \"should not fill with no-init in verify-only mode\""
, "clang/lib/Sema/SemaInit.cpp", 660, __extension__ __PRETTY_FUNCTION__
))
;
661 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
662 if (Init < NumInits)
663 ILE->setInit(Init, Filler);
664 else
665 ILE->updateInit(SemaRef.Context, Init, Filler);
666 return;
667 }
668 // C++1y [dcl.init.aggr]p7:
669 // If there are fewer initializer-clauses in the list than there are
670 // members in the aggregate, then each member not explicitly initialized
671 // shall be initialized from its brace-or-equal-initializer [...]
672 if (Field->hasInClassInitializer()) {
673 if (VerifyOnly)
674 return;
675
676 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
677 if (DIE.isInvalid()) {
678 hadError = true;
679 return;
680 }
681 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
682 if (Init < NumInits)
683 ILE->setInit(Init, DIE.get());
684 else {
685 ILE->updateInit(SemaRef.Context, Init, DIE.get());
686 RequiresSecondPass = true;
687 }
688 return;
689 }
690
691 if (Field->getType()->isReferenceType()) {
692 if (!VerifyOnly) {
693 // C++ [dcl.init.aggr]p9:
694 // If an incomplete or empty initializer-list leaves a
695 // member of reference type uninitialized, the program is
696 // ill-formed.
697 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
698 << Field->getType()
699 << ILE->getSyntacticForm()->getSourceRange();
700 SemaRef.Diag(Field->getLocation(),
701 diag::note_uninit_reference_member);
702 }
703 hadError = true;
704 return;
705 }
706
707 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
708 if (MemberInit.isInvalid()) {
709 hadError = true;
710 return;
711 }
712
713 if (hadError || VerifyOnly) {
714 // Do nothing
715 } else if (Init < NumInits) {
716 ILE->setInit(Init, MemberInit.getAs<Expr>());
717 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
718 // Empty initialization requires a constructor call, so
719 // extend the initializer list to include the constructor
720 // call and make a note that we'll need to take another pass
721 // through the initializer list.
722 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
723 RequiresSecondPass = true;
724 }
725 } else if (InitListExpr *InnerILE
726 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
727 FillInEmptyInitializations(MemberEntity, InnerILE,
728 RequiresSecondPass, ILE, Init, FillWithNoInit);
729 } else if (DesignatedInitUpdateExpr *InnerDIUE =
730 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
731 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
732 RequiresSecondPass, ILE, Init,
733 /*FillWithNoInit =*/true);
734 }
735}
736
737/// Recursively replaces NULL values within the given initializer list
738/// with expressions that perform value-initialization of the
739/// appropriate type, and finish off the InitListExpr formation.
740void
741InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
742 InitListExpr *ILE,
743 bool &RequiresSecondPass,
744 InitListExpr *OuterILE,
745 unsigned OuterIndex,
746 bool FillWithNoInit) {
747 assert((ILE->getType() != SemaRef.Context.VoidTy) &&(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "clang/lib/Sema/SemaInit.cpp", 748, __extension__ __PRETTY_FUNCTION__
))
748 "Should not have void type")(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "clang/lib/Sema/SemaInit.cpp", 748, __extension__ __PRETTY_FUNCTION__
))
;
749
750 // We don't need to do any checks when just filling NoInitExprs; that can't
751 // fail.
752 if (FillWithNoInit && VerifyOnly)
753 return;
754
755 // If this is a nested initializer list, we might have changed its contents
756 // (and therefore some of its properties, such as instantiation-dependence)
757 // while filling it in. Inform the outer initializer list so that its state
758 // can be updated to match.
759 // FIXME: We should fully build the inner initializers before constructing
760 // the outer InitListExpr instead of mutating AST nodes after they have
761 // been used as subexpressions of other nodes.
762 struct UpdateOuterILEWithUpdatedInit {
763 InitListExpr *Outer;
764 unsigned OuterIndex;
765 ~UpdateOuterILEWithUpdatedInit() {
766 if (Outer)
767 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
768 }
769 } UpdateOuterRAII = {OuterILE, OuterIndex};
770
771 // A transparent ILE is not performing aggregate initialization and should
772 // not be filled in.
773 if (ILE->isTransparent())
774 return;
775
776 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
777 const RecordDecl *RDecl = RType->getDecl();
778 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
779 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
780 Entity, ILE, RequiresSecondPass, FillWithNoInit);
781 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
782 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
783 for (auto *Field : RDecl->fields()) {
784 if (Field->hasInClassInitializer()) {
785 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
786 FillWithNoInit);
787 break;
788 }
789 }
790 } else {
791 // The fields beyond ILE->getNumInits() are default initialized, so in
792 // order to leave them uninitialized, the ILE is expanded and the extra
793 // fields are then filled with NoInitExpr.
794 unsigned NumElems = numStructUnionElements(ILE->getType());
795 if (RDecl->hasFlexibleArrayMember())
796 ++NumElems;
797 if (!VerifyOnly && ILE->getNumInits() < NumElems)
798 ILE->resizeInits(SemaRef.Context, NumElems);
799
800 unsigned Init = 0;
801
802 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
803 for (auto &Base : CXXRD->bases()) {
804 if (hadError)
805 return;
806
807 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
808 FillWithNoInit);
809 ++Init;
810 }
811 }
812
813 for (auto *Field : RDecl->fields()) {
814 if (Field->isUnnamedBitfield())
815 continue;
816
817 if (hadError)
818 return;
819
820 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
821 FillWithNoInit);
822 if (hadError)
823 return;
824
825 ++Init;
826
827 // Only look at the first initialization of a union.
828 if (RDecl->isUnion())
829 break;
830 }
831 }
832
833 return;
834 }
835
836 QualType ElementType;
837
838 InitializedEntity ElementEntity = Entity;
839 unsigned NumInits = ILE->getNumInits();
840 unsigned NumElements = NumInits;
841 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
842 ElementType = AType->getElementType();
843 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
844 NumElements = CAType->getSize().getZExtValue();
845 // For an array new with an unknown bound, ask for one additional element
846 // in order to populate the array filler.
847 if (Entity.isVariableLengthArrayNew())
848 ++NumElements;
849 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
850 0, Entity);
851 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
852 ElementType = VType->getElementType();
853 NumElements = VType->getNumElements();
854 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
855 0, Entity);
856 } else
857 ElementType = ILE->getType();
858
859 bool SkipEmptyInitChecks = false;
860 for (unsigned Init = 0; Init != NumElements; ++Init) {
861 if (hadError)
862 return;
863
864 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
865 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
866 ElementEntity.setElementIndex(Init);
867
868 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
869 return;
870
871 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
872 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
873 ILE->setInit(Init, ILE->getArrayFiller());
874 else if (!InitExpr && !ILE->hasArrayFiller()) {
875 // In VerifyOnly mode, there's no point performing empty initialization
876 // more than once.
877 if (SkipEmptyInitChecks)
878 continue;
879
880 Expr *Filler = nullptr;
881
882 if (FillWithNoInit)
883 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
884 else {
885 ExprResult ElementInit =
886 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
887 if (ElementInit.isInvalid()) {
888 hadError = true;
889 return;
890 }
891
892 Filler = ElementInit.getAs<Expr>();
893 }
894
895 if (hadError) {
896 // Do nothing
897 } else if (VerifyOnly) {
898 SkipEmptyInitChecks = true;
899 } else if (Init < NumInits) {
900 // For arrays, just set the expression used for value-initialization
901 // of the "holes" in the array.
902 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
903 ILE->setArrayFiller(Filler);
904 else
905 ILE->setInit(Init, Filler);
906 } else {
907 // For arrays, just set the expression used for value-initialization
908 // of the rest of elements and exit.
909 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
910 ILE->setArrayFiller(Filler);
911 return;
912 }
913
914 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
915 // Empty initialization requires a constructor call, so
916 // extend the initializer list to include the constructor
917 // call and make a note that we'll need to take another pass
918 // through the initializer list.
919 ILE->updateInit(SemaRef.Context, Init, Filler);
920 RequiresSecondPass = true;
921 }
922 }
923 } else if (InitListExpr *InnerILE
924 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
925 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
926 ILE, Init, FillWithNoInit);
927 } else if (DesignatedInitUpdateExpr *InnerDIUE =
928 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
929 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
930 RequiresSecondPass, ILE, Init,
931 /*FillWithNoInit =*/true);
932 }
933 }
934}
935
936static bool hasAnyDesignatedInits(const InitListExpr *IL) {
937 for (const Stmt *Init : *IL)
938 if (Init && isa<DesignatedInitExpr>(Init))
939 return true;
940 return false;
941}
942
943InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
944 InitListExpr *IL, QualType &T, bool VerifyOnly,
945 bool TreatUnavailableAsInvalid,
946 bool InOverloadResolution)
947 : SemaRef(S), VerifyOnly(VerifyOnly),
948 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
949 InOverloadResolution(InOverloadResolution) {
950 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
951 FullyStructuredList =
952 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
953
954 // FIXME: Check that IL isn't already the semantic form of some other
955 // InitListExpr. If it is, we'd create a broken AST.
956 if (!VerifyOnly)
957 FullyStructuredList->setSyntacticForm(IL);
958 }
959
960 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
961 /*TopLevelObject=*/true);
962
963 if (!hadError && FullyStructuredList) {
964 bool RequiresSecondPass = false;
965 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
966 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
967 if (RequiresSecondPass && !hadError)
968 FillInEmptyInitializations(Entity, FullyStructuredList,
969 RequiresSecondPass, nullptr, 0);
970 }
971 if (hadError && FullyStructuredList)
972 FullyStructuredList->markError();
973}
974
975int InitListChecker::numArrayElements(QualType DeclType) {
976 // FIXME: use a proper constant
977 int maxElements = 0x7FFFFFFF;
978 if (const ConstantArrayType *CAT =
979 SemaRef.Context.getAsConstantArrayType(DeclType)) {
980 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
981 }
982 return maxElements;
983}
984
985int InitListChecker::numStructUnionElements(QualType DeclType) {
986 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
987 int InitializableMembers = 0;
988 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
989 InitializableMembers += CXXRD->getNumBases();
990 for (const auto *Field : structDecl->fields())
991 if (!Field->isUnnamedBitfield())
992 ++InitializableMembers;
993
994 if (structDecl->isUnion())
995 return std::min(InitializableMembers, 1);
996 return InitializableMembers - structDecl->hasFlexibleArrayMember();
997}
998
999/// Determine whether Entity is an entity for which it is idiomatic to elide
1000/// the braces in aggregate initialization.
1001static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1002 // Recursive initialization of the one and only field within an aggregate
1003 // class is considered idiomatic. This case arises in particular for
1004 // initialization of std::array, where the C++ standard suggests the idiom of
1005 //
1006 // std::array<T, N> arr = {1, 2, 3};
1007 //
1008 // (where std::array is an aggregate struct containing a single array field.
1009
1010 if (!Entity.getParent())
1011 return false;
1012
1013 // Allows elide brace initialization for aggregates with empty base.
1014 if (Entity.getKind() == InitializedEntity::EK_Base) {
1015 auto *ParentRD =
1016 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1017 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1018 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1019 }
1020
1021 // Allow brace elision if the only subobject is a field.
1022 if (Entity.getKind() == InitializedEntity::EK_Member) {
1023 auto *ParentRD =
1024 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1025 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1026 if (CXXRD->getNumBases()) {
1027 return false;
1028 }
1029 }
1030 auto FieldIt = ParentRD->field_begin();
1031 assert(FieldIt != ParentRD->field_end() &&(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "clang/lib/Sema/SemaInit.cpp", 1032, __extension__ __PRETTY_FUNCTION__
))
1032 "no fields but have initializer for member?")(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "clang/lib/Sema/SemaInit.cpp", 1032, __extension__ __PRETTY_FUNCTION__
))
;
1033 return ++FieldIt == ParentRD->field_end();
1034 }
1035
1036 return false;
1037}
1038
1039/// Check whether the range of the initializer \p ParentIList from element
1040/// \p Index onwards can be used to initialize an object of type \p T. Update
1041/// \p Index to indicate how many elements of the list were consumed.
1042///
1043/// This also fills in \p StructuredList, from element \p StructuredIndex
1044/// onwards, with the fully-braced, desugared form of the initialization.
1045void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1046 InitListExpr *ParentIList,
1047 QualType T, unsigned &Index,
1048 InitListExpr *StructuredList,
1049 unsigned &StructuredIndex) {
1050 int maxElements = 0;
1051
1052 if (T->isArrayType())
1053 maxElements = numArrayElements(T);
1054 else if (T->isRecordType())
1055 maxElements = numStructUnionElements(T);
1056 else if (T->isVectorType())
1057 maxElements = T->castAs<VectorType>()->getNumElements();
1058 else
1059 llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type"
, "clang/lib/Sema/SemaInit.cpp", 1059)
;
1060
1061 if (maxElements == 0) {
1062 if (!VerifyOnly)
1063 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1064 diag::err_implicit_empty_initializer);
1065 ++Index;
1066 hadError = true;
1067 return;
1068 }
1069
1070 // Build a structured initializer list corresponding to this subobject.
1071 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1072 ParentIList, Index, T, StructuredList, StructuredIndex,
1073 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1074 ParentIList->getSourceRange().getEnd()));
1075 unsigned StructuredSubobjectInitIndex = 0;
1076
1077 // Check the element types and build the structural subobject.
1078 unsigned StartIndex = Index;
1079 CheckListElementTypes(Entity, ParentIList, T,
1080 /*SubobjectIsDesignatorContext=*/false, Index,
1081 StructuredSubobjectInitList,
1082 StructuredSubobjectInitIndex);
1083
1084 if (StructuredSubobjectInitList) {
1085 StructuredSubobjectInitList->setType(T);
1086
1087 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1088 // Update the structured sub-object initializer so that it's ending
1089 // range corresponds with the end of the last initializer it used.
1090 if (EndIndex < ParentIList->getNumInits() &&
1091 ParentIList->getInit(EndIndex)) {
1092 SourceLocation EndLoc
1093 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1094 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1095 }
1096
1097 // Complain about missing braces.
1098 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1099 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1100 !isIdiomaticBraceElisionEntity(Entity)) {
1101 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1102 diag::warn_missing_braces)
1103 << StructuredSubobjectInitList->getSourceRange()
1104 << FixItHint::CreateInsertion(
1105 StructuredSubobjectInitList->getBeginLoc(), "{")
1106 << FixItHint::CreateInsertion(
1107 SemaRef.getLocForEndOfToken(
1108 StructuredSubobjectInitList->getEndLoc()),
1109 "}");
1110 }
1111
1112 // Warn if this type won't be an aggregate in future versions of C++.
1113 auto *CXXRD = T->getAsCXXRecordDecl();
1114 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1115 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1116 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1117 << StructuredSubobjectInitList->getSourceRange() << T;
1118 }
1119 }
1120}
1121
1122/// Warn that \p Entity was of scalar type and was initialized by a
1123/// single-element braced initializer list.
1124static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1125 SourceRange Braces) {
1126 // Don't warn during template instantiation. If the initialization was
1127 // non-dependent, we warned during the initial parse; otherwise, the
1128 // type might not be scalar in some uses of the template.
1129 if (S.inTemplateInstantiation())
1130 return;
1131
1132 unsigned DiagID = 0;
1133
1134 switch (Entity.getKind()) {
1135 case InitializedEntity::EK_VectorElement:
1136 case InitializedEntity::EK_ComplexElement:
1137 case InitializedEntity::EK_ArrayElement:
1138 case InitializedEntity::EK_Parameter:
1139 case InitializedEntity::EK_Parameter_CF_Audited:
1140 case InitializedEntity::EK_TemplateParameter:
1141 case InitializedEntity::EK_Result:
1142 // Extra braces here are suspicious.
1143 DiagID = diag::warn_braces_around_init;
1144 break;
1145
1146 case InitializedEntity::EK_Member:
1147 // Warn on aggregate initialization but not on ctor init list or
1148 // default member initializer.
1149 if (Entity.getParent())
1150 DiagID = diag::warn_braces_around_init;
1151 break;
1152
1153 case InitializedEntity::EK_Variable:
1154 case InitializedEntity::EK_LambdaCapture:
1155 // No warning, might be direct-list-initialization.
1156 // FIXME: Should we warn for copy-list-initialization in these cases?
1157 break;
1158
1159 case InitializedEntity::EK_New:
1160 case InitializedEntity::EK_Temporary:
1161 case InitializedEntity::EK_CompoundLiteralInit:
1162 // No warning, braces are part of the syntax of the underlying construct.
1163 break;
1164
1165 case InitializedEntity::EK_RelatedResult:
1166 // No warning, we already warned when initializing the result.
1167 break;
1168
1169 case InitializedEntity::EK_Exception:
1170 case InitializedEntity::EK_Base:
1171 case InitializedEntity::EK_Delegating:
1172 case InitializedEntity::EK_BlockElement:
1173 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1174 case InitializedEntity::EK_Binding:
1175 case InitializedEntity::EK_StmtExprResult:
1176 llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init"
, "clang/lib/Sema/SemaInit.cpp", 1176)
;
1177 }
1178
1179 if (DiagID) {
1180 S.Diag(Braces.getBegin(), DiagID)
1181 << Entity.getType()->isSizelessBuiltinType() << Braces
1182 << FixItHint::CreateRemoval(Braces.getBegin())
1183 << FixItHint::CreateRemoval(Braces.getEnd());
1184 }
1185}
1186
1187/// Check whether the initializer \p IList (that was written with explicit
1188/// braces) can be used to initialize an object of type \p T.
1189///
1190/// This also fills in \p StructuredList with the fully-braced, desugared
1191/// form of the initialization.
1192void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1193 InitListExpr *IList, QualType &T,
1194 InitListExpr *StructuredList,
1195 bool TopLevelObject) {
1196 unsigned Index = 0, StructuredIndex = 0;
1197 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1198 Index, StructuredList, StructuredIndex, TopLevelObject);
1199 if (StructuredList) {
1200 QualType ExprTy = T;
1201 if (!ExprTy->isArrayType())
1202 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1203 if (!VerifyOnly)
1204 IList->setType(ExprTy);
1205 StructuredList->setType(ExprTy);
1206 }
1207 if (hadError)
1208 return;
1209
1210 // Don't complain for incomplete types, since we'll get an error elsewhere.
1211 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1212 // We have leftover initializers
1213 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1214 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1215 hadError = ExtraInitsIsError;
1216 if (VerifyOnly) {
1217 return;
1218 } else if (StructuredIndex == 1 &&
1219 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1220 SIF_None) {
1221 unsigned DK =
1222 ExtraInitsIsError
1223 ? diag::err_excess_initializers_in_char_array_initializer
1224 : diag::ext_excess_initializers_in_char_array_initializer;
1225 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1226 << IList->getInit(Index)->getSourceRange();
1227 } else if (T->isSizelessBuiltinType()) {
1228 unsigned DK = ExtraInitsIsError
1229 ? diag::err_excess_initializers_for_sizeless_type
1230 : diag::ext_excess_initializers_for_sizeless_type;
1231 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1232 << T << IList->getInit(Index)->getSourceRange();
1233 } else {
1234 int initKind = T->isArrayType() ? 0 :
1235 T->isVectorType() ? 1 :
1236 T->isScalarType() ? 2 :
1237 T->isUnionType() ? 3 :
1238 4;
1239
1240 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1241 : diag::ext_excess_initializers;
1242 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1243 << initKind << IList->getInit(Index)->getSourceRange();
1244 }
1245 }
1246
1247 if (!VerifyOnly) {
1248 if (T->isScalarType() && IList->getNumInits() == 1 &&
1249 !isa<InitListExpr>(IList->getInit(0)))
1250 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1251
1252 // Warn if this is a class type that won't be an aggregate in future
1253 // versions of C++.
1254 auto *CXXRD = T->getAsCXXRecordDecl();
1255 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1256 // Don't warn if there's an equivalent default constructor that would be
1257 // used instead.
1258 bool HasEquivCtor = false;
1259 if (IList->getNumInits() == 0) {
1260 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1261 HasEquivCtor = CD && !CD->isDeleted();
1262 }
1263
1264 if (!HasEquivCtor) {
1265 SemaRef.Diag(IList->getBeginLoc(),
1266 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1267 << IList->getSourceRange() << T;
1268 }
1269 }
1270 }
1271}
1272
1273void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1274 InitListExpr *IList,
1275 QualType &DeclType,
1276 bool SubobjectIsDesignatorContext,
1277 unsigned &Index,
1278 InitListExpr *StructuredList,
1279 unsigned &StructuredIndex,
1280 bool TopLevelObject) {
1281 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1282 // Explicitly braced initializer for complex type can be real+imaginary
1283 // parts.
1284 CheckComplexType(Entity, IList, DeclType, Index,
1285 StructuredList, StructuredIndex);
1286 } else if (DeclType->isScalarType()) {
1287 CheckScalarType(Entity, IList, DeclType, Index,
1288 StructuredList, StructuredIndex);
1289 } else if (DeclType->isVectorType()) {
1290 CheckVectorType(Entity, IList, DeclType, Index,
1291 StructuredList, StructuredIndex);
1292 } else if (DeclType->isRecordType()) {
1293 assert(DeclType->isAggregateType() &&(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "clang/lib/Sema/SemaInit.cpp", 1294, __extension__ __PRETTY_FUNCTION__
))
1294 "non-aggregate records should be handed in CheckSubElementType")(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "clang/lib/Sema/SemaInit.cpp", 1294, __extension__ __PRETTY_FUNCTION__
))
;
1295 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
1296 auto Bases =
1297 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1298 CXXRecordDecl::base_class_iterator());
1299 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1300 Bases = CXXRD->bases();
1301 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1302 SubobjectIsDesignatorContext, Index, StructuredList,
1303 StructuredIndex, TopLevelObject);
1304 } else if (DeclType->isArrayType()) {
1305 llvm::APSInt Zero(
1306 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1307 false);
1308 CheckArrayType(Entity, IList, DeclType, Zero,
1309 SubobjectIsDesignatorContext, Index,
1310 StructuredList, StructuredIndex);
1311 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1312 // This type is invalid, issue a diagnostic.
1313 ++Index;
1314 if (!VerifyOnly)
1315 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1316 << DeclType;
1317 hadError = true;
1318 } else if (DeclType->isReferenceType()) {
1319 CheckReferenceType(Entity, IList, DeclType, Index,
1320 StructuredList, StructuredIndex);
1321 } else if (DeclType->isObjCObjectType()) {
1322 if (!VerifyOnly)
1323 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1324 hadError = true;
1325 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1326 DeclType->isSizelessBuiltinType()) {
1327 // Checks for scalar type are sufficient for these types too.
1328 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1329 StructuredIndex);
1330 } else {
1331 if (!VerifyOnly)
1332 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1333 << DeclType;
1334 hadError = true;
1335 }
1336}
1337
1338void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1339 InitListExpr *IList,
1340 QualType ElemType,
1341 unsigned &Index,
1342 InitListExpr *StructuredList,
1343 unsigned &StructuredIndex,
1344 bool DirectlyDesignated) {
1345 Expr *expr = IList->getInit(Index);
1346
1347 if (ElemType->isReferenceType())
1348 return CheckReferenceType(Entity, IList, ElemType, Index,
1349 StructuredList, StructuredIndex);
1350
1351 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1352 if (SubInitList->getNumInits() == 1 &&
1353 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1354 SIF_None) {
1355 // FIXME: It would be more faithful and no less correct to include an
1356 // InitListExpr in the semantic form of the initializer list in this case.
1357 expr = SubInitList->getInit(0);
1358 }
1359 // Nested aggregate initialization and C++ initialization are handled later.
1360 } else if (isa<ImplicitValueInitExpr>(expr)) {
1361 // This happens during template instantiation when we see an InitListExpr
1362 // that we've already checked once.
1363 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "clang/lib/Sema/SemaInit.cpp", 1364, __extension__ __PRETTY_FUNCTION__
))
1364 "found implicit initialization for the wrong type")(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "clang/lib/Sema/SemaInit.cpp", 1364, __extension__ __PRETTY_FUNCTION__
))
;
1365 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1366 ++Index;
1367 return;
1368 }
1369
1370 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1371 // C++ [dcl.init.aggr]p2:
1372 // Each member is copy-initialized from the corresponding
1373 // initializer-clause.
1374
1375 // FIXME: Better EqualLoc?
1376 InitializationKind Kind =
1377 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1378
1379 // Vector elements can be initialized from other vectors in which case
1380 // we need initialization entity with a type of a vector (and not a vector
1381 // element!) initializing multiple vector elements.
1382 auto TmpEntity =
1383 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1384 ? InitializedEntity::InitializeTemporary(ElemType)
1385 : Entity;
1386
1387 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1388 /*TopLevelOfInitList*/ true);
1389
1390 // C++14 [dcl.init.aggr]p13:
1391 // If the assignment-expression can initialize a member, the member is
1392 // initialized. Otherwise [...] brace elision is assumed
1393 //
1394 // Brace elision is never performed if the element is not an
1395 // assignment-expression.
1396 if (Seq || isa<InitListExpr>(expr)) {
1397 if (!VerifyOnly) {
1398 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1399 if (Result.isInvalid())
1400 hadError = true;
1401
1402 UpdateStructuredListElement(StructuredList, StructuredIndex,
1403 Result.getAs<Expr>());
1404 } else if (!Seq) {
1405 hadError = true;
1406 } else if (StructuredList) {
1407 UpdateStructuredListElement(StructuredList, StructuredIndex,
1408 getDummyInit());
1409 }
1410 ++Index;
1411 return;
1412 }
1413
1414 // Fall through for subaggregate initialization
1415 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1416 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1417 return CheckScalarType(Entity, IList, ElemType, Index,
1418 StructuredList, StructuredIndex);
1419 } else if (const ArrayType *arrayType =
1420 SemaRef.Context.getAsArrayType(ElemType)) {
1421 // arrayType can be incomplete if we're initializing a flexible
1422 // array member. There's nothing we can do with the completed
1423 // type here, though.
1424
1425 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1426 // FIXME: Should we do this checking in verify-only mode?
1427 if (!VerifyOnly)
1428 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1429 if (StructuredList)
1430 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1431 ++Index;
1432 return;
1433 }
1434
1435 // Fall through for subaggregate initialization.
1436
1437 } else {
1438 assert((ElemType->isRecordType() || ElemType->isVectorType() ||(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 1439, __extension__ __PRETTY_FUNCTION__
))
1439 ElemType->isOpenCLSpecificType()) && "Unexpected type")(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 1439, __extension__ __PRETTY_FUNCTION__
))
;
1440
1441 // C99 6.7.8p13:
1442 //
1443 // The initializer for a structure or union object that has
1444 // automatic storage duration shall be either an initializer
1445 // list as described below, or a single expression that has
1446 // compatible structure or union type. In the latter case, the
1447 // initial value of the object, including unnamed members, is
1448 // that of the expression.
1449 ExprResult ExprRes = expr;
1450 if (SemaRef.CheckSingleAssignmentConstraints(
1451 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1452 if (ExprRes.isInvalid())
1453 hadError = true;
1454 else {
1455 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1456 if (ExprRes.isInvalid())
1457 hadError = true;
1458 }
1459 UpdateStructuredListElement(StructuredList, StructuredIndex,
1460 ExprRes.getAs<Expr>());
1461 ++Index;
1462 return;
1463 }
1464 ExprRes.get();
1465 // Fall through for subaggregate initialization
1466 }
1467
1468 // C++ [dcl.init.aggr]p12:
1469 //
1470 // [...] Otherwise, if the member is itself a non-empty
1471 // subaggregate, brace elision is assumed and the initializer is
1472 // considered for the initialization of the first member of
1473 // the subaggregate.
1474 // OpenCL vector initializer is handled elsewhere.
1475 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1476 ElemType->isAggregateType()) {
1477 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1478 StructuredIndex);
1479 ++StructuredIndex;
1480
1481 // In C++20, brace elision is not permitted for a designated initializer.
1482 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1483 if (InOverloadResolution)
1484 hadError = true;
1485 if (!VerifyOnly) {
1486 SemaRef.Diag(expr->getBeginLoc(),
1487 diag::ext_designated_init_brace_elision)
1488 << expr->getSourceRange()
1489 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1490 << FixItHint::CreateInsertion(
1491 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1492 }
1493 }
1494 } else {
1495 if (!VerifyOnly) {
1496 // We cannot initialize this element, so let PerformCopyInitialization
1497 // produce the appropriate diagnostic. We already checked that this
1498 // initialization will fail.
1499 ExprResult Copy =
1500 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1501 /*TopLevelOfInitList=*/true);
1502 (void)Copy;
1503 assert(Copy.isInvalid() &&(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail"
) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\""
, "clang/lib/Sema/SemaInit.cpp", 1504, __extension__ __PRETTY_FUNCTION__
))
1504 "expected non-aggregate initialization to fail")(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail"
) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\""
, "clang/lib/Sema/SemaInit.cpp", 1504, __extension__ __PRETTY_FUNCTION__
))
;
1505 }
1506 hadError = true;
1507 ++Index;
1508 ++StructuredIndex;
1509 }
1510}
1511
1512void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1513 InitListExpr *IList, QualType DeclType,
1514 unsigned &Index,
1515 InitListExpr *StructuredList,
1516 unsigned &StructuredIndex) {
1517 assert(Index == 0 && "Index in explicit init list must be zero")(static_cast <bool> (Index == 0 && "Index in explicit init list must be zero"
) ? void (0) : __assert_fail ("Index == 0 && \"Index in explicit init list must be zero\""
, "clang/lib/Sema/SemaInit.cpp", 1517, __extension__ __PRETTY_FUNCTION__
))
;
1518
1519 // As an extension, clang supports complex initializers, which initialize
1520 // a complex number component-wise. When an explicit initializer list for
1521 // a complex number contains two two initializers, this extension kicks in:
1522 // it exepcts the initializer list to contain two elements convertible to
1523 // the element type of the complex type. The first element initializes
1524 // the real part, and the second element intitializes the imaginary part.
1525
1526 if (IList->getNumInits() != 2)
1527 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1528 StructuredIndex);
1529
1530 // This is an extension in C. (The builtin _Complex type does not exist
1531 // in the C++ standard.)
1532 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1533 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1534 << IList->getSourceRange();
1535
1536 // Initialize the complex number.
1537 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1538 InitializedEntity ElementEntity =
1539 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1540
1541 for (unsigned i = 0; i < 2; ++i) {
1542 ElementEntity.setElementIndex(Index);
1543 CheckSubElementType(ElementEntity, IList, elementType, Index,
1544 StructuredList, StructuredIndex);
1545 }
1546}
1547
1548void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1549 InitListExpr *IList, QualType DeclType,
1550 unsigned &Index,
1551 InitListExpr *StructuredList,
1552 unsigned &StructuredIndex) {
1553 if (Index >= IList->getNumInits()) {
1554 if (!VerifyOnly) {
1555 if (DeclType->isSizelessBuiltinType())
1556 SemaRef.Diag(IList->getBeginLoc(),
1557 SemaRef.getLangOpts().CPlusPlus11
1558 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1559 : diag::err_empty_sizeless_initializer)
1560 << DeclType << IList->getSourceRange();
1561 else
1562 SemaRef.Diag(IList->getBeginLoc(),
1563 SemaRef.getLangOpts().CPlusPlus11
1564 ? diag::warn_cxx98_compat_empty_scalar_initializer
1565 : diag::err_empty_scalar_initializer)
1566 << IList->getSourceRange();
1567 }
1568 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1569 ++Index;
1570 ++StructuredIndex;
1571 return;
1572 }
1573
1574 Expr *expr = IList->getInit(Index);
1575 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1576 // FIXME: This is invalid, and accepting it causes overload resolution
1577 // to pick the wrong overload in some corner cases.
1578 if (!VerifyOnly)
1579 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1580 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1581
1582 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1583 StructuredIndex);
1584 return;
1585 } else if (isa<DesignatedInitExpr>(expr)) {
1586 if (!VerifyOnly)
1587 SemaRef.Diag(expr->getBeginLoc(),
1588 diag::err_designator_for_scalar_or_sizeless_init)
1589 << DeclType->isSizelessBuiltinType() << DeclType
1590 << expr->getSourceRange();
1591 hadError = true;
1592 ++Index;
1593 ++StructuredIndex;
1594 return;
1595 }
1596
1597 ExprResult Result;
1598 if (VerifyOnly) {
1599 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1600 Result = getDummyInit();
1601 else
1602 Result = ExprError();
1603 } else {
1604 Result =
1605 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1606 /*TopLevelOfInitList=*/true);
1607 }
1608
1609 Expr *ResultExpr = nullptr;
1610
1611 if (Result.isInvalid())
1612 hadError = true; // types weren't compatible.
1613 else {
1614 ResultExpr = Result.getAs<Expr>();
1615
1616 if (ResultExpr != expr && !VerifyOnly) {
1617 // The type was promoted, update initializer list.
1618 // FIXME: Why are we updating the syntactic init list?
1619 IList->setInit(Index, ResultExpr);
1620 }
1621 }
1622 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1623 ++Index;
1624}
1625
1626void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1627 InitListExpr *IList, QualType DeclType,
1628 unsigned &Index,
1629 InitListExpr *StructuredList,
1630 unsigned &StructuredIndex) {
1631 if (Index >= IList->getNumInits()) {
1632 // FIXME: It would be wonderful if we could point at the actual member. In
1633 // general, it would be useful to pass location information down the stack,
1634 // so that we know the location (or decl) of the "current object" being
1635 // initialized.
1636 if (!VerifyOnly)
1637 SemaRef.Diag(IList->getBeginLoc(),
1638 diag::err_init_reference_member_uninitialized)
1639 << DeclType << IList->getSourceRange();
1640 hadError = true;
1641 ++Index;
1642 ++StructuredIndex;
1643 return;
1644 }
1645
1646 Expr *expr = IList->getInit(Index);
1647 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1648 if (!VerifyOnly)
1649 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1650 << DeclType << IList->getSourceRange();
1651 hadError = true;
1652 ++Index;
1653 ++StructuredIndex;
1654 return;
1655 }
1656
1657 ExprResult Result;
1658 if (VerifyOnly) {
1659 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1660 Result = getDummyInit();
1661 else
1662 Result = ExprError();
1663 } else {
1664 Result =
1665 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1666 /*TopLevelOfInitList=*/true);
1667 }
1668
1669 if (Result.isInvalid())
1670 hadError = true;
1671
1672 expr = Result.getAs<Expr>();
1673 // FIXME: Why are we updating the syntactic init list?
1674 if (!VerifyOnly && expr)
1675 IList->setInit(Index, expr);
1676
1677 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1678 ++Index;
1679}
1680
1681void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1682 InitListExpr *IList, QualType DeclType,
1683 unsigned &Index,
1684 InitListExpr *StructuredList,
1685 unsigned &StructuredIndex) {
1686 const VectorType *VT = DeclType->castAs<VectorType>();
1687 unsigned maxElements = VT->getNumElements();
1688 unsigned numEltsInit = 0;
1689 QualType elementType = VT->getElementType();
1690
1691 if (Index >= IList->getNumInits()) {
1692 // Make sure the element type can be value-initialized.
1693 CheckEmptyInitializable(
1694 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1695 IList->getEndLoc());
1696 return;
1697 }
1698
1699 if (!SemaRef.getLangOpts().OpenCL) {
1700 // If the initializing element is a vector, try to copy-initialize
1701 // instead of breaking it apart (which is doomed to failure anyway).
1702 Expr *Init = IList->getInit(Index);
1703 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1704 ExprResult Result;
1705 if (VerifyOnly) {
1706 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1707 Result = getDummyInit();
1708 else
1709 Result = ExprError();
1710 } else {
1711 Result =
1712 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1713 /*TopLevelOfInitList=*/true);
1714 }
1715
1716 Expr *ResultExpr = nullptr;
1717 if (Result.isInvalid())
1718 hadError = true; // types weren't compatible.
1719 else {
1720 ResultExpr = Result.getAs<Expr>();
1721
1722 if (ResultExpr != Init && !VerifyOnly) {
1723 // The type was promoted, update initializer list.
1724 // FIXME: Why are we updating the syntactic init list?
1725 IList->setInit(Index, ResultExpr);
1726 }
1727 }
1728 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1729 ++Index;
1730 return;
1731 }
1732
1733 InitializedEntity ElementEntity =
1734 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1735
1736 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1737 // Don't attempt to go past the end of the init list
1738 if (Index >= IList->getNumInits()) {
1739 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1740 break;
1741 }
1742
1743 ElementEntity.setElementIndex(Index);
1744 CheckSubElementType(ElementEntity, IList, elementType, Index,
1745 StructuredList, StructuredIndex);
1746 }
1747
1748 if (VerifyOnly)
1749 return;
1750
1751 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1752 const VectorType *T = Entity.getType()->castAs<VectorType>();
1753 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1754 T->getVectorKind() == VectorType::NeonPolyVector)) {
1755 // The ability to use vector initializer lists is a GNU vector extension
1756 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1757 // endian machines it works fine, however on big endian machines it
1758 // exhibits surprising behaviour:
1759 //
1760 // uint32x2_t x = {42, 64};
1761 // return vget_lane_u32(x, 0); // Will return 64.
1762 //
1763 // Because of this, explicitly call out that it is non-portable.
1764 //
1765 SemaRef.Diag(IList->getBeginLoc(),
1766 diag::warn_neon_vector_initializer_non_portable);
1767
1768 const char *typeCode;
1769 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1770
1771 if (elementType->isFloatingType())
1772 typeCode = "f";
1773 else if (elementType->isSignedIntegerType())
1774 typeCode = "s";
1775 else if (elementType->isUnsignedIntegerType())
1776 typeCode = "u";
1777 else
1778 llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "clang/lib/Sema/SemaInit.cpp"
, 1778)
;
1779
1780 SemaRef.Diag(IList->getBeginLoc(),
1781 SemaRef.Context.getTypeSize(VT) > 64
1782 ? diag::note_neon_vector_initializer_non_portable_q
1783 : diag::note_neon_vector_initializer_non_portable)
1784 << typeCode << typeSize;
1785 }
1786
1787 return;
1788 }
1789
1790 InitializedEntity ElementEntity =
1791 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1792
1793 // OpenCL initializers allows vectors to be constructed from vectors.
1794 for (unsigned i = 0; i < maxElements; ++i) {
1795 // Don't attempt to go past the end of the init list
1796 if (Index >= IList->getNumInits())
1797 break;
1798
1799 ElementEntity.setElementIndex(Index);
1800
1801 QualType IType = IList->getInit(Index)->getType();
1802 if (!IType->isVectorType()) {
1803 CheckSubElementType(ElementEntity, IList, elementType, Index,
1804 StructuredList, StructuredIndex);
1805 ++numEltsInit;
1806 } else {
1807 QualType VecType;
1808 const VectorType *IVT = IType->castAs<VectorType>();
1809 unsigned numIElts = IVT->getNumElements();
1810
1811 if (IType->isExtVectorType())
1812 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1813 else
1814 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1815 IVT->getVectorKind());
1816 CheckSubElementType(ElementEntity, IList, VecType, Index,
1817 StructuredList, StructuredIndex);
1818 numEltsInit += numIElts;
1819 }
1820 }
1821
1822 // OpenCL requires all elements to be initialized.
1823 if (numEltsInit != maxElements) {
1824 if (!VerifyOnly)
1825 SemaRef.Diag(IList->getBeginLoc(),
1826 diag::err_vector_incorrect_num_initializers)
1827 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1828 hadError = true;
1829 }
1830}
1831
1832/// Check if the type of a class element has an accessible destructor, and marks
1833/// it referenced. Returns true if we shouldn't form a reference to the
1834/// destructor.
1835///
1836/// Aggregate initialization requires a class element's destructor be
1837/// accessible per 11.6.1 [dcl.init.aggr]:
1838///
1839/// The destructor for each element of class type is potentially invoked
1840/// (15.4 [class.dtor]) from the context where the aggregate initialization
1841/// occurs.
1842static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1843 Sema &SemaRef) {
1844 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1845 if (!CXXRD)
1846 return false;
1847
1848 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1849 SemaRef.CheckDestructorAccess(Loc, Destructor,
1850 SemaRef.PDiag(diag::err_access_dtor_temp)
1851 << ElementType);
1852 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1853 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1854}
1855
1856void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1857 InitListExpr *IList, QualType &DeclType,
1858 llvm::APSInt elementIndex,
1859 bool SubobjectIsDesignatorContext,
1860 unsigned &Index,
1861 InitListExpr *StructuredList,
1862 unsigned &StructuredIndex) {
1863 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1864
1865 if (!VerifyOnly) {
1866 if (checkDestructorReference(arrayType->getElementType(),
1867 IList->getEndLoc(), SemaRef)) {
1868 hadError = true;
1869 return;
1870 }
1871 }
1872
1873 // Check for the special-case of initializing an array with a string.
1874 if (Index < IList->getNumInits()) {
1875 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1876 SIF_None) {
1877 // We place the string literal directly into the resulting
1878 // initializer list. This is the only place where the structure
1879 // of the structured initializer list doesn't match exactly,
1880 // because doing so would involve allocating one character
1881 // constant for each string.
1882 // FIXME: Should we do these checks in verify-only mode too?
1883 if (!VerifyOnly)
1884 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1885 if (StructuredList) {
1886 UpdateStructuredListElement(StructuredList, StructuredIndex,
1887 IList->getInit(Index));
1888 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1889 }
1890 ++Index;
1891 return;
1892 }
1893 }
1894 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1895 // Check for VLAs; in standard C it would be possible to check this
1896 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1897 // them in all sorts of strange places).
1898 if (!VerifyOnly)
1899 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1900 diag::err_variable_object_no_init)
1901 << VAT->getSizeExpr()->getSourceRange();
1902 hadError = true;
1903 ++Index;
1904 ++StructuredIndex;
1905 return;
1906 }
1907
1908 // We might know the maximum number of elements in advance.
1909 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1910 elementIndex.isUnsigned());
1911 bool maxElementsKnown = false;
1912 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1913 maxElements = CAT->getSize();
1914 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1915 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1916 maxElementsKnown = true;
1917 }
1918
1919 QualType elementType = arrayType->getElementType();
1920 while (Index < IList->getNumInits()) {
1921 Expr *Init = IList->getInit(Index);
1922 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1923 // If we're not the subobject that matches up with the '{' for
1924 // the designator, we shouldn't be handling the
1925 // designator. Return immediately.
1926 if (!SubobjectIsDesignatorContext)
1927 return;
1928
1929 // Handle this designated initializer. elementIndex will be
1930 // updated to be the next array element we'll initialize.
1931 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1932 DeclType, nullptr, &elementIndex, Index,
1933 StructuredList, StructuredIndex, true,
1934 false)) {
1935 hadError = true;
1936 continue;
1937 }
1938
1939 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1940 maxElements = maxElements.extend(elementIndex.getBitWidth());
1941 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1942 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1943 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1944
1945 // If the array is of incomplete type, keep track of the number of
1946 // elements in the initializer.
1947 if (!maxElementsKnown && elementIndex > maxElements)
1948 maxElements = elementIndex;
1949
1950 continue;
1951 }
1952
1953 // If we know the maximum number of elements, and we've already
1954 // hit it, stop consuming elements in the initializer list.
1955 if (maxElementsKnown && elementIndex == maxElements)
1956 break;
1957
1958 InitializedEntity ElementEntity =
1959 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1960 Entity);
1961 // Check this element.
1962 CheckSubElementType(ElementEntity, IList, elementType, Index,
1963 StructuredList, StructuredIndex);
1964 ++elementIndex;
1965
1966 // If the array is of incomplete type, keep track of the number of
1967 // elements in the initializer.
1968 if (!maxElementsKnown && elementIndex > maxElements)
1969 maxElements = elementIndex;
1970 }
1971 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1972 // If this is an incomplete array type, the actual type needs to
1973 // be calculated here.
1974 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1975 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1976 // Sizing an array implicitly to zero is not allowed by ISO C,
1977 // but is supported by GNU.
1978 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
1979 }
1980
1981 DeclType = SemaRef.Context.getConstantArrayType(
1982 elementType, maxElements, nullptr, ArrayType::Normal, 0);
1983 }
1984 if (!hadError) {
1985 // If there are any members of the array that get value-initialized, check
1986 // that is possible. That happens if we know the bound and don't have
1987 // enough elements, or if we're performing an array new with an unknown
1988 // bound.
1989 if ((maxElementsKnown && elementIndex < maxElements) ||
1990 Entity.isVariableLengthArrayNew())
1991 CheckEmptyInitializable(
1992 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1993 IList->getEndLoc());
1994 }
1995}
1996
1997bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1998 Expr *InitExpr,
1999 FieldDecl *Field,
2000 bool TopLevelObject) {
2001 // Handle GNU flexible array initializers.
2002 unsigned FlexArrayDiag;
2003 if (isa<InitListExpr>(InitExpr) &&
2004 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2005 // Empty flexible array init always allowed as an extension
2006 FlexArrayDiag = diag::ext_flexible_array_init;
2007 } else if (!TopLevelObject) {
2008 // Disallow flexible array init on non-top-level object
2009 FlexArrayDiag = diag::err_flexible_array_init;
2010 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2011 // Disallow flexible array init on anything which is not a variable.
2012 FlexArrayDiag = diag::err_flexible_array_init;
2013 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2014 // Disallow flexible array init on local variables.
2015 FlexArrayDiag = diag::err_flexible_array_init;
2016 } else {
2017 // Allow other cases.
2018 FlexArrayDiag = diag::ext_flexible_array_init;
2019 }
2020
2021 if (!VerifyOnly) {
2022 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2023 << InitExpr->getBeginLoc();
2024 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2025 << Field;
2026 }
2027
2028 return FlexArrayDiag != diag::ext_flexible_array_init;
2029}
2030
2031void InitListChecker::CheckStructUnionTypes(
2032 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2033 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
2034 bool SubobjectIsDesignatorContext, unsigned &Index,
2035 InitListExpr *StructuredList, unsigned &StructuredIndex,
2036 bool TopLevelObject) {
2037 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
2038
2039 // If the record is invalid, some of it's members are invalid. To avoid
2040 // confusion, we forgo checking the initializer for the entire record.
2041 if (structDecl->isInvalidDecl()) {
2042 // Assume it was supposed to consume a single initializer.
2043 ++Index;
2044 hadError = true;
2045 return;
2046 }
2047
2048 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
2049 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2050
2051 if (!VerifyOnly)
2052 for (FieldDecl *FD : RD->fields()) {
2053 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2054 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2055 hadError = true;
2056 return;
2057 }
2058 }
2059
2060 // If there's a default initializer, use it.
2061 if (isa<CXXRecordDecl>(RD) &&
2062 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2063 if (!StructuredList)
2064 return;
2065 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2066 Field != FieldEnd; ++Field) {
2067 if (Field->hasInClassInitializer()) {
2068 StructuredList->setInitializedFieldInUnion(*Field);
2069 // FIXME: Actually build a CXXDefaultInitExpr?
2070 return;
2071 }
2072 }
2073 }
2074
2075 // Value-initialize the first member of the union that isn't an unnamed
2076 // bitfield.
2077 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2078 Field != FieldEnd; ++Field) {
2079 if (!Field->isUnnamedBitfield()) {
2080 CheckEmptyInitializable(
2081 InitializedEntity::InitializeMember(*Field, &Entity),
2082 IList->getEndLoc());
2083 if (StructuredList)
2084 StructuredList->setInitializedFieldInUnion(*Field);
2085 break;
2086 }
2087 }
2088 return;
2089 }
2090
2091 bool InitializedSomething = false;
2092
2093 // If we have any base classes, they are initialized prior to the fields.
2094 for (auto &Base : Bases) {
2095 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2096
2097 // Designated inits always initialize fields, so if we see one, all
2098 // remaining base classes have no explicit initializer.
2099 if (Init && isa<DesignatedInitExpr>(Init))
2100 Init = nullptr;
2101
2102 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2103 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2104 SemaRef.Context, &Base, false, &Entity);
2105 if (Init) {
2106 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2107 StructuredList, StructuredIndex);
2108 InitializedSomething = true;
2109 } else {
2110 CheckEmptyInitializable(BaseEntity, InitLoc);
2111 }
2112
2113 if (!VerifyOnly)
2114 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2115 hadError = true;
2116 return;
2117 }
2118 }
2119
2120 // If structDecl is a forward declaration, this loop won't do
2121 // anything except look at designated initializers; That's okay,
2122 // because an error should get printed out elsewhere. It might be
2123 // worthwhile to skip over the rest of the initializer, though.
2124 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2125 RecordDecl::field_iterator FieldEnd = RD->field_end();
2126 size_t NumRecordFields = std::distance(RD->field_begin(), RD->field_end());
2127 bool CheckForMissingFields =
2128 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2129 bool HasDesignatedInit = false;
2130
2131 while (Index < IList->getNumInits()) {
2132 Expr *Init = IList->getInit(Index);
2133 SourceLocation InitLoc = Init->getBeginLoc();
2134
2135 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2136 // If we're not the subobject that matches up with the '{' for
2137 // the designator, we shouldn't be handling the
2138 // designator. Return immediately.
2139 if (!SubobjectIsDesignatorContext)
2140 return;
2141
2142 HasDesignatedInit = true;
2143
2144 // Handle this designated initializer. Field will be updated to
2145 // the next field that we'll be initializing.
2146 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2147 DeclType, &Field, nullptr, Index,
2148 StructuredList, StructuredIndex,
2149 true, TopLevelObject))
2150 hadError = true;
2151 else if (!VerifyOnly) {
2152 // Find the field named by the designated initializer.
2153 RecordDecl::field_iterator F = RD->field_begin();
2154 while (std::next(F) != Field)
2155 ++F;
2156 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2157 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2158 hadError = true;
2159 return;
2160 }
2161 }
2162
2163 InitializedSomething = true;
2164
2165 // Disable check for missing fields when designators are used.
2166 // This matches gcc behaviour.
2167 CheckForMissingFields = false;
2168 continue;
2169 }
2170
2171 if (Field == FieldEnd) {
2172 // We've run out of fields. We're done.
2173 break;
2174 }
2175
2176 // Check if this is an initializer of forms:
2177 //
2178 // struct foo f = {};
2179 // struct foo g = {0};
2180 //
2181 // These are okay for randomized structures. [C99 6.7.8p19]
2182 //
2183 // Also, if there is only one element in the structure, we allow something
2184 // like this, because it's really not randomized in the tranditional sense.
2185 //
2186 // struct foo h = {bar};
2187 auto IsZeroInitializer = [&](const Expr *I) {
2188 if (IList->getNumInits() == 1) {
2189 if (NumRecordFields == 1)
2190 return true;
2191 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2192 return IL->getValue().isZero();
2193 }
2194 return false;
2195 };
2196
2197 // Don't allow non-designated initializers on randomized structures.
2198 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2199 if (!VerifyOnly)
2200 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2201 hadError = true;
2202 break;
2203 }
2204
2205 // We've already initialized a member of a union. We're done.
2206 if (InitializedSomething && DeclType->isUnionType())
2207 break;
2208
2209 // If we've hit the flexible array member at the end, we're done.
2210 if (Field->getType()->isIncompleteArrayType())
2211 break;
2212
2213 if (Field->isUnnamedBitfield()) {
2214 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2215 ++Field;
2216 continue;
2217 }
2218
2219 // Make sure we can use this declaration.
2220 bool InvalidUse;
2221 if (VerifyOnly)
2222 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2223 else
2224 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2225 *Field, IList->getInit(Index)->getBeginLoc());
2226 if (InvalidUse) {
2227 ++Index;
2228 ++Field;
2229 hadError = true;
2230 continue;
2231 }
2232
2233 if (!VerifyOnly) {
2234 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2235 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2236 hadError = true;
2237 return;
2238 }
2239 }
2240
2241 InitializedEntity MemberEntity =
2242 InitializedEntity::InitializeMember(*Field, &Entity);
2243 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2244 StructuredList, StructuredIndex);
2245 InitializedSomething = true;
2246
2247 if (DeclType->isUnionType() && StructuredList) {
2248 // Initialize the first field within the union.
2249 StructuredList->setInitializedFieldInUnion(*Field);
2250 }
2251
2252 ++Field;
2253 }
2254
2255 // Emit warnings for missing struct field initializers.
2256 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2257 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2258 !DeclType->isUnionType()) {
2259 // It is possible we have one or more unnamed bitfields remaining.
2260 // Find first (if any) named field and emit warning.
2261 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2262 it != end; ++it) {
2263 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2264 SemaRef.Diag(IList->getSourceRange().getEnd(),
2265 diag::warn_missing_field_initializers) << *it;
2266 break;
2267 }
2268 }
2269 }
2270
2271 // Check that any remaining fields can be value-initialized if we're not
2272 // building a structured list. (If we are, we'll check this later.)
2273 if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() &&
2274 !Field->getType()->isIncompleteArrayType()) {
2275 for (; Field != FieldEnd && !hadError; ++Field) {
2276 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2277 CheckEmptyInitializable(
2278 InitializedEntity::InitializeMember(*Field, &Entity),
2279 IList->getEndLoc());
2280 }
2281 }
2282
2283 // Check that the types of the remaining fields have accessible destructors.
2284 if (!VerifyOnly) {
2285 // If the initializer expression has a designated initializer, check the
2286 // elements for which a designated initializer is not provided too.
2287 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2288 : Field;
2289 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2290 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2291 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2292 hadError = true;
2293 return;
2294 }
2295 }
2296 }
2297
2298 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2299 Index >= IList->getNumInits())
2300 return;
2301
2302 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2303 TopLevelObject)) {
2304 hadError = true;
2305 ++Index;
2306 return;
2307 }
2308
2309 InitializedEntity MemberEntity =
2310 InitializedEntity::InitializeMember(*Field, &Entity);
2311
2312 if (isa<InitListExpr>(IList->getInit(Index)))
2313 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2314 StructuredList, StructuredIndex);
2315 else
2316 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2317 StructuredList, StructuredIndex);
2318}
2319
2320/// Expand a field designator that refers to a member of an
2321/// anonymous struct or union into a series of field designators that
2322/// refers to the field within the appropriate subobject.
2323///
2324static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2325 DesignatedInitExpr *DIE,
2326 unsigned DesigIdx,
2327 IndirectFieldDecl *IndirectField) {
2328 typedef DesignatedInitExpr::Designator Designator;
2329
2330 // Build the replacement designators.
2331 SmallVector<Designator, 4> Replacements;
2332 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2333 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2334 if (PI + 1 == PE)
2335 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2336 DIE->getDesignator(DesigIdx)->getDotLoc(),
2337 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2338 else
2339 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2340 SourceLocation(), SourceLocation()));
2341 assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(*PI)", "clang/lib/Sema/SemaInit.cpp"
, 2341, __extension__ __PRETTY_FUNCTION__))
;
2342 Replacements.back().setField(cast<FieldDecl>(*PI));
2343 }
2344
2345 // Expand the current designator into the set of replacement
2346 // designators, so we have a full subobject path down to where the
2347 // member of the anonymous struct/union is actually stored.
2348 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2349 &Replacements[0] + Replacements.size());
2350}
2351
2352static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2353 DesignatedInitExpr *DIE) {
2354 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2355 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2356 for (unsigned I = 0; I < NumIndexExprs; ++I)
2357 IndexExprs[I] = DIE->getSubExpr(I + 1);
2358 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2359 IndexExprs,
2360 DIE->getEqualOrColonLoc(),
2361 DIE->usesGNUSyntax(), DIE->getInit());
2362}
2363
2364namespace {
2365
2366// Callback to only accept typo corrections that are for field members of
2367// the given struct or union.
2368class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2369 public:
2370 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2371 : Record(RD) {}
2372
2373 bool ValidateCandidate(const TypoCorrection &candidate) override {
2374 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2375 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2376 }
2377
2378 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2379 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2380 }
2381
2382 private:
2383 RecordDecl *Record;
2384};
2385
2386} // end anonymous namespace
2387
2388/// Check the well-formedness of a C99 designated initializer.
2389///
2390/// Determines whether the designated initializer @p DIE, which
2391/// resides at the given @p Index within the initializer list @p
2392/// IList, is well-formed for a current object of type @p DeclType
2393/// (C99 6.7.8). The actual subobject that this designator refers to
2394/// within the current subobject is returned in either
2395/// @p NextField or @p NextElementIndex (whichever is appropriate).
2396///
2397/// @param IList The initializer list in which this designated
2398/// initializer occurs.
2399///
2400/// @param DIE The designated initializer expression.
2401///
2402/// @param DesigIdx The index of the current designator.
2403///
2404/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2405/// into which the designation in @p DIE should refer.
2406///
2407/// @param NextField If non-NULL and the first designator in @p DIE is
2408/// a field, this will be set to the field declaration corresponding
2409/// to the field named by the designator. On input, this is expected to be
2410/// the next field that would be initialized in the absence of designation,
2411/// if the complete object being initialized is a struct.
2412///
2413/// @param NextElementIndex If non-NULL and the first designator in @p
2414/// DIE is an array designator or GNU array-range designator, this
2415/// will be set to the last index initialized by this designator.
2416///
2417/// @param Index Index into @p IList where the designated initializer
2418/// @p DIE occurs.
2419///
2420/// @param StructuredList The initializer list expression that
2421/// describes all of the subobject initializers in the order they'll
2422/// actually be initialized.
2423///
2424/// @returns true if there was an error, false otherwise.
2425bool
2426InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2427 InitListExpr *IList,
2428 DesignatedInitExpr *DIE,
2429 unsigned DesigIdx,
2430 QualType &CurrentObjectType,
2431 RecordDecl::field_iterator *NextField,
2432 llvm::APSInt *NextElementIndex,
2433 unsigned &Index,
2434 InitListExpr *StructuredList,
2435 unsigned &StructuredIndex,
2436 bool FinishSubobjectInit,
2437 bool TopLevelObject) {
2438 if (DesigIdx == DIE->size()) {
2439 // C++20 designated initialization can result in direct-list-initialization
2440 // of the designated subobject. This is the only way that we can end up
2441 // performing direct initialization as part of aggregate initialization, so
2442 // it needs special handling.
2443 if (DIE->isDirectInit()) {
2444 Expr *Init = DIE->getInit();
2445 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"designator result in direct non-list initialization?") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\""
, "clang/lib/Sema/SemaInit.cpp", 2446, __extension__ __PRETTY_FUNCTION__
))
2446 "designator result in direct non-list initialization?")(static_cast <bool> (isa<InitListExpr>(Init) &&
"designator result in direct non-list initialization?") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\""
, "clang/lib/Sema/SemaInit.cpp", 2446, __extension__ __PRETTY_FUNCTION__
))
;
2447 InitializationKind Kind = InitializationKind::CreateDirectList(
2448 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2449 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2450 /*TopLevelOfInitList*/ true);
2451 if (StructuredList) {
2452 ExprResult Result = VerifyOnly
2453 ? getDummyInit()
2454 : Seq.Perform(SemaRef, Entity, Kind, Init);
2455 UpdateStructuredListElement(StructuredList, StructuredIndex,
2456 Result.get());
2457 }
2458 ++Index;
2459 return !Seq;
2460 }
2461
2462 // Check the actual initialization for the designated object type.
2463 bool prevHadError = hadError;
2464
2465 // Temporarily remove the designator expression from the
2466 // initializer list that the child calls see, so that we don't try
2467 // to re-process the designator.
2468 unsigned OldIndex = Index;
2469 IList->setInit(OldIndex, DIE->getInit());
2470
2471 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2472 StructuredIndex, /*DirectlyDesignated=*/true);
2473
2474 // Restore the designated initializer expression in the syntactic
2475 // form of the initializer list.
2476 if (IList->getInit(OldIndex) != DIE->getInit())
2477 DIE->setInit(IList->getInit(OldIndex));
2478 IList->setInit(OldIndex, DIE);
2479
2480 return hadError && !prevHadError;
2481 }
2482
2483 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2484 bool IsFirstDesignator = (DesigIdx == 0);
2485 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2486 // Determine the structural initializer list that corresponds to the
2487 // current subobject.
2488 if (IsFirstDesignator)
2489 StructuredList = FullyStructuredList;
2490 else {
2491 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2492 StructuredList->getInit(StructuredIndex) : nullptr;
2493 if (!ExistingInit && StructuredList->hasArrayFiller())
2494 ExistingInit = StructuredList->getArrayFiller();
2495
2496 if (!ExistingInit)
2497 StructuredList = getStructuredSubobjectInit(
2498 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2499 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2500 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2501 StructuredList = Result;
2502 else {
2503 // We are creating an initializer list that initializes the
2504 // subobjects of the current object, but there was already an
2505 // initialization that completely initialized the current
2506 // subobject, e.g., by a compound literal:
2507 //
2508 // struct X { int a, b; };
2509 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2510 //
2511 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2512 // designated initializer re-initializes only its current object
2513 // subobject [0].b.
2514 diagnoseInitOverride(ExistingInit,
2515 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2516 /*FullyOverwritten=*/false);
2517
2518 if (!VerifyOnly) {
2519 if (DesignatedInitUpdateExpr *E =
2520 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2521 StructuredList = E->getUpdater();
2522 else {
2523 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2524 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2525 ExistingInit, DIE->getEndLoc());
2526 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2527 StructuredList = DIUE->getUpdater();
2528 }
2529 } else {
2530 // We don't need to track the structured representation of a
2531 // designated init update of an already-fully-initialized object in
2532 // verify-only mode. The only reason we would need the structure is
2533 // to determine where the uninitialized "holes" are, and in this
2534 // case, we know there aren't any and we can't introduce any.
2535 StructuredList = nullptr;
2536 }
2537 }
2538 }
2539 }
2540
2541 if (D->isFieldDesignator()) {
2542 // C99 6.7.8p7:
2543 //
2544 // If a designator has the form
2545 //
2546 // . identifier
2547 //
2548 // then the current object (defined below) shall have
2549 // structure or union type and the identifier shall be the
2550 // name of a member of that type.
2551 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2552 if (!RT) {
2553 SourceLocation Loc = D->getDotLoc();
2554 if (Loc.isInvalid())
2555 Loc = D->getFieldLoc();
2556 if (!VerifyOnly)
2557 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2558 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2559 ++Index;
2560 return true;
2561 }
2562
2563 FieldDecl *KnownField = D->getField();
2564 if (!KnownField) {
2565 IdentifierInfo *FieldName = D->getFieldName();
2566 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2567 for (NamedDecl *ND : Lookup) {
2568 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2569 KnownField = FD;
2570 break;
2571 }
2572 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2573 // In verify mode, don't modify the original.
2574 if (VerifyOnly)
2575 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2576 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2577 D = DIE->getDesignator(DesigIdx);
2578 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2579 break;
2580 }
2581 }
2582 if (!KnownField) {
2583 if (VerifyOnly) {
2584 ++Index;
2585 return true; // No typo correction when just trying this out.
2586 }
2587
2588 // Name lookup found something, but it wasn't a field.
2589 if (!Lookup.empty()) {
2590 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2591 << FieldName;
2592 SemaRef.Diag(Lookup.front()->getLocation(),
2593 diag::note_field_designator_found);
2594 ++Index;
2595 return true;
2596 }
2597
2598 // Name lookup didn't find anything.
2599 // Determine whether this was a typo for another field name.
2600 FieldInitializerValidatorCCC CCC(RT->getDecl());
2601 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2602 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2603 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2604 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2605 SemaRef.diagnoseTypo(
2606 Corrected,
2607 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2608 << FieldName << CurrentObjectType);
2609 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2610 hadError = true;
2611 } else {
2612 // Typo correction didn't find anything.
2613 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2614 << FieldName << CurrentObjectType;
2615 ++Index;
2616 return true;
2617 }
2618 }
2619 }
2620
2621 unsigned NumBases = 0;
2622 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2623 NumBases = CXXRD->getNumBases();
2624
2625 unsigned FieldIndex = NumBases;
2626
2627 for (auto *FI : RT->getDecl()->fields()) {
2628 if (FI->isUnnamedBitfield())
2629 continue;
2630 if (declaresSameEntity(KnownField, FI)) {
2631 KnownField = FI;
2632 break;
2633 }
2634 ++FieldIndex;
2635 }
2636
2637 RecordDecl::field_iterator Field =
2638 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2639
2640 // All of the fields of a union are located at the same place in
2641 // the initializer list.
2642 if (RT->getDecl()->isUnion()) {
2643 FieldIndex = 0;
2644 if (StructuredList) {
2645 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2646 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2647 assert(StructuredList->getNumInits() == 1(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "clang/lib/Sema/SemaInit.cpp", 2648, __extension__ __PRETTY_FUNCTION__
))
2648 && "A union should never have more than one initializer!")(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "clang/lib/Sema/SemaInit.cpp", 2648, __extension__ __PRETTY_FUNCTION__
))
;
2649
2650 Expr *ExistingInit = StructuredList->getInit(0);
2651 if (ExistingInit) {
2652 // We're about to throw away an initializer, emit warning.
2653 diagnoseInitOverride(
2654 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2655 }
2656
2657 // remove existing initializer
2658 StructuredList->resizeInits(SemaRef.Context, 0);
2659 StructuredList->setInitializedFieldInUnion(nullptr);
2660 }
2661
2662 StructuredList->setInitializedFieldInUnion(*Field);
2663 }
2664 }
2665
2666 // Make sure we can use this declaration.
2667 bool InvalidUse;
2668 if (VerifyOnly)
2669 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2670 else
2671 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2672 if (InvalidUse) {
2673 ++Index;
2674 return true;
2675 }
2676
2677 // C++20 [dcl.init.list]p3:
2678 // The ordered identifiers in the designators of the designated-
2679 // initializer-list shall form a subsequence of the ordered identifiers
2680 // in the direct non-static data members of T.
2681 //
2682 // Note that this is not a condition on forming the aggregate
2683 // initialization, only on actually performing initialization,
2684 // so it is not checked in VerifyOnly mode.
2685 //
2686 // FIXME: This is the only reordering diagnostic we produce, and it only
2687 // catches cases where we have a top-level field designator that jumps
2688 // backwards. This is the only such case that is reachable in an
2689 // otherwise-valid C++20 program, so is the only case that's required for
2690 // conformance, but for consistency, we should diagnose all the other
2691 // cases where a designator takes us backwards too.
2692 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2693 NextField &&
2694 (*NextField == RT->getDecl()->field_end() ||
2695 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2696 // Find the field that we just initialized.
2697 FieldDecl *PrevField = nullptr;
2698 for (auto FI = RT->getDecl()->field_begin();
2699 FI != RT->getDecl()->field_end(); ++FI) {
2700 if (FI->isUnnamedBitfield())
2701 continue;
2702 if (*NextField != RT->getDecl()->field_end() &&
2703 declaresSameEntity(*FI, **NextField))
2704 break;
2705 PrevField = *FI;
2706 }
2707
2708 if (PrevField &&
2709 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2710 SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
2711 << KnownField << PrevField << DIE->getSourceRange();
2712
2713 unsigned OldIndex = NumBases + PrevField->getFieldIndex();
2714 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2715 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2716 SemaRef.Diag(PrevInit->getBeginLoc(),
2717 diag::note_previous_field_init)
2718 << PrevField << PrevInit->getSourceRange();
2719 }
2720 }
2721 }
2722 }
2723
2724
2725 // Update the designator with the field declaration.
2726 if (!VerifyOnly)
2727 D->setField(*Field);
2728
2729 // Make sure that our non-designated initializer list has space
2730 // for a subobject corresponding to this field.
2731 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2732 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2733
2734 // This designator names a flexible array member.
2735 if (Field->getType()->isIncompleteArrayType()) {
2736 bool Invalid = false;
2737 if ((DesigIdx + 1) != DIE->size()) {
2738 // We can't designate an object within the flexible array
2739 // member (because GCC doesn't allow it).
2740 if (!VerifyOnly) {
2741 DesignatedInitExpr::Designator *NextD
2742 = DIE->getDesignator(DesigIdx + 1);
2743 SemaRef.Diag(NextD->getBeginLoc(),
2744 diag::err_designator_into_flexible_array_member)
2745 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2746 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2747 << *Field;
2748 }
2749 Invalid = true;
2750 }
2751
2752 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2753 !isa<StringLiteral>(DIE->getInit())) {
2754 // The initializer is not an initializer list.
2755 if (!VerifyOnly) {
2756 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2757 diag::err_flexible_array_init_needs_braces)
2758 << DIE->getInit()->getSourceRange();
2759 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2760 << *Field;
2761 }
2762 Invalid = true;
2763 }
2764
2765 // Check GNU flexible array initializer.
2766 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2767 TopLevelObject))
2768 Invalid = true;
2769
2770 if (Invalid) {
2771 ++Index;
2772 return true;
2773 }
2774
2775 // Initialize the array.
2776 bool prevHadError = hadError;
2777 unsigned newStructuredIndex = FieldIndex;
2778 unsigned OldIndex = Index;
2779 IList->setInit(Index, DIE->getInit());
2780
2781 InitializedEntity MemberEntity =
2782 InitializedEntity::InitializeMember(*Field, &Entity);
2783 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2784 StructuredList, newStructuredIndex);
2785
2786 IList->setInit(OldIndex, DIE);
2787 if (hadError && !prevHadError) {
2788 ++Field;
2789 ++FieldIndex;
2790 if (NextField)
2791 *NextField = Field;
2792 StructuredIndex = FieldIndex;
2793 return true;
2794 }
2795 } else {
2796 // Recurse to check later designated subobjects.
2797 QualType FieldType = Field->getType();
2798 unsigned newStructuredIndex = FieldIndex;
2799
2800 InitializedEntity MemberEntity =
2801 InitializedEntity::InitializeMember(*Field, &Entity);
2802 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2803 FieldType, nullptr, nullptr, Index,
2804 StructuredList, newStructuredIndex,
2805 FinishSubobjectInit, false))
2806 return true;
2807 }
2808
2809 // Find the position of the next field to be initialized in this
2810 // subobject.
2811 ++Field;
2812 ++FieldIndex;
2813
2814 // If this the first designator, our caller will continue checking
2815 // the rest of this struct/class/union subobject.
2816 if (IsFirstDesignator) {
2817 if (NextField)
2818 *NextField = Field;
2819 StructuredIndex = FieldIndex;
2820 return false;
2821 }
2822
2823 if (!FinishSubobjectInit)
2824 return false;
2825
2826 // We've already initialized something in the union; we're done.
2827 if (RT->getDecl()->isUnion())
2828 return hadError;
2829
2830 // Check the remaining fields within this class/struct/union subobject.
2831 bool prevHadError = hadError;
2832
2833 auto NoBases =
2834 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2835 CXXRecordDecl::base_class_iterator());
2836 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2837 false, Index, StructuredList, FieldIndex);
2838 return hadError && !prevHadError;
2839 }
2840
2841 // C99 6.7.8p6:
2842 //
2843 // If a designator has the form
2844 //
2845 // [ constant-expression ]
2846 //
2847 // then the current object (defined below) shall have array
2848 // type and the expression shall be an integer constant
2849 // expression. If the array is of unknown size, any
2850 // nonnegative value is valid.
2851 //
2852 // Additionally, cope with the GNU extension that permits
2853 // designators of the form
2854 //
2855 // [ constant-expression ... constant-expression ]
2856 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2857 if (!AT) {
2858 if (!VerifyOnly)
2859 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2860 << CurrentObjectType;
2861 ++Index;
2862 return true;
2863 }
2864
2865 Expr *IndexExpr = nullptr;
2866 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2867 if (D->isArrayDesignator()) {
2868 IndexExpr = DIE->getArrayIndex(*D);
2869 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2870 DesignatedEndIndex = DesignatedStartIndex;
2871 } else {
2872 assert(D->isArrayRangeDesignator() && "Need array-range designator")(static_cast <bool> (D->isArrayRangeDesignator() &&
"Need array-range designator") ? void (0) : __assert_fail ("D->isArrayRangeDesignator() && \"Need array-range designator\""
, "clang/lib/Sema/SemaInit.cpp", 2872, __extension__ __PRETTY_FUNCTION__
))
;
2873
2874 DesignatedStartIndex =
2875 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2876 DesignatedEndIndex =
2877 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2878 IndexExpr = DIE->getArrayRangeEnd(*D);
2879
2880 // Codegen can't handle evaluating array range designators that have side
2881 // effects, because we replicate the AST value for each initialized element.
2882 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2883 // elements with something that has a side effect, so codegen can emit an
2884 // "error unsupported" error instead of miscompiling the app.
2885 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2886 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2887 FullyStructuredList->sawArrayRangeDesignator();
2888 }
2889
2890 if (isa<ConstantArrayType>(AT)) {
2891 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2892 DesignatedStartIndex
2893 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2894 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2895 DesignatedEndIndex
2896 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2897 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2898 if (DesignatedEndIndex >= MaxElements) {
2899 if (!VerifyOnly)
2900 SemaRef.Diag(IndexExpr->getBeginLoc(),
2901 diag::err_array_designator_too_large)
2902 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
2903 << IndexExpr->getSourceRange();
2904 ++Index;
2905 return true;
2906 }
2907 } else {
2908 unsigned DesignatedIndexBitWidth =
2909 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2910 DesignatedStartIndex =
2911 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2912 DesignatedEndIndex =
2913 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2914 DesignatedStartIndex.setIsUnsigned(true);
2915 DesignatedEndIndex.setIsUnsigned(true);
2916 }
2917
2918 bool IsStringLiteralInitUpdate =
2919 StructuredList && StructuredList->isStringLiteralInit();
2920 if (IsStringLiteralInitUpdate && VerifyOnly) {
2921 // We're just verifying an update to a string literal init. We don't need
2922 // to split the string up into individual characters to do that.
2923 StructuredList = nullptr;
2924 } else if (IsStringLiteralInitUpdate) {
2925 // We're modifying a string literal init; we have to decompose the string
2926 // so we can modify the individual characters.
2927 ASTContext &Context = SemaRef.Context;
2928 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
2929
2930 // Compute the character type
2931 QualType CharTy = AT->getElementType();
2932
2933 // Compute the type of the integer literals.
2934 QualType PromotedCharTy = CharTy;
2935 if (CharTy->isPromotableIntegerType())
2936 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2937 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2938
2939 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2940 // Get the length of the string.
2941 uint64_t StrLen = SL->getLength();
2942 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2943 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2944 StructuredList->resizeInits(Context, StrLen);
2945
2946 // Build a literal for each character in the string, and put them into
2947 // the init list.
2948 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2949 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2950 Expr *Init = new (Context) IntegerLiteral(
2951 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2952 if (CharTy != PromotedCharTy)
2953 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2954 Init, nullptr, VK_PRValue,
2955 FPOptionsOverride());
2956 StructuredList->updateInit(Context, i, Init);
2957 }
2958 } else {
2959 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2960 std::string Str;
2961 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2962
2963 // Get the length of the string.
2964 uint64_t StrLen = Str.size();
2965 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2966 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2967 StructuredList->resizeInits(Context, StrLen);
2968
2969 // Build a literal for each character in the string, and put them into
2970 // the init list.
2971 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2972 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2973 Expr *Init = new (Context) IntegerLiteral(
2974 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2975 if (CharTy != PromotedCharTy)
2976 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2977 Init, nullptr, VK_PRValue,
2978 FPOptionsOverride());
2979 StructuredList->updateInit(Context, i, Init);
2980 }
2981 }
2982 }
2983
2984 // Make sure that our non-designated initializer list has space
2985 // for a subobject corresponding to this array element.
2986 if (StructuredList &&
2987 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2988 StructuredList->resizeInits(SemaRef.Context,
2989 DesignatedEndIndex.getZExtValue() + 1);
2990
2991 // Repeatedly perform subobject initializations in the range
2992 // [DesignatedStartIndex, DesignatedEndIndex].
2993
2994 // Move to the next designator
2995 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2996 unsigned OldIndex = Index;
2997
2998 InitializedEntity ElementEntity =
2999 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3000
3001 while (DesignatedStartIndex <= DesignatedEndIndex) {
3002 // Recurse to check later designated subobjects.
3003 QualType ElementType = AT->getElementType();
3004 Index = OldIndex;
3005
3006 ElementEntity.setElementIndex(ElementIndex);
3007 if (CheckDesignatedInitializer(
3008 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3009 nullptr, Index, StructuredList, ElementIndex,
3010 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3011 false))
3012 return true;
3013
3014 // Move to the next index in the array that we'll be initializing.
3015 ++DesignatedStartIndex;
3016 ElementIndex = DesignatedStartIndex.getZExtValue();
3017 }
3018
3019 // If this the first designator, our caller will continue checking
3020 // the rest of this array subobject.
3021 if (IsFirstDesignator) {
3022 if (NextElementIndex)
3023 *NextElementIndex = DesignatedStartIndex;
3024 StructuredIndex = ElementIndex;
3025 return false;
3026 }
3027
3028 if (!FinishSubobjectInit)
3029 return false;
3030
3031 // Check the remaining elements within this array subobject.
3032 bool prevHadError = hadError;
3033 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3034 /*SubobjectIsDesignatorContext=*/false, Index,
3035 StructuredList, ElementIndex);
3036 return hadError && !prevHadError;
3037}
3038
3039// Get the structured initializer list for a subobject of type
3040// @p CurrentObjectType.
3041InitListExpr *
3042InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3043 QualType CurrentObjectType,
3044 InitListExpr *StructuredList,
3045 unsigned StructuredIndex,
3046 SourceRange InitRange,
3047 bool IsFullyOverwritten) {
3048 if (!StructuredList)
3049 return nullptr;
3050
3051 Expr *ExistingInit = nullptr;
3052 if (StructuredIndex < StructuredList->getNumInits())
3053 ExistingInit = StructuredList->getInit(StructuredIndex);
3054
3055 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3056 // There might have already been initializers for subobjects of the current
3057 // object, but a subsequent initializer list will overwrite the entirety
3058 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3059 //
3060 // struct P { char x[6]; };
3061 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3062 //
3063 // The first designated initializer is ignored, and l.x is just "f".
3064 if (!IsFullyOverwritten)
3065 return Result;
3066
3067 if (ExistingInit) {
3068 // We are creating an initializer list that initializes the
3069 // subobjects of the current object, but there was already an
3070 // initialization that completely initialized the current
3071 // subobject:
3072 //
3073 // struct X { int a, b; };
3074 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3075 //
3076 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3077 // designated initializer overwrites the [0].b initializer
3078 // from the prior initialization.
3079 //
3080 // When the existing initializer is an expression rather than an
3081 // initializer list, we cannot decompose and update it in this way.
3082 // For example:
3083 //
3084 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3085 //
3086 // This case is handled by CheckDesignatedInitializer.
3087 diagnoseInitOverride(ExistingInit, InitRange);
3088 }
3089
3090 unsigned ExpectedNumInits = 0;
3091 if (Index < IList->getNumInits()) {
3092 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3093 ExpectedNumInits = Init->getNumInits();
3094 else
3095 ExpectedNumInits = IList->getNumInits() - Index;
3096 }
3097
3098 InitListExpr *Result =
3099 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3100
3101 // Link this new initializer list into the structured initializer
3102 // lists.
3103 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3104 return Result;
3105}
3106
3107InitListExpr *
3108InitListChecker::createInitListExpr(QualType CurrentObjectType,
3109 SourceRange InitRange,
3110 unsigned ExpectedNumInits) {
3111 InitListExpr *Result
3112 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
3113 InitRange.getBegin(), None,
3114 InitRange.getEnd());
3115
3116 QualType ResultType = CurrentObjectType;
3117 if (!ResultType->isArrayType())
3118 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3119 Result->setType(ResultType);
3120
3121 // Pre-allocate storage for the structured initializer list.
3122 unsigned NumElements = 0;
3123
3124 if (const ArrayType *AType
3125 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3126 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3127 NumElements = CAType->getSize().getZExtValue();
3128 // Simple heuristic so that we don't allocate a very large
3129 // initializer with many empty entries at the end.
3130 if (NumElements > ExpectedNumInits)
3131 NumElements = 0;
3132 }
3133 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3134 NumElements = VType->getNumElements();
3135 } else if (CurrentObjectType->isRecordType()) {
3136 NumElements = numStructUnionElements(CurrentObjectType);
3137 }
3138
3139 Result->reserveInits(SemaRef.Context, NumElements);
3140
3141 return Result;
3142}
3143
3144/// Update the initializer at index @p StructuredIndex within the
3145/// structured initializer list to the value @p expr.
3146void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3147 unsigned &StructuredIndex,
3148 Expr *expr) {
3149 // No structured initializer list to update
3150 if (!StructuredList)
3151 return;
3152
3153 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3154 StructuredIndex, expr)) {
3155 // This initializer overwrites a previous initializer.
3156 // No need to diagnose when `expr` is nullptr because a more relevant
3157 // diagnostic has already been issued and this diagnostic is potentially
3158 // noise.
3159 if (expr)
3160 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3161 }
3162
3163 ++StructuredIndex;
3164}
3165
3166/// Determine whether we can perform aggregate initialization for the purposes
3167/// of overload resolution.
3168bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3169 const InitializedEntity &Entity, InitListExpr *From) {
3170 QualType Type = Entity.getType();
3171 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3172 /*TreatUnavailableAsInvalid=*/false,
3173 /*InOverloadResolution=*/true);
3174 return !Check.HadError();
3175}
3176
3177/// Check that the given Index expression is a valid array designator
3178/// value. This is essentially just a wrapper around
3179/// VerifyIntegerConstantExpression that also checks for negative values
3180/// and produces a reasonable diagnostic if there is a
3181/// failure. Returns the index expression, possibly with an implicit cast
3182/// added, on success. If everything went okay, Value will receive the
3183/// value of the constant expression.
3184static ExprResult
3185CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3186 SourceLocation Loc = Index->getBeginLoc();
3187
3188 // Make sure this is an integer constant expression.
3189 ExprResult Result =
3190 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3191 if (Result.isInvalid())
3192 return Result;
3193
3194 if (Value.isSigned() && Value.isNegative())
3195 return S.Diag(Loc, diag::err_array_designator_negative)
3196 << toString(Value, 10) << Index->getSourceRange();
3197
3198 Value.setIsUnsigned(true);
3199 return Result;
3200}
3201
3202ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3203 SourceLocation EqualOrColonLoc,
3204 bool GNUSyntax,
3205 ExprResult Init) {
3206 typedef DesignatedInitExpr::Designator ASTDesignator;
3207
3208 bool Invalid = false;
3209 SmallVector<ASTDesignator, 32> Designators;
3210 SmallVector<Expr *, 32> InitExpressions;
3211
3212 // Build designators and check array designator expressions.
3213 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3214 const Designator &D = Desig.getDesignator(Idx);
3215 switch (D.getKind()) {
3216 case Designator::FieldDesignator:
3217 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
3218 D.getFieldLoc()));
3219 break;
3220
3221 case Designator::ArrayDesignator: {
3222 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3223 llvm::APSInt IndexValue;
3224 if (!Index->isTypeDependent() && !Index->isValueDependent())
3225 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3226 if (!Index)
3227 Invalid = true;
3228 else {
3229 Designators.push_back(ASTDesignator(InitExpressions.size(),
3230 D.getLBracketLoc(),
3231 D.getRBracketLoc()));
3232 InitExpressions.push_back(Index);
3233 }
3234 break;
3235 }
3236
3237 case Designator::ArrayRangeDesignator: {
3238 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3239 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3240 llvm::APSInt StartValue;
3241 llvm::APSInt EndValue;
3242 bool StartDependent = StartIndex->isTypeDependent() ||
3243 StartIndex->isValueDependent();
3244 bool EndDependent = EndIndex->isTypeDependent() ||
3245 EndIndex->isValueDependent();
3246 if (!StartDependent)
3247 StartIndex =
3248 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3249 if (!EndDependent)
3250 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3251
3252 if (!StartIndex || !EndIndex)
3253 Invalid = true;
3254 else {
3255 // Make sure we're comparing values with the same bit width.
3256 if (StartDependent || EndDependent) {
3257 // Nothing to compute.
3258 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3259 EndValue = EndValue.extend(StartValue.getBitWidth());
3260 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3261 StartValue = StartValue.extend(EndValue.getBitWidth());
3262
3263 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3264 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3265 << toString(StartValue, 10) << toString(EndValue, 10)
3266 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3267 Invalid = true;
3268 } else {
3269 Designators.push_back(ASTDesignator(InitExpressions.size(),
3270 D.getLBracketLoc(),
3271 D.getEllipsisLoc(),
3272 D.getRBracketLoc()));
3273 InitExpressions.push_back(StartIndex);
3274 InitExpressions.push_back(EndIndex);
3275 }
3276 }
3277 break;
3278 }
3279 }
3280 }
3281
3282 if (Invalid || Init.isInvalid())
3283 return ExprError();
3284
3285 // Clear out the expressions within the designation.
3286 Desig.ClearExprs(*this);
3287
3288 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3289 EqualOrColonLoc, GNUSyntax,
3290 Init.getAs<Expr>());
3291}
3292
3293//===----------------------------------------------------------------------===//
3294// Initialization entity
3295//===----------------------------------------------------------------------===//
3296
3297InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3298 const InitializedEntity &Parent)
3299 : Parent(&Parent), Index(Index)
3300{
3301 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3302 Kind = EK_ArrayElement;
3303 Type = AT->getElementType();
3304 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3305 Kind = EK_VectorElement;
3306 Type = VT->getElementType();
3307 } else {
3308 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3309 assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ?
void (0) : __assert_fail ("CT && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 3309, __extension__ __PRETTY_FUNCTION__
))
;
3310 Kind = EK_ComplexElement;
3311 Type = CT->getElementType();
3312 }
3313}
3314
3315InitializedEntity
3316InitializedEntity::InitializeBase(ASTContext &Context,
3317 const CXXBaseSpecifier *Base,
3318 bool IsInheritedVirtualBase,
3319 const InitializedEntity *Parent) {
3320 InitializedEntity Result;
3321 Result.Kind = EK_Base;
3322 Result.Parent = Parent;
3323 Result.Base = {Base, IsInheritedVirtualBase};
3324 Result.Type = Base->getType();
3325 return Result;
3326}
3327
3328DeclarationName InitializedEntity::getName() const {
3329 switch (getKind()) {
3330 case EK_Parameter:
3331 case EK_Parameter_CF_Audited: {
3332 ParmVarDecl *D = Parameter.getPointer();
3333 return (D ? D->getDeclName() : DeclarationName());
3334 }
3335
3336 case EK_Variable:
3337 case EK_Member:
3338 case EK_Binding:
3339 case EK_TemplateParameter:
3340 return Variable.VariableOrMember->getDeclName();
3341
3342 case EK_LambdaCapture:
3343 return DeclarationName(Capture.VarID);
3344
3345 case EK_Result:
3346 case EK_StmtExprResult:
3347 case EK_Exception:
3348 case EK_New:
3349 case EK_Temporary:
3350 case EK_Base:
3351 case EK_Delegating:
3352 case EK_ArrayElement:
3353 case EK_VectorElement:
3354 case EK_ComplexElement:
3355 case EK_BlockElement:
3356 case EK_LambdaToBlockConversionBlockElement:
3357 case EK_CompoundLiteralInit:
3358 case EK_RelatedResult:
3359 return DeclarationName();
3360 }
3361
3362 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3362)
;
3363}
3364
3365ValueDecl *InitializedEntity::getDecl() const {
3366 switch (getKind()) {
3367 case EK_Variable:
3368 case EK_Member:
3369 case EK_Binding:
3370 case EK_TemplateParameter:
3371 return Variable.VariableOrMember;
3372
3373 case EK_Parameter:
3374 case EK_Parameter_CF_Audited:
3375 return Parameter.getPointer();
3376
3377 case EK_Result:
3378 case EK_StmtExprResult:
3379 case EK_Exception:
3380 case EK_New:
3381 case EK_Temporary:
3382 case EK_Base:
3383 case EK_Delegating:
3384 case EK_ArrayElement:
3385 case EK_VectorElement:
3386 case EK_ComplexElement:
3387 case EK_BlockElement:
3388 case EK_LambdaToBlockConversionBlockElement:
3389 case EK_LambdaCapture:
3390 case EK_CompoundLiteralInit:
3391 case EK_RelatedResult:
3392 return nullptr;
3393 }
3394
3395 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3395)
;
3396}
3397
3398bool InitializedEntity::allowsNRVO() const {
3399 switch (getKind()) {
3400 case EK_Result:
3401 case EK_Exception:
3402 return LocAndNRVO.NRVO;
3403
3404 case EK_StmtExprResult:
3405 case EK_Variable:
3406 case EK_Parameter:
3407 case EK_Parameter_CF_Audited:
3408 case EK_TemplateParameter:
3409 case EK_Member:
3410 case EK_Binding:
3411 case EK_New:
3412 case EK_Temporary:
3413 case EK_CompoundLiteralInit:
3414 case EK_Base:
3415 case EK_Delegating:
3416 case EK_ArrayElement:
3417 case EK_VectorElement:
3418 case EK_ComplexElement:
3419 case EK_BlockElement:
3420 case EK_LambdaToBlockConversionBlockElement:
3421 case EK_LambdaCapture:
3422 case EK_RelatedResult:
3423 break;
3424 }
3425
3426 return false;
3427}
3428
3429unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3430 assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail
("getParent() != this", "clang/lib/Sema/SemaInit.cpp", 3430,
__extension__ __PRETTY_FUNCTION__))
;
3431 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3432 for (unsigned I = 0; I != Depth; ++I)
3433 OS << "`-";
3434
3435 switch (getKind()) {
3436 case EK_Variable: OS << "Variable"; break;
3437 case EK_Parameter: OS << "Parameter"; break;
3438 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3439 break;
3440 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3441 case EK_Result: OS << "Result"; break;
3442 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3443 case EK_Exception: OS << "Exception"; break;
3444 case EK_Member: OS << "Member"; break;
3445 case EK_Binding: OS << "Binding"; break;
3446 case EK_New: OS << "New"; break;
3447 case EK_Temporary: OS << "Temporary"; break;
3448 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3449 case EK_RelatedResult: OS << "RelatedResult"; break;
3450 case EK_Base: OS << "Base"; break;
3451 case EK_Delegating: OS << "Delegating"; break;
3452 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3453 case EK_VectorElement: OS << "VectorElement " << Index; break;
3454 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3455 case EK_BlockElement: OS << "Block"; break;
3456 case EK_LambdaToBlockConversionBlockElement:
3457 OS << "Block (lambda)";
3458 break;
3459 case EK_LambdaCapture:
3460 OS << "LambdaCapture ";
3461 OS << DeclarationName(Capture.VarID);
3462 break;
3463 }
3464
3465 if (auto *D = getDecl()) {
3466 OS << " ";
3467 D->printQualifiedName(OS);
3468 }
3469
3470 OS << " '" << getType().getAsString() << "'\n";
3471
3472 return Depth + 1;
3473}
3474
3475LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const {
3476 dumpImpl(llvm::errs());
3477}
3478
3479//===----------------------------------------------------------------------===//
3480// Initialization sequence
3481//===----------------------------------------------------------------------===//
3482
3483void InitializationSequence::Step::Destroy() {
3484 switch (Kind) {
3485 case SK_ResolveAddressOfOverloadedFunction:
3486 case SK_CastDerivedToBasePRValue:
3487 case SK_CastDerivedToBaseXValue:
3488 case SK_CastDerivedToBaseLValue:
3489 case SK_BindReference:
3490 case SK_BindReferenceToTemporary:
3491 case SK_FinalCopy:
3492 case SK_ExtraneousCopyToTemporary:
3493 case SK_UserConversion:
3494 case SK_QualificationConversionPRValue:
3495 case SK_QualificationConversionXValue:
3496 case SK_QualificationConversionLValue:
3497 case SK_FunctionReferenceConversion:
3498 case SK_AtomicConversion:
3499 case SK_ListInitialization:
3500 case SK_UnwrapInitList:
3501 case SK_RewrapInitList:
3502 case SK_ConstructorInitialization:
3503 case SK_ConstructorInitializationFromList:
3504 case SK_ZeroInitialization:
3505 case SK_CAssignment:
3506 case SK_StringInit:
3507 case SK_ObjCObjectConversion:
3508 case SK_ArrayLoopIndex:
3509 case SK_ArrayLoopInit:
3510 case SK_ArrayInit:
3511 case SK_GNUArrayInit:
3512 case SK_ParenthesizedArrayInit:
3513 case SK_PassByIndirectCopyRestore:
3514 case SK_PassByIndirectRestore:
3515 case SK_ProduceObjCObject:
3516 case SK_StdInitializerList:
3517 case SK_StdInitializerListConstructorCall:
3518 case SK_OCLSamplerInit:
3519 case SK_OCLZeroOpaqueType:
3520 break;
3521
3522 case SK_ConversionSequence:
3523 case SK_ConversionSequenceNoNarrowing:
3524 delete ICS;
3525 }
3526}
3527
3528bool InitializationSequence::isDirectReferenceBinding() const {
3529 // There can be some lvalue adjustments after the SK_BindReference step.
3530 for (const Step &S : llvm::reverse(Steps)) {
3531 if (S.Kind == SK_BindReference)
3532 return true;
3533 if (S.Kind == SK_BindReferenceToTemporary)
3534 return false;
3535 }
3536 return false;
3537}
3538
3539bool InitializationSequence::isAmbiguous() const {
3540 if (!Failed())
3541 return false;
3542
3543 switch (getFailureKind()) {
3544 case FK_TooManyInitsForReference:
3545 case FK_ParenthesizedListInitForReference:
3546 case FK_ArrayNeedsInitList:
3547 case FK_ArrayNeedsInitListOrStringLiteral:
3548 case FK_ArrayNeedsInitListOrWideStringLiteral:
3549 case FK_NarrowStringIntoWideCharArray:
3550 case FK_WideStringIntoCharArray:
3551 case FK_IncompatWideStringIntoWideChar:
3552 case FK_PlainStringIntoUTF8Char:
3553 case FK_UTF8StringIntoPlainChar:
3554 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3555 case FK_NonConstLValueReferenceBindingToTemporary:
3556 case FK_NonConstLValueReferenceBindingToBitfield:
3557 case FK_NonConstLValueReferenceBindingToVectorElement:
3558 case FK_NonConstLValueReferenceBindingToMatrixElement:
3559 case FK_NonConstLValueReferenceBindingToUnrelated:
3560 case FK_RValueReferenceBindingToLValue:
3561 case FK_ReferenceAddrspaceMismatchTemporary:
3562 case FK_ReferenceInitDropsQualifiers:
3563 case FK_ReferenceInitFailed:
3564 case FK_ConversionFailed:
3565 case FK_ConversionFromPropertyFailed:
3566 case FK_TooManyInitsForScalar:
3567 case FK_ParenthesizedListInitForScalar:
3568 case FK_ReferenceBindingToInitList:
3569 case FK_InitListBadDestinationType:
3570 case FK_DefaultInitOfConst:
3571 case FK_Incomplete:
3572 case FK_ArrayTypeMismatch:
3573 case FK_NonConstantArrayInit:
3574 case FK_ListInitializationFailed:
3575 case FK_VariableLengthArrayHasInitializer:
3576 case FK_PlaceholderType:
3577 case FK_ExplicitConstructor:
3578 case FK_AddressOfUnaddressableFunction:
3579 return false;
3580
3581 case FK_ReferenceInitOverloadFailed:
3582 case FK_UserConversionOverloadFailed:
3583 case FK_ConstructorOverloadFailed:
3584 case FK_ListConstructorOverloadFailed:
3585 return FailedOverloadResult == OR_Ambiguous;
3586 }
3587
3588 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3588)
;
3589}
3590
3591bool InitializationSequence::isConstructorInitialization() const {
3592 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3593}
3594
3595void
3596InitializationSequence
3597::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3598 DeclAccessPair Found,
3599 bool HadMultipleCandidates) {
3600 Step S;
3601 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3602 S.Type = Function->getType();
3603 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3604 S.Function.Function = Function;
3605 S.Function.FoundDecl = Found;
3606 Steps.push_back(S);
3607}
3608
3609void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3610 ExprValueKind VK) {
3611 Step S;
3612 switch (VK) {
3613 case VK_PRValue:
3614 S.Kind = SK_CastDerivedToBasePRValue;
3615 break;
3616 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3617 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3618 }
3619 S.Type = BaseType;
3620 Steps.push_back(S);
3621}
3622
3623void InitializationSequence::AddReferenceBindingStep(QualType T,
3624 bool BindingTemporary) {
3625 Step S;
3626 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3627 S.Type = T;
3628 Steps.push_back(S);
3629}
3630
3631void InitializationSequence::AddFinalCopy(QualType T) {
3632 Step S;
3633 S.Kind = SK_FinalCopy;
3634 S.Type = T;
3635 Steps.push_back(S);
3636}
3637
3638void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3639 Step S;
3640 S.Kind = SK_ExtraneousCopyToTemporary;
3641 S.Type = T;
3642 Steps.push_back(S);
3643}
3644
3645void
3646InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3647 DeclAccessPair FoundDecl,
3648 QualType T,
3649 bool HadMultipleCandidates) {
3650 Step S;
3651 S.Kind = SK_UserConversion;
3652 S.Type = T;
3653 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3654 S.Function.Function = Function;
3655 S.Function.FoundDecl = FoundDecl;
3656 Steps.push_back(S);
3657}
3658
3659void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3660 ExprValueKind VK) {
3661 Step S;
3662 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3663 switch (VK) {
3664 case VK_PRValue:
3665 S.Kind = SK_QualificationConversionPRValue;
3666 break;
3667 case VK_XValue:
3668 S.Kind = SK_QualificationConversionXValue;
3669 break;
3670 case VK_LValue:
3671 S.Kind = SK_QualificationConversionLValue;
3672 break;
3673 }
3674 S.Type = Ty;
3675 Steps.push_back(S);
3676}
3677
3678void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3679 Step S;
3680 S.Kind = SK_FunctionReferenceConversion;
3681 S.Type = Ty;
3682 Steps.push_back(S);
3683}
3684
3685void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3686 Step S;
3687 S.Kind = SK_AtomicConversion;
3688 S.Type = Ty;
3689 Steps.push_back(S);
3690}
3691
3692void InitializationSequence::AddConversionSequenceStep(
3693 const ImplicitConversionSequence &ICS, QualType T,
3694 bool TopLevelOfInitList) {
3695 Step S;
3696 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3697 : SK_ConversionSequence;
3698 S.Type = T;
3699 S.ICS = new ImplicitConversionSequence(ICS);
3700 Steps.push_back(S);
3701}
3702
3703void InitializationSequence::AddListInitializationStep(QualType T) {
3704 Step S;
3705 S.Kind = SK_ListInitialization;
3706 S.Type = T;
3707 Steps.push_back(S);
3708}
3709
3710void InitializationSequence::AddConstructorInitializationStep(
3711 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3712 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3713 Step S;
3714 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3715 : SK_ConstructorInitializationFromList
3716 : SK_ConstructorInitialization;
3717 S.Type = T;
3718 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3719 S.Function.Function = Constructor;
3720 S.Function.FoundDecl = FoundDecl;
3721 Steps.push_back(S);
3722}
3723
3724void InitializationSequence::AddZeroInitializationStep(QualType T) {
3725 Step S;
3726 S.Kind = SK_ZeroInitialization;
3727 S.Type = T;
3728 Steps.push_back(S);
3729}
3730
3731void InitializationSequence::AddCAssignmentStep(QualType T) {
3732 Step S;
3733 S.Kind = SK_CAssignment;
3734 S.Type = T;
3735 Steps.push_back(S);
3736}
3737
3738void InitializationSequence::AddStringInitStep(QualType T) {
3739 Step S;
3740 S.Kind = SK_StringInit;
3741 S.Type = T;
3742 Steps.push_back(S);
3743}
3744
3745void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3746 Step S;
3747 S.Kind = SK_ObjCObjectConversion;
3748 S.Type = T;
3749 Steps.push_back(S);
3750}
3751
3752void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3753 Step S;
3754 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3755 S.Type = T;
3756 Steps.push_back(S);
3757}
3758
3759void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3760 Step S;
3761 S.Kind = SK_ArrayLoopIndex;
3762 S.Type = EltT;
3763 Steps.insert(Steps.begin(), S);
3764
3765 S.Kind = SK_ArrayLoopInit;
3766 S.Type = T;
3767 Steps.push_back(S);
3768}
3769
3770void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3771 Step S;
3772 S.Kind = SK_ParenthesizedArrayInit;
3773 S.Type = T;
3774 Steps.push_back(S);
3775}
3776
3777void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3778 bool shouldCopy) {
3779 Step s;
3780 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3781 : SK_PassByIndirectRestore);
3782 s.Type = type;
3783 Steps.push_back(s);
3784}
3785
3786void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3787 Step S;
3788 S.Kind = SK_ProduceObjCObject;
3789 S.Type = T;
3790 Steps.push_back(S);
3791}
3792
3793void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3794 Step S;
3795 S.Kind = SK_StdInitializerList;
3796 S.Type = T;
3797 Steps.push_back(S);
3798}
3799
3800void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3801 Step S;
3802 S.Kind = SK_OCLSamplerInit;
3803 S.Type = T;
3804 Steps.push_back(S);
3805}
3806
3807void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3808 Step S;
3809 S.Kind = SK_OCLZeroOpaqueType;
3810 S.Type = T;
3811 Steps.push_back(S);
3812}
3813
3814void InitializationSequence::RewrapReferenceInitList(QualType T,
3815 InitListExpr *Syntactic) {
3816 assert(Syntactic->getNumInits() == 1 &&(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "clang/lib/Sema/SemaInit.cpp", 3817, __extension__ __PRETTY_FUNCTION__
))
3817 "Can only rewrap trivial init lists.")(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "clang/lib/Sema/SemaInit.cpp", 3817, __extension__ __PRETTY_FUNCTION__
))
;
3818 Step S;
3819 S.Kind = SK_UnwrapInitList;
3820 S.Type = Syntactic->getInit(0)->getType();
3821 Steps.insert(Steps.begin(), S);
3822
3823 S.Kind = SK_RewrapInitList;
3824 S.Type = T;
3825 S.WrappingSyntacticList = Syntactic;
3826 Steps.push_back(S);
3827}
3828
3829void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3830 OverloadingResult Result) {
3831 setSequenceKind(FailedSequence);
3832 this->Failure = Failure;
3833 this->FailedOverloadResult = Result;
3834}
3835
3836//===----------------------------------------------------------------------===//
3837// Attempt initialization
3838//===----------------------------------------------------------------------===//
3839
3840/// Tries to add a zero initializer. Returns true if that worked.
3841static bool
3842maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3843 const InitializedEntity &Entity) {
3844 if (Entity.getKind() != InitializedEntity::EK_Variable)
3845 return false;
3846
3847 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3848 if (VD->getInit() || VD->getEndLoc().isMacroID())
3849 return false;
3850
3851 QualType VariableTy = VD->getType().getCanonicalType();
3852 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3853 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3854 if (!Init.empty()) {
3855 Sequence.AddZeroInitializationStep(Entity.getType());
3856 Sequence.SetZeroInitializationFixit(Init, Loc);
3857 return true;
3858 }
3859 return false;
3860}
3861
3862static void MaybeProduceObjCObject(Sema &S,
3863 InitializationSequence &Sequence,
3864 const InitializedEntity &Entity) {
3865 if (!S.getLangOpts().ObjCAutoRefCount) return;
3866
3867 /// When initializing a parameter, produce the value if it's marked
3868 /// __attribute__((ns_consumed)).
3869 if (Entity.isParameterKind()) {
3870 if (!Entity.isParameterConsumed())
3871 return;
3872
3873 assert(Entity.getType()->isObjCRetainableType() &&(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "clang/lib/Sema/SemaInit.cpp", 3874, __extension__ __PRETTY_FUNCTION__
))
3874 "consuming an object of unretainable type?")(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "clang/lib/Sema/SemaInit.cpp", 3874, __extension__ __PRETTY_FUNCTION__
))
;
3875 Sequence.AddProduceObjCObjectStep(Entity.getType());
3876
3877 /// When initializing a return value, if the return type is a
3878 /// retainable type, then returns need to immediately retain the
3879 /// object. If an autorelease is required, it will be done at the
3880 /// last instant.
3881 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3882 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
3883 if (!Entity.getType()->isObjCRetainableType())
3884 return;
3885
3886 Sequence.AddProduceObjCObjectStep(Entity.getType());
3887 }
3888}
3889
3890static void TryListInitialization(Sema &S,
3891 const InitializedEntity &Entity,
3892 const InitializationKind &Kind,
3893 InitListExpr *InitList,
3894 InitializationSequence &Sequence,
3895 bool TreatUnavailableAsInvalid);
3896
3897/// When initializing from init list via constructor, handle
3898/// initialization of an object of type std::initializer_list<T>.
3899///
3900/// \return true if we have handled initialization of an object of type
3901/// std::initializer_list<T>, false otherwise.
3902static bool TryInitializerListConstruction(Sema &S,
3903 InitListExpr *List,
3904 QualType DestType,
3905 InitializationSequence &Sequence,
3906 bool TreatUnavailableAsInvalid) {
3907 QualType E;
3908 if (!S.isStdInitializerList(DestType, &E))
3909 return false;
3910
3911 if (!S.isCompleteType(List->getExprLoc(), E)) {
3912 Sequence.setIncompleteTypeFailure(E);
3913 return true;
3914 }
3915
3916 // Try initializing a temporary array from the init list.
3917 QualType ArrayType = S.Context.getConstantArrayType(
3918 E.withConst(),
3919 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3920 List->getNumInits()),
3921 nullptr, clang::ArrayType::Normal, 0);
3922 InitializedEntity HiddenArray =
3923 InitializedEntity::InitializeTemporary(ArrayType);
3924 InitializationKind Kind = InitializationKind::CreateDirectList(
3925 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3926 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3927 TreatUnavailableAsInvalid);
3928 if (Sequence)
3929 Sequence.AddStdInitializerListConstructionStep(DestType);
3930 return true;
3931}
3932
3933/// Determine if the constructor has the signature of a copy or move
3934/// constructor for the type T of the class in which it was found. That is,
3935/// determine if its first parameter is of type T or reference to (possibly
3936/// cv-qualified) T.
3937static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3938 const ConstructorInfo &Info) {
3939 if (Info.Constructor->getNumParams() == 0)
3940 return false;
3941
3942 QualType ParmT =
3943 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3944 QualType ClassT =
3945 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3946
3947 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3948}
3949
3950static OverloadingResult
3951ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3952 MultiExprArg Args,
3953 OverloadCandidateSet &CandidateSet,
3954 QualType DestType,
3955 DeclContext::lookup_result Ctors,
3956 OverloadCandidateSet::iterator &Best,
3957 bool CopyInitializing, bool AllowExplicit,
3958 bool OnlyListConstructors, bool IsListInit,
3959 bool SecondStepOfCopyInit = false) {
3960 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3961 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
3962
3963 for (NamedDecl *D : Ctors) {
3964 auto Info = getConstructorInfo(D);
3965 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3966 continue;
3967
3968 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3969 continue;
3970
3971 // C++11 [over.best.ics]p4:
3972 // ... and the constructor or user-defined conversion function is a
3973 // candidate by
3974 // - 13.3.1.3, when the argument is the temporary in the second step
3975 // of a class copy-initialization, or
3976 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3977 // - the second phase of 13.3.1.7 when the initializer list has exactly
3978 // one element that is itself an initializer list, and the target is
3979 // the first parameter of a constructor of class X, and the conversion
3980 // is to X or reference to (possibly cv-qualified X),
3981 // user-defined conversion sequences are not considered.
3982 bool SuppressUserConversions =
3983 SecondStepOfCopyInit ||
3984 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3985 hasCopyOrMoveCtorParam(S.Context, Info));
3986
3987 if (Info.ConstructorTmpl)
3988 S.AddTemplateOverloadCandidate(
3989 Info.ConstructorTmpl, Info.FoundDecl,
3990 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3991 /*PartialOverloading=*/false, AllowExplicit);
3992 else {
3993 // C++ [over.match.copy]p1:
3994 // - When initializing a temporary to be bound to the first parameter
3995 // of a constructor [for type T] that takes a reference to possibly
3996 // cv-qualified T as its first argument, called with a single
3997 // argument in the context of direct-initialization, explicit
3998 // conversion functions are also considered.
3999 // FIXME: What if a constructor template instantiates to such a signature?
4000 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4001 Args.size() == 1 &&
4002 hasCopyOrMoveCtorParam(S.Context, Info);
4003 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4004 CandidateSet, SuppressUserConversions,
4005 /*PartialOverloading=*/false, AllowExplicit,
4006 AllowExplicitConv);
4007 }
4008 }
4009
4010 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4011 //
4012 // When initializing an object of class type T by constructor
4013 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4014 // from a single expression of class type U, conversion functions of
4015 // U that convert to the non-reference type cv T are candidates.
4016 // Explicit conversion functions are only candidates during
4017 // direct-initialization.
4018 //
4019 // Note: SecondStepOfCopyInit is only ever true in this case when
4020 // evaluating whether to produce a C++98 compatibility warning.
4021 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4022 !SecondStepOfCopyInit) {
4023 Expr *Initializer = Args[0];
4024 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4025 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4026 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4027 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4028 NamedDecl *D = *I;
4029 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4030 D = D->getUnderlyingDecl();
4031
4032 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4033 CXXConversionDecl *Conv;
4034 if (ConvTemplate)
4035 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4036 else
4037 Conv = cast<CXXConversionDecl>(D);
4038
4039 if (ConvTemplate)
4040 S.AddTemplateConversionCandidate(
4041 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4042 CandidateSet, AllowExplicit, AllowExplicit,
4043 /*AllowResultConversion*/ false);
4044 else
4045 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4046 DestType, CandidateSet, AllowExplicit,
4047 AllowExplicit,
4048 /*AllowResultConversion*/ false);
4049 }
4050 }
4051 }
4052
4053 // Perform overload resolution and return the result.
4054 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4055}
4056
4057/// Attempt initialization by constructor (C++ [dcl.init]), which
4058/// enumerates the constructors of the initialized entity and performs overload
4059/// resolution to select the best.
4060/// \param DestType The destination class type.
4061/// \param DestArrayType The destination type, which is either DestType or
4062/// a (possibly multidimensional) array of DestType.
4063/// \param IsListInit Is this list-initialization?
4064/// \param IsInitListCopy Is this non-list-initialization resulting from a
4065/// list-initialization from {x} where x is the same
4066/// type as the entity?
4067static void TryConstructorInitialization(Sema &S,
4068 const InitializedEntity &Entity,
4069 const InitializationKind &Kind,
4070 MultiExprArg Args, QualType DestType,
4071 QualType DestArrayType,
4072 InitializationSequence &Sequence,
4073 bool IsListInit = false,
4074 bool IsInitListCopy = false) {
4075 assert(((!IsListInit && !IsInitListCopy) ||(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4078, __extension__ __PRETTY_FUNCTION__
))
4076 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4078, __extension__ __PRETTY_FUNCTION__
))
4077 "IsListInit/IsInitListCopy must come with a single initializer list "(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4078, __extension__ __PRETTY_FUNCTION__
))
4078 "argument.")(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4078, __extension__ __PRETTY_FUNCTION__
))
;
4079 InitListExpr *ILE =
4080 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4081 MultiExprArg UnwrappedArgs =
4082 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4083
4084 // The type we're constructing needs to be complete.
4085 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4086 Sequence.setIncompleteTypeFailure(DestType);
4087 return;
4088 }
4089
4090 // C++17 [dcl.init]p17:
4091 // - If the initializer expression is a prvalue and the cv-unqualified
4092 // version of the source type is the same class as the class of the
4093 // destination, the initializer expression is used to initialize the
4094 // destination object.
4095 // Per DR (no number yet), this does not apply when initializing a base
4096 // class or delegating to another constructor from a mem-initializer.
4097 // ObjC++: Lambda captured by the block in the lambda to block conversion
4098 // should avoid copy elision.
4099 if (S.getLangOpts().CPlusPlus17 &&
4100 Entity.getKind() != InitializedEntity::EK_Base &&
4101 Entity.getKind() != InitializedEntity::EK_Delegating &&
4102 Entity.getKind() !=
4103 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
4104 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4105 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4106 // Convert qualifications if necessary.
4107 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4108 if (ILE)
4109 Sequence.RewrapReferenceInitList(DestType, ILE);
4110 return;
4111 }
4112
4113 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4114 assert(DestRecordType && "Constructor initialization requires record type")(static_cast <bool> (DestRecordType && "Constructor initialization requires record type"
) ? void (0) : __assert_fail ("DestRecordType && \"Constructor initialization requires record type\""
, "clang/lib/Sema/SemaInit.cpp", 4114, __extension__ __PRETTY_FUNCTION__
))
;
4115 CXXRecordDecl *DestRecordDecl
4116 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4117
4118 // Build the candidate set directly in the initialization sequence
4119 // structure, so that it will persist if we fail.
4120 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4121
4122 // Determine whether we are allowed to call explicit constructors or
4123 // explicit conversion operators.
4124 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4125 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4126
4127 // - Otherwise, if T is a class type, constructors are considered. The
4128 // applicable constructors are enumerated, and the best one is chosen
4129 // through overload resolution.
4130 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4131
4132 OverloadingResult Result = OR_No_Viable_Function;
4133 OverloadCandidateSet::iterator Best;
4134 bool AsInitializerList = false;
4135
4136 // C++11 [over.match.list]p1, per DR1467:
4137 // When objects of non-aggregate type T are list-initialized, such that
4138 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4139 // according to the rules in this section, overload resolution selects
4140 // the constructor in two phases:
4141 //
4142 // - Initially, the candidate functions are the initializer-list
4143 // constructors of the class T and the argument list consists of the
4144 // initializer list as a single argument.
4145 if (IsListInit) {
4146 AsInitializerList = true;
4147
4148 // If the initializer list has no elements and T has a default constructor,
4149 // the first phase is omitted.
4150 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4151 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
4152 CandidateSet, DestType, Ctors, Best,
4153 CopyInitialization, AllowExplicit,
4154 /*OnlyListConstructors=*/true,
4155 IsListInit);
4156 }
4157
4158 // C++11 [over.match.list]p1:
4159 // - If no viable initializer-list constructor is found, overload resolution
4160 // is performed again, where the candidate functions are all the
4161 // constructors of the class T and the argument list consists of the
4162 // elements of the initializer list.
4163 if (Result == OR_No_Viable_Function) {
4164 AsInitializerList = false;
4165 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
4166 CandidateSet, DestType, Ctors, Best,
4167 CopyInitialization, AllowExplicit,
4168 /*OnlyListConstructors=*/false,
4169 IsListInit);
4170 }
4171 if (Result) {
4172 Sequence.SetOverloadFailure(
4173 IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4174 : InitializationSequence::FK_ConstructorOverloadFailed,
4175 Result);
4176
4177 if (Result != OR_Deleted)
4178 return;
4179 }
4180
4181 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4182
4183 // In C++17, ResolveConstructorOverload can select a conversion function
4184 // instead of a constructor.
4185 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4186 // Add the user-defined conversion step that calls the conversion function.
4187 QualType ConvType = CD->getConversionType();
4188 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "clang/lib/Sema/SemaInit.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
4189 "should not have selected this conversion function")(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "clang/lib/Sema/SemaInit.cpp", 4189, __extension__ __PRETTY_FUNCTION__
))
;
4190 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4191 HadMultipleCandidates);
4192 if (!S.Context.hasSameType(ConvType, DestType))
4193 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4194 if (IsListInit)
4195 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4196 return;
4197 }
4198
4199 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4200 if (Result != OR_Deleted) {
4201 // C++11 [dcl.init]p6:
4202 // If a program calls for the default initialization of an object
4203 // of a const-qualified type T, T shall be a class type with a
4204 // user-provided default constructor.
4205 // C++ core issue 253 proposal:
4206 // If the implicit default constructor initializes all subobjects, no
4207 // initializer should be required.
4208 // The 253 proposal is for example needed to process libstdc++ headers
4209 // in 5.x.
4210 if (Kind.getKind() == InitializationKind::IK_Default &&
4211 Entity.getType().isConstQualified()) {
4212 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4213 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4214 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4215 return;
4216 }
4217 }
4218
4219 // C++11 [over.match.list]p1:
4220 // In copy-list-initialization, if an explicit constructor is chosen, the
4221 // initializer is ill-formed.
4222 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4223 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4224 return;
4225 }
4226 }
4227
4228 // [class.copy.elision]p3:
4229 // In some copy-initialization contexts, a two-stage overload resolution
4230 // is performed.
4231 // If the first overload resolution selects a deleted function, we also
4232 // need the initialization sequence to decide whether to perform the second
4233 // overload resolution.
4234 // For deleted functions in other contexts, there is no need to get the
4235 // initialization sequence.
4236 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4237 return;
4238
4239 // Add the constructor initialization step. Any cv-qualification conversion is
4240 // subsumed by the initialization.
4241 Sequence.AddConstructorInitializationStep(
4242 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4243 IsListInit | IsInitListCopy, AsInitializerList);
4244}
4245
4246static bool
4247ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4248 Expr *Initializer,
4249 QualType &SourceType,
4250 QualType &UnqualifiedSourceType,
4251 QualType UnqualifiedTargetType,
4252 InitializationSequence &Sequence) {
4253 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4254 S.Context.OverloadTy) {
4255 DeclAccessPair Found;
4256 bool HadMultipleCandidates = false;
4257 if (FunctionDecl *Fn
4258 = S.ResolveAddressOfOverloadedFunction(Initializer,
4259 UnqualifiedTargetType,
4260 false, Found,
4261 &HadMultipleCandidates)) {
4262 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4263 HadMultipleCandidates);
4264 SourceType = Fn->getType();
4265 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4266 } else if (!UnqualifiedTargetType->isRecordType()) {
4267 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4268 return true;
4269 }
4270 }
4271 return false;
4272}
4273
4274static void TryReferenceInitializationCore(Sema &S,
4275 const InitializedEntity &Entity,
4276 const InitializationKind &Kind,
4277 Expr *Initializer,
4278 QualType cv1T1, QualType T1,
4279 Qualifiers T1Quals,
4280 QualType cv2T2, QualType T2,
4281 Qualifiers T2Quals,
4282 InitializationSequence &Sequence);
4283
4284static void TryValueInitialization(Sema &S,
4285 const InitializedEntity &Entity,
4286 const InitializationKind &Kind,
4287 InitializationSequence &Sequence,
4288 InitListExpr *InitList = nullptr);
4289
4290/// Attempt list initialization of a reference.
4291static void TryReferenceListInitialization(Sema &S,
4292 const InitializedEntity &Entity,
4293 const InitializationKind &Kind,
4294 InitListExpr *InitList,
4295 InitializationSequence &Sequence,
4296 bool TreatUnavailableAsInvalid) {
4297 // First, catch C++03 where this isn't possible.
4298 if (!S.getLangOpts().CPlusPlus11) {
4299 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4300 return;
4301 }
4302 // Can't reference initialize a compound literal.
4303 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4304 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4305 return;
4306 }
4307
4308 QualType DestType = Entity.getType();
4309 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4310 Qualifiers T1Quals;
4311 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4312
4313 // Reference initialization via an initializer list works thus:
4314 // If the initializer list consists of a single element that is
4315 // reference-related to the referenced type, bind directly to that element
4316 // (possibly creating temporaries).
4317 // Otherwise, initialize a temporary with the initializer list and
4318 // bind to that.
4319 if (InitList->getNumInits() == 1) {
4320 Expr *Initializer = InitList->getInit(0);
4321 QualType cv2T2 = S.getCompletedType(Initializer);
4322 Qualifiers T2Quals;
4323 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4324
4325 // If this fails, creating a temporary wouldn't work either.
4326 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4327 T1, Sequence))
4328 return;
4329
4330 SourceLocation DeclLoc = Initializer->getBeginLoc();
4331 Sema::ReferenceCompareResult RefRelationship
4332 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4333 if (RefRelationship >= Sema::Ref_Related) {
4334 // Try to bind the reference here.
4335 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4336 T1Quals, cv2T2, T2, T2Quals, Sequence);
4337 if (Sequence)
4338 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4339 return;
4340 }
4341
4342 // Update the initializer if we've resolved an overloaded function.
4343 if (Sequence.step_begin() != Sequence.step_end())
4344 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4345 }
4346 // Perform address space compatibility check.
4347 QualType cv1T1IgnoreAS = cv1T1;
4348 if (T1Quals.hasAddressSpace()) {
4349 Qualifiers T2Quals;
4350 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4351 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4352 Sequence.SetFailed(
4353 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4354 return;
4355 }
4356 // Ignore address space of reference type at this point and perform address
4357 // space conversion after the reference binding step.
4358 cv1T1IgnoreAS =
4359 S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4360 }
4361 // Not reference-related. Create a temporary and bind to that.
4362 InitializedEntity TempEntity =
4363 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4364
4365 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4366 TreatUnavailableAsInvalid);
4367 if (Sequence) {
4368 if (DestType->isRValueReferenceType() ||
4369 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4370 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4371 /*BindingTemporary=*/true);
4372 if (T1Quals.hasAddressSpace())
4373 Sequence.AddQualificationConversionStep(
4374 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4375 } else
4376 Sequence.SetFailed(
4377 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4378 }
4379}
4380
4381/// Attempt list initialization (C++0x [dcl.init.list])
4382static void TryListInitialization(Sema &S,
4383 const InitializedEntity &Entity,
4384 const InitializationKind &Kind,
4385 InitListExpr *InitList,
4386 InitializationSequence &Sequence,
4387 bool TreatUnavailableAsInvalid) {
4388 QualType DestType = Entity.getType();
4389
4390 // C++ doesn't allow scalar initialization with more than one argument.
4391 // But C99 complex numbers are scalars and it makes sense there.
4392 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4393 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4394 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4395 return;
4396 }
4397 if (DestType->isReferenceType()) {
4398 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4399 TreatUnavailableAsInvalid);
4400 return;
4401 }
4402
4403 if (DestType->isRecordType() &&
4404 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4405 Sequence.setIncompleteTypeFailure(DestType);
4406 return;
4407 }
4408
4409 // C++11 [dcl.init.list]p3, per DR1467:
4410 // - If T is a class type and the initializer list has a single element of
4411 // type cv U, where U is T or a class derived from T, the object is
4412 // initialized from that element (by copy-initialization for
4413 // copy-list-initialization, or by direct-initialization for
4414 // direct-list-initialization).
4415 // - Otherwise, if T is a character array and the initializer list has a
4416 // single element that is an appropriately-typed string literal
4417 // (8.5.2 [dcl.init.string]), initialization is performed as described
4418 // in that section.
4419 // - Otherwise, if T is an aggregate, [...] (continue below).
4420 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4421 if (DestType->isRecordType()) {
4422 QualType InitType = InitList->getInit(0)->getType();
4423 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4424 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4425 Expr *InitListAsExpr = InitList;
4426 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4427 DestType, Sequence,
4428 /*InitListSyntax*/false,
4429 /*IsInitListCopy*/true);
4430 return;
4431 }
4432 }
4433 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4434 Expr *SubInit[1] = {InitList->getInit(0)};
4435 if (!isa<VariableArrayType>(DestAT) &&
4436 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4437 InitializationKind SubKind =
4438 Kind.getKind() == InitializationKind::IK_DirectList
4439 ? InitializationKind::CreateDirect(Kind.getLocation(),
4440 InitList->getLBraceLoc(),
4441 InitList->getRBraceLoc())
4442 : Kind;
4443 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4444 /*TopLevelOfInitList*/ true,
4445 TreatUnavailableAsInvalid);
4446
4447 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4448 // the element is not an appropriately-typed string literal, in which
4449 // case we should proceed as in C++11 (below).
4450 if (Sequence) {
4451 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4452 return;
4453 }
4454 }
4455 }
4456 }
4457
4458 // C++11 [dcl.init.list]p3:
4459 // - If T is an aggregate, aggregate initialization is performed.
4460 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4461 (S.getLangOpts().CPlusPlus11 &&
4462 S.isStdInitializerList(DestType, nullptr))) {
4463 if (S.getLangOpts().CPlusPlus11) {
4464 // - Otherwise, if the initializer list has no elements and T is a
4465 // class type with a default constructor, the object is
4466 // value-initialized.
4467 if (InitList->getNumInits() == 0) {
4468 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4469 if (S.LookupDefaultConstructor(RD)) {
4470 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4471 return;
4472 }
4473 }
4474
4475 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4476 // an initializer_list object constructed [...]
4477 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4478 TreatUnavailableAsInvalid))
4479 return;
4480
4481 // - Otherwise, if T is a class type, constructors are considered.
4482 Expr *InitListAsExpr = InitList;
4483 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4484 DestType, Sequence, /*InitListSyntax*/true);
4485 } else
4486 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4487 return;
4488 }
4489
4490 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4491 InitList->getNumInits() == 1) {
4492 Expr *E = InitList->getInit(0);
4493
4494 // - Otherwise, if T is an enumeration with a fixed underlying type,
4495 // the initializer-list has a single element v, and the initialization
4496 // is direct-list-initialization, the object is initialized with the
4497 // value T(v); if a narrowing conversion is required to convert v to
4498 // the underlying type of T, the program is ill-formed.
4499 auto *ET = DestType->getAs<EnumType>();
4500 if (S.getLangOpts().CPlusPlus17 &&
4501 Kind.getKind() == InitializationKind::IK_DirectList &&
4502 ET && ET->getDecl()->isFixed() &&
4503 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4504 (E->getType()->isIntegralOrEnumerationType() ||
4505 E->getType()->isFloatingType())) {
4506 // There are two ways that T(v) can work when T is an enumeration type.
4507 // If there is either an implicit conversion sequence from v to T or
4508 // a conversion function that can convert from v to T, then we use that.
4509 // Otherwise, if v is of integral, enumeration, or floating-point type,
4510 // it is converted to the enumeration type via its underlying type.
4511 // There is no overlap possible between these two cases (except when the
4512 // source value is already of the destination type), and the first
4513 // case is handled by the general case for single-element lists below.
4514 ImplicitConversionSequence ICS;
4515 ICS.setStandard();
4516 ICS.Standard.setAsIdentityConversion();
4517 if (!E->isPRValue())
4518 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4519 // If E is of a floating-point type, then the conversion is ill-formed
4520 // due to narrowing, but go through the motions in order to produce the
4521 // right diagnostic.
4522 ICS.Standard.Second = E->getType()->isFloatingType()
4523 ? ICK_Floating_Integral
4524 : ICK_Integral_Conversion;
4525 ICS.Standard.setFromType(E->getType());
4526 ICS.Standard.setToType(0, E->getType());
4527 ICS.Standard.setToType(1, DestType);
4528 ICS.Standard.setToType(2, DestType);
4529 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4530 /*TopLevelOfInitList*/true);
4531 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4532 return;
4533 }
4534
4535 // - Otherwise, if the initializer list has a single element of type E
4536 // [...references are handled above...], the object or reference is
4537 // initialized from that element (by copy-initialization for
4538 // copy-list-initialization, or by direct-initialization for
4539 // direct-list-initialization); if a narrowing conversion is required
4540 // to convert the element to T, the program is ill-formed.
4541 //
4542 // Per core-24034, this is direct-initialization if we were performing
4543 // direct-list-initialization and copy-initialization otherwise.
4544 // We can't use InitListChecker for this, because it always performs
4545 // copy-initialization. This only matters if we might use an 'explicit'
4546 // conversion operator, or for the special case conversion of nullptr_t to
4547 // bool, so we only need to handle those cases.
4548 //
4549 // FIXME: Why not do this in all cases?
4550 Expr *Init = InitList->getInit(0);
4551 if (Init->getType()->isRecordType() ||
4552 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4553 InitializationKind SubKind =
4554 Kind.getKind() == InitializationKind::IK_DirectList
4555 ? InitializationKind::CreateDirect(Kind.getLocation(),
4556 InitList->getLBraceLoc(),
4557 InitList->getRBraceLoc())
4558 : Kind;
4559 Expr *SubInit[1] = { Init };
4560 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4561 /*TopLevelOfInitList*/true,
4562 TreatUnavailableAsInvalid);
4563 if (Sequence)
4564 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4565 return;
4566 }
4567 }
4568
4569 InitListChecker CheckInitList(S, Entity, InitList,
4570 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4571 if (CheckInitList.HadError()) {
4572 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4573 return;
4574 }
4575
4576 // Add the list initialization step with the built init list.
4577 Sequence.AddListInitializationStep(DestType);
4578}
4579
4580/// Try a reference initialization that involves calling a conversion
4581/// function.
4582static OverloadingResult TryRefInitWithConversionFunction(
4583 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4584 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4585 InitializationSequence &Sequence) {
4586 QualType DestType = Entity.getType();
4587 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4588 QualType T1 = cv1T1.getUnqualifiedType();
4589 QualType cv2T2 = Initializer->getType();
4590 QualType T2 = cv2T2.getUnqualifiedType();
4591
4592 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\""
, "clang/lib/Sema/SemaInit.cpp", 4593, __extension__ __PRETTY_FUNCTION__
))
4593 "Must have incompatible references when binding via conversion")(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\""
, "clang/lib/Sema/SemaInit.cpp", 4593, __extension__ __PRETTY_FUNCTION__
))
;
4594
4595 // Build the candidate set directly in the initialization sequence
4596 // structure, so that it will persist if we fail.
4597 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4598 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4599
4600 // Determine whether we are allowed to call explicit conversion operators.
4601 // Note that none of [over.match.copy], [over.match.conv], nor
4602 // [over.match.ref] permit an explicit constructor to be chosen when
4603 // initializing a reference, not even for direct-initialization.
4604 bool AllowExplicitCtors = false;
4605 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4606
4607 const RecordType *T1RecordType = nullptr;
4608 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4609 S.isCompleteType(Kind.getLocation(), T1)) {
4610 // The type we're converting to is a class type. Enumerate its constructors
4611 // to see if there is a suitable conversion.
4612 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4613
4614 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4615 auto Info = getConstructorInfo(D);
4616 if (!Info.Constructor)
4617 continue;
4618
4619 if (!Info.Constructor->isInvalidDecl() &&
4620 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4621 if (Info.ConstructorTmpl)
4622 S.AddTemplateOverloadCandidate(
4623 Info.ConstructorTmpl, Info.FoundDecl,
4624 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4625 /*SuppressUserConversions=*/true,
4626 /*PartialOverloading*/ false, AllowExplicitCtors);
4627 else
4628 S.AddOverloadCandidate(
4629 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4630 /*SuppressUserConversions=*/true,
4631 /*PartialOverloading*/ false, AllowExplicitCtors);
4632 }
4633 }
4634 }
4635 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4636 return OR_No_Viable_Function;
4637
4638 const RecordType *T2RecordType = nullptr;
4639 if ((T2RecordType = T2->getAs<RecordType>()) &&
4640 S.isCompleteType(Kind.getLocation(), T2)) {
4641 // The type we're converting from is a class type, enumerate its conversion
4642 // functions.
4643 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4644
4645 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4646 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4647 NamedDecl *D = *I;
4648 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4649 if (isa<UsingShadowDecl>(D))
4650 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4651
4652 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4653 CXXConversionDecl *Conv;
4654 if (ConvTemplate)
4655 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4656 else
4657 Conv = cast<CXXConversionDecl>(D);
4658
4659 // If the conversion function doesn't return a reference type,
4660 // it can't be considered for this conversion unless we're allowed to
4661 // consider rvalues.
4662 // FIXME: Do we need to make sure that we only consider conversion
4663 // candidates with reference-compatible results? That might be needed to
4664 // break recursion.
4665 if ((AllowRValues ||
4666 Conv->getConversionType()->isLValueReferenceType())) {
4667 if (ConvTemplate)
4668 S.AddTemplateConversionCandidate(
4669 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4670 CandidateSet,
4671 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4672 else
4673 S.AddConversionCandidate(
4674 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4675 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4676 }
4677 }
4678 }
4679 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4680 return OR_No_Viable_Function;
4681
4682 SourceLocation DeclLoc = Initializer->getBeginLoc();
4683
4684 // Perform overload resolution. If it fails, return the failed result.
4685 OverloadCandidateSet::iterator Best;
4686 if (OverloadingResult Result
4687 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4688 return Result;
4689
4690 FunctionDecl *Function = Best->Function;
4691 // This is the overload that will be used for this initialization step if we
4692 // use this initialization. Mark it as referenced.
4693 Function->setReferenced();
4694
4695 // Compute the returned type and value kind of the conversion.
4696 QualType cv3T3;
4697 if (isa<CXXConversionDecl>(Function))
4698 cv3T3 = Function->getReturnType();
4699 else
4700 cv3T3 = T1;
4701
4702 ExprValueKind VK = VK_PRValue;
4703 if (cv3T3->isLValueReferenceType())
4704 VK = VK_LValue;
4705 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4706 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4707 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4708
4709 // Add the user-defined conversion step.
4710 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4711 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4712 HadMultipleCandidates);
4713
4714 // Determine whether we'll need to perform derived-to-base adjustments or
4715 // other conversions.
4716 Sema::ReferenceConversions RefConv;
4717 Sema::ReferenceCompareResult NewRefRelationship =
4718 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4719
4720 // Add the final conversion sequence, if necessary.
4721 if (NewRefRelationship == Sema::Ref_Incompatible) {
4722 assert(!isa<CXXConstructorDecl>(Function) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "clang/lib/Sema/SemaInit.cpp", 4723, __extension__ __PRETTY_FUNCTION__
))
4723 "should not have conversion after constructor")(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "clang/lib/Sema/SemaInit.cpp", 4723, __extension__ __PRETTY_FUNCTION__
))
;
4724
4725 ImplicitConversionSequence ICS;
4726 ICS.setStandard();
4727 ICS.Standard = Best->FinalConversion;
4728 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4729
4730 // Every implicit conversion results in a prvalue, except for a glvalue
4731 // derived-to-base conversion, which we handle below.
4732 cv3T3 = ICS.Standard.getToType(2);
4733 VK = VK_PRValue;
4734 }
4735
4736 // If the converted initializer is a prvalue, its type T4 is adjusted to
4737 // type "cv1 T4" and the temporary materialization conversion is applied.
4738 //
4739 // We adjust the cv-qualifications to match the reference regardless of
4740 // whether we have a prvalue so that the AST records the change. In this
4741 // case, T4 is "cv3 T3".
4742 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4743 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4744 Sequence.AddQualificationConversionStep(cv1T4, VK);
4745 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4746 VK = IsLValueRef ? VK_LValue : VK_XValue;
4747
4748 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4749 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4750 else if (RefConv & Sema::ReferenceConversions::ObjC)
4751 Sequence.AddObjCObjectConversionStep(cv1T1);
4752 else if (RefConv & Sema::ReferenceConversions::Function)
4753 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4754 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4755 if (!S.Context.hasSameType(cv1T4, cv1T1))
4756 Sequence.AddQualificationConversionStep(cv1T1, VK);
4757 }
4758
4759 return OR_Success;
4760}
4761
4762static void CheckCXX98CompatAccessibleCopy(Sema &S,
4763 const InitializedEntity &Entity,
4764 Expr *CurInitExpr);
4765
4766/// Attempt reference initialization (C++0x [dcl.init.ref])
4767static void TryReferenceInitialization(Sema &S,
4768 const InitializedEntity &Entity,
4769 const InitializationKind &Kind,
4770 Expr *Initializer,
4771 InitializationSequence &Sequence) {
4772 QualType DestType = Entity.getType();
4773 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4774 Qualifiers T1Quals;
4775 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4776 QualType cv2T2 = S.getCompletedType(Initializer);
4777 Qualifiers T2Quals;
4778 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4779
4780 // If the initializer is the address of an overloaded function, try
4781 // to resolve the overloaded function. If all goes well, T2 is the
4782 // type of the resulting function.
4783 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4784 T1, Sequence))
4785 return;
4786
4787 // Delegate everything else to a subfunction.
4788 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4789 T1Quals, cv2T2, T2, T2Quals, Sequence);
4790}
4791
4792/// Determine whether an expression is a non-referenceable glvalue (one to
4793/// which a reference can never bind). Attempting to bind a reference to
4794/// such a glvalue will always create a temporary.
4795static bool isNonReferenceableGLValue(Expr *E) {
4796 return E->refersToBitField() || E->refersToVectorElement() ||
4797 E->refersToMatrixElement();
4798}
4799
4800/// Reference initialization without resolving overloaded functions.
4801///
4802/// We also can get here in C if we call a builtin which is declared as
4803/// a function with a parameter of reference type (such as __builtin_va_end()).
4804static void TryReferenceInitializationCore(Sema &S,
4805 const InitializedEntity &Entity,
4806 const InitializationKind &Kind,
4807 Expr *Initializer,
4808 QualType cv1T1, QualType T1,
4809 Qualifiers T1Quals,
4810 QualType cv2T2, QualType T2,
4811 Qualifiers T2Quals,
4812 InitializationSequence &Sequence) {
4813 QualType DestType = Entity.getType();
4814 SourceLocation DeclLoc = Initializer->getBeginLoc();
4815
4816 // Compute some basic properties of the types and the initializer.
4817 bool isLValueRef = DestType->isLValueReferenceType();
4818 bool isRValueRef = !isLValueRef;
4819 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4820
4821 Sema::ReferenceConversions RefConv;
4822 Sema::ReferenceCompareResult RefRelationship =
4823 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4824
4825 // C++0x [dcl.init.ref]p5:
4826 // A reference to type "cv1 T1" is initialized by an expression of type
4827 // "cv2 T2" as follows:
4828 //
4829 // - If the reference is an lvalue reference and the initializer
4830 // expression
4831 // Note the analogous bullet points for rvalue refs to functions. Because
4832 // there are no function rvalues in C++, rvalue refs to functions are treated
4833 // like lvalue refs.
4834 OverloadingResult ConvOvlResult = OR_Success;
4835 bool T1Function = T1->isFunctionType();
4836 if (isLValueRef || T1Function) {
4837 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4838 (RefRelationship == Sema::Ref_Compatible ||
4839 (Kind.isCStyleOrFunctionalCast() &&
4840 RefRelationship == Sema::Ref_Related))) {
4841 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4842 // reference-compatible with "cv2 T2," or
4843 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
4844 Sema::ReferenceConversions::ObjC)) {
4845 // If we're converting the pointee, add any qualifiers first;
4846 // these qualifiers must all be top-level, so just convert to "cv1 T2".
4847 if (RefConv & (Sema::ReferenceConversions::Qualification))
4848 Sequence.AddQualificationConversionStep(
4849 S.Context.getQualifiedType(T2, T1Quals),
4850 Initializer->getValueKind());
4851 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4852 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4853 else
4854 Sequence.AddObjCObjectConversionStep(cv1T1);
4855 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
4856 // Perform a (possibly multi-level) qualification conversion.
4857 Sequence.AddQualificationConversionStep(cv1T1,
4858 Initializer->getValueKind());
4859 } else if (RefConv & Sema::ReferenceConversions::Function) {
4860 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4861 }
4862
4863 // We only create a temporary here when binding a reference to a
4864 // bit-field or vector element. Those cases are't supposed to be
4865 // handled by this bullet, but the outcome is the same either way.
4866 Sequence.AddReferenceBindingStep(cv1T1, false);
4867 return;
4868 }
4869
4870 // - has a class type (i.e., T2 is a class type), where T1 is not
4871 // reference-related to T2, and can be implicitly converted to an
4872 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4873 // with "cv3 T3" (this conversion is selected by enumerating the
4874 // applicable conversion functions (13.3.1.6) and choosing the best
4875 // one through overload resolution (13.3)),
4876 // If we have an rvalue ref to function type here, the rhs must be
4877 // an rvalue. DR1287 removed the "implicitly" here.
4878 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4879 (isLValueRef || InitCategory.isRValue())) {
4880 if (S.getLangOpts().CPlusPlus) {
4881 // Try conversion functions only for C++.
4882 ConvOvlResult = TryRefInitWithConversionFunction(
4883 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4884 /*IsLValueRef*/ isLValueRef, Sequence);
4885 if (ConvOvlResult == OR_Success)
4886 return;
4887 if (ConvOvlResult != OR_No_Viable_Function)
4888 Sequence.SetOverloadFailure(
4889 InitializationSequence::FK_ReferenceInitOverloadFailed,
4890 ConvOvlResult);
4891 } else {
4892 ConvOvlResult = OR_No_Viable_Function;
4893 }
4894 }
4895 }
4896
4897 // - Otherwise, the reference shall be an lvalue reference to a
4898 // non-volatile const type (i.e., cv1 shall be const), or the reference
4899 // shall be an rvalue reference.
4900 // For address spaces, we interpret this to mean that an addr space
4901 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4902 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4903 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
4904 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4905 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4906 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4907 Sequence.SetOverloadFailure(
4908 InitializationSequence::FK_ReferenceInitOverloadFailed,
4909 ConvOvlResult);
4910 else if (!InitCategory.isLValue())
4911 Sequence.SetFailed(
4912 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4913 ? InitializationSequence::
4914 FK_NonConstLValueReferenceBindingToTemporary
4915 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
4916 else {
4917 InitializationSequence::FailureKind FK;
4918 switch (RefRelationship) {
4919 case Sema::Ref_Compatible:
4920 if (Initializer->refersToBitField())
4921 FK = InitializationSequence::
4922 FK_NonConstLValueReferenceBindingToBitfield;
4923 else if (Initializer->refersToVectorElement())
4924 FK = InitializationSequence::
4925 FK_NonConstLValueReferenceBindingToVectorElement;
4926 else if (Initializer->refersToMatrixElement())
4927 FK = InitializationSequence::
4928 FK_NonConstLValueReferenceBindingToMatrixElement;
4929 else
4930 llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer"
, "clang/lib/Sema/SemaInit.cpp", 4930)
;
4931 break;
4932 case Sema::Ref_Related:
4933 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4934 break;
4935 case Sema::Ref_Incompatible:
4936 FK = InitializationSequence::
4937 FK_NonConstLValueReferenceBindingToUnrelated;
4938 break;
4939 }
4940 Sequence.SetFailed(FK);
4941 }
4942 return;
4943 }
4944
4945 // - If the initializer expression
4946 // - is an
4947 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4948 // [1z] rvalue (but not a bit-field) or
4949 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4950 //
4951 // Note: functions are handled above and below rather than here...
4952 if (!T1Function &&
4953 (RefRelationship == Sema::Ref_Compatible ||
4954 (Kind.isCStyleOrFunctionalCast() &&
4955 RefRelationship == Sema::Ref_Related)) &&
4956 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4957 (InitCategory.isPRValue() &&
4958 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4959 T2->isArrayType())))) {
4960 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
4961 if (InitCategory.isPRValue() && T2->isRecordType()) {
4962 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4963 // compiler the freedom to perform a copy here or bind to the
4964 // object, while C++0x requires that we bind directly to the
4965 // object. Hence, we always bind to the object without making an
4966 // extra copy. However, in C++03 requires that we check for the
4967 // presence of a suitable copy constructor:
4968 //
4969 // The constructor that would be used to make the copy shall
4970 // be callable whether or not the copy is actually done.
4971 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4972 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4973 else if (S.getLangOpts().CPlusPlus11)
4974 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4975 }
4976
4977 // C++1z [dcl.init.ref]/5.2.1.2:
4978 // If the converted initializer is a prvalue, its type T4 is adjusted
4979 // to type "cv1 T4" and the temporary materialization conversion is
4980 // applied.
4981 // Postpone address space conversions to after the temporary materialization
4982 // conversion to allow creating temporaries in the alloca address space.
4983 auto T1QualsIgnoreAS = T1Quals;
4984 auto T2QualsIgnoreAS = T2Quals;
4985 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4986 T1QualsIgnoreAS.removeAddressSpace();
4987 T2QualsIgnoreAS.removeAddressSpace();
4988 }
4989 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4990 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
4991 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4992 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
4993 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4994 // Add addr space conversion if required.
4995 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4996 auto T4Quals = cv1T4.getQualifiers();
4997 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
4998 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
4999 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5000 cv1T4 = cv1T4WithAS;
5001 }
5002
5003 // In any case, the reference is bound to the resulting glvalue (or to
5004 // an appropriate base class subobject).
5005 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5006 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5007 else if (RefConv & Sema::ReferenceConversions::ObjC)
5008 Sequence.AddObjCObjectConversionStep(cv1T1);
5009 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5010 if (!S.Context.hasSameType(cv1T4, cv1T1))
5011 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5012 }
5013 return;
5014 }
5015
5016 // - has a class type (i.e., T2 is a class type), where T1 is not
5017 // reference-related to T2, and can be implicitly converted to an
5018 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5019 // where "cv1 T1" is reference-compatible with "cv3 T3",
5020 //
5021 // DR1287 removes the "implicitly" here.
5022 if (T2->isRecordType()) {
5023 if (RefRelationship == Sema::Ref_Incompatible) {
5024 ConvOvlResult = TryRefInitWithConversionFunction(
5025 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5026 /*IsLValueRef*/ isLValueRef, Sequence);
5027 if (ConvOvlResult)
5028 Sequence.SetOverloadFailure(
5029 InitializationSequence::FK_ReferenceInitOverloadFailed,
5030 ConvOvlResult);
5031
5032 return;
5033 }
5034
5035 if (RefRelationship == Sema::Ref_Compatible &&
5036 isRValueRef && InitCategory.isLValue()) {
5037 Sequence.SetFailed(
5038 InitializationSequence::FK_RValueReferenceBindingToLValue);
5039 return;
5040 }
5041
5042 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5043 return;
5044 }
5045
5046 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5047 // from the initializer expression using the rules for a non-reference
5048 // copy-initialization (8.5). The reference is then bound to the
5049 // temporary. [...]
5050
5051 // Ignore address space of reference type at this point and perform address
5052 // space conversion after the reference binding step.
5053 QualType cv1T1IgnoreAS =
5054 T1Quals.hasAddressSpace()
5055 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5056 : cv1T1;
5057
5058 InitializedEntity TempEntity =
5059 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5060
5061 // FIXME: Why do we use an implicit conversion here rather than trying
5062 // copy-initialization?
5063 ImplicitConversionSequence ICS
5064 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5065 /*SuppressUserConversions=*/false,
5066 Sema::AllowedExplicit::None,
5067 /*FIXME:InOverloadResolution=*/false,
5068 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5069 /*AllowObjCWritebackConversion=*/false);
5070
5071 if (ICS.isBad()) {
5072 // FIXME: Use the conversion function set stored in ICS to turn
5073 // this into an overloading ambiguity diagnostic. However, we need
5074 // to keep that set as an OverloadCandidateSet rather than as some
5075 // other kind of set.
5076 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5077 Sequence.SetOverloadFailure(
5078 InitializationSequence::FK_ReferenceInitOverloadFailed,
5079 ConvOvlResult);
5080 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5081 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5082 else
5083 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5084 return;
5085 } else {
5086 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
5087 }
5088
5089 // [...] If T1 is reference-related to T2, cv1 must be the
5090 // same cv-qualification as, or greater cv-qualification
5091 // than, cv2; otherwise, the program is ill-formed.
5092 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5093 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5094 if (RefRelationship == Sema::Ref_Related &&
5095 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5096 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5097 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5098 return;
5099 }
5100
5101 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5102 // reference, the initializer expression shall not be an lvalue.
5103 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5104 InitCategory.isLValue()) {
5105 Sequence.SetFailed(
5106 InitializationSequence::FK_RValueReferenceBindingToLValue);
5107 return;
5108 }
5109
5110 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5111
5112 if (T1Quals.hasAddressSpace()) {
5113 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
5114 LangAS::Default)) {
5115 Sequence.SetFailed(
5116 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5117 return;
5118 }
5119 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5120 : VK_XValue);
5121 }
5122}
5123
5124/// Attempt character array initialization from a string literal
5125/// (C++ [dcl.init.string], C99 6.7.8).
5126static void TryStringLiteralInitialization(Sema &S,
5127 const InitializedEntity &Entity,
5128 const InitializationKind &Kind,
5129 Expr *Initializer,
5130 InitializationSequence &Sequence) {
5131 Sequence.AddStringInitStep(Entity.getType());
5132}
5133
5134/// Attempt value initialization (C++ [dcl.init]p7).
5135static void TryValueInitialization(Sema &S,
5136 const InitializedEntity &Entity,
5137 const InitializationKind &Kind,
5138 InitializationSequence &Sequence,
5139 InitListExpr *InitList) {
5140 assert((!InitList || InitList->getNumInits() == 0) &&(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "clang/lib/Sema/SemaInit.cpp", 5141, __extension__ __PRETTY_FUNCTION__
))
5141 "Shouldn't use value-init for non-empty init lists")(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "clang/lib/Sema/SemaInit.cpp", 5141, __extension__ __PRETTY_FUNCTION__
))
;
5142
5143 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5144 //
5145 // To value-initialize an object of type T means:
5146 QualType T = Entity.getType();
5147
5148 // -- if T is an array type, then each element is value-initialized;
5149 T = S.Context.getBaseElementType(T);
5150
5151 if (const RecordType *RT = T->getAs<RecordType>()) {
5152 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5153 bool NeedZeroInitialization = true;
5154 // C++98:
5155 // -- if T is a class type (clause 9) with a user-declared constructor
5156 // (12.1), then the default constructor for T is called (and the
5157 // initialization is ill-formed if T has no accessible default
5158 // constructor);
5159 // C++11:
5160 // -- if T is a class type (clause 9) with either no default constructor
5161 // (12.1 [class.ctor]) or a default constructor that is user-provided
5162 // or deleted, then the object is default-initialized;
5163 //
5164 // Note that the C++11 rule is the same as the C++98 rule if there are no
5165 // defaulted or deleted constructors, so we just use it unconditionally.
5166 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5167 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5168 NeedZeroInitialization = false;
5169
5170 // -- if T is a (possibly cv-qualified) non-union class type without a
5171 // user-provided or deleted default constructor, then the object is
5172 // zero-initialized and, if T has a non-trivial default constructor,
5173 // default-initialized;
5174 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5175 // constructor' part was removed by DR1507.
5176 if (NeedZeroInitialization)
5177 Sequence.AddZeroInitializationStep(Entity.getType());
5178
5179 // C++03:
5180 // -- if T is a non-union class type without a user-declared constructor,
5181 // then every non-static data member and base class component of T is
5182 // value-initialized;
5183 // [...] A program that calls for [...] value-initialization of an
5184 // entity of reference type is ill-formed.
5185 //
5186 // C++11 doesn't need this handling, because value-initialization does not
5187 // occur recursively there, and the implicit default constructor is
5188 // defined as deleted in the problematic cases.
5189 if (!S.getLangOpts().CPlusPlus11 &&
5190 ClassDecl->hasUninitializedReferenceMember()) {
5191 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5192 return;
5193 }
5194
5195 // If this is list-value-initialization, pass the empty init list on when
5196 // building the constructor call. This affects the semantics of a few
5197 // things (such as whether an explicit default constructor can be called).
5198 Expr *InitListAsExpr = InitList;
5199 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5200 bool InitListSyntax = InitList;
5201
5202 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5203 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5204 return TryConstructorInitialization(
5205 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5206 }
5207 }
5208
5209 Sequence.AddZeroInitializationStep(Entity.getType());
5210}
5211
5212/// Attempt default initialization (C++ [dcl.init]p6).
5213static void TryDefaultInitialization(Sema &S,
5214 const InitializedEntity &Entity,
5215 const InitializationKind &Kind,
5216 InitializationSequence &Sequence) {
5217 assert(Kind.getKind() == InitializationKind::IK_Default)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Default) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Default"
, "clang/lib/Sema/SemaInit.cpp", 5217, __extension__ __PRETTY_FUNCTION__
))
;
5218
5219 // C++ [dcl.init]p6:
5220 // To default-initialize an object of type T means:
5221 // - if T is an array type, each element is default-initialized;
5222 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5223
5224 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5225 // constructor for T is called (and the initialization is ill-formed if
5226 // T has no accessible default constructor);
5227 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5228 TryConstructorInitialization(S, Entity, Kind, None, DestType,
5229 Entity.getType(), Sequence);
5230 return;
5231 }
5232
5233 // - otherwise, no initialization is performed.
5234
5235 // If a program calls for the default initialization of an object of
5236 // a const-qualified type T, T shall be a class type with a user-provided
5237 // default constructor.
5238 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5239 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5240 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5241 return;
5242 }
5243
5244 // If the destination type has a lifetime property, zero-initialize it.
5245 if (DestType.getQualifiers().hasObjCLifetime()) {
5246 Sequence.AddZeroInitializationStep(Entity.getType());
5247 return;
5248 }
5249}
5250
5251/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5252/// which enumerates all conversion functions and performs overload resolution
5253/// to select the best.
5254static void TryUserDefinedConversion(Sema &S,
5255 QualType DestType,
5256 const InitializationKind &Kind,
5257 Expr *Initializer,
5258 InitializationSequence &Sequence,
5259 bool TopLevelOfInitList) {
5260 assert(!DestType->isReferenceType() && "References are handled elsewhere")(static_cast <bool> (!DestType->isReferenceType() &&
"References are handled elsewhere") ? void (0) : __assert_fail
("!DestType->isReferenceType() && \"References are handled elsewhere\""
, "clang/lib/Sema/SemaInit.cpp", 5260, __extension__ __PRETTY_FUNCTION__
))
;
5261 QualType SourceType = Initializer->getType();
5262 assert((DestType->isRecordType() || SourceType->isRecordType()) &&(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "clang/lib/Sema/SemaInit.cpp", 5263, __extension__ __PRETTY_FUNCTION__
))
5263 "Must have a class type to perform a user-defined conversion")(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "clang/lib/Sema/SemaInit.cpp", 5263, __extension__ __PRETTY_FUNCTION__
))
;
5264
5265 // Build the candidate set directly in the initialization sequence
5266 // structure, so that it will persist if we fail.
5267 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5268 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5269 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5270
5271 // Determine whether we are allowed to call explicit constructors or
5272 // explicit conversion operators.
5273 bool AllowExplicit = Kind.AllowExplicit();
5274
5275 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5276 // The type we're converting to is a class type. Enumerate its constructors
5277 // to see if there is a suitable conversion.
5278 CXXRecordDecl *DestRecordDecl
5279 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5280
5281 // Try to complete the type we're converting to.
5282 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5283 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5284 auto Info = getConstructorInfo(D);
5285 if (!Info.Constructor)
5286 continue;
5287
5288 if (!Info.Constructor->isInvalidDecl() &&
5289 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5290 if (Info.ConstructorTmpl)
5291 S.AddTemplateOverloadCandidate(
5292 Info.ConstructorTmpl, Info.FoundDecl,
5293 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5294 /*SuppressUserConversions=*/true,
5295 /*PartialOverloading*/ false, AllowExplicit);
5296 else
5297 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5298 Initializer, CandidateSet,
5299 /*SuppressUserConversions=*/true,
5300 /*PartialOverloading*/ false, AllowExplicit);
5301 }
5302 }
5303 }
5304 }
5305
5306 SourceLocation DeclLoc = Initializer->getBeginLoc();
5307
5308 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5309 // The type we're converting from is a class type, enumerate its conversion
5310 // functions.
5311
5312 // We can only enumerate the conversion functions for a complete type; if
5313 // the type isn't complete, simply skip this step.
5314 if (S.isCompleteType(DeclLoc, SourceType)) {
5315 CXXRecordDecl *SourceRecordDecl
5316 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5317
5318 const auto &Conversions =
5319 SourceRecordDecl->getVisibleConversionFunctions();
5320 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5321 NamedDecl *D = *I;
5322 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5323 if (isa<UsingShadowDecl>(D))
5324 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5325
5326 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5327 CXXConversionDecl *Conv;
5328 if (ConvTemplate)
5329 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5330 else
5331 Conv = cast<CXXConversionDecl>(D);
5332
5333 if (ConvTemplate)
5334 S.AddTemplateConversionCandidate(
5335 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5336 CandidateSet, AllowExplicit, AllowExplicit);
5337 else
5338 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5339 DestType, CandidateSet, AllowExplicit,
5340 AllowExplicit);
5341 }
5342 }
5343 }
5344
5345 // Perform overload resolution. If it fails, return the failed result.
5346 OverloadCandidateSet::iterator Best;
5347 if (OverloadingResult Result
5348 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5349 Sequence.SetOverloadFailure(
5350 InitializationSequence::FK_UserConversionOverloadFailed, Result);
5351
5352 // [class.copy.elision]p3:
5353 // In some copy-initialization contexts, a two-stage overload resolution
5354 // is performed.
5355 // If the first overload resolution selects a deleted function, we also
5356 // need the initialization sequence to decide whether to perform the second
5357 // overload resolution.
5358 if (!(Result == OR_Deleted &&
5359 Kind.getKind() == InitializationKind::IK_Copy))
5360 return;
5361 }
5362
5363 FunctionDecl *Function = Best->Function;
5364 Function->setReferenced();
5365 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5366
5367 if (isa<CXXConstructorDecl>(Function)) {
5368 // Add the user-defined conversion step. Any cv-qualification conversion is
5369 // subsumed by the initialization. Per DR5, the created temporary is of the
5370 // cv-unqualified type of the destination.
5371 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5372 DestType.getUnqualifiedType(),
5373 HadMultipleCandidates);
5374
5375 // C++14 and before:
5376 // - if the function is a constructor, the call initializes a temporary
5377 // of the cv-unqualified version of the destination type. The [...]
5378 // temporary [...] is then used to direct-initialize, according to the
5379 // rules above, the object that is the destination of the
5380 // copy-initialization.
5381 // Note that this just performs a simple object copy from the temporary.
5382 //
5383 // C++17:
5384 // - if the function is a constructor, the call is a prvalue of the
5385 // cv-unqualified version of the destination type whose return object
5386 // is initialized by the constructor. The call is used to
5387 // direct-initialize, according to the rules above, the object that
5388 // is the destination of the copy-initialization.
5389 // Therefore we need to do nothing further.
5390 //
5391 // FIXME: Mark this copy as extraneous.
5392 if (!S.getLangOpts().CPlusPlus17)
5393 Sequence.AddFinalCopy(DestType);
5394 else if (DestType.hasQualifiers())
5395 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5396 return;
5397 }
5398
5399 // Add the user-defined conversion step that calls the conversion function.
5400 QualType ConvType = Function->getCallResultType();
5401 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5402 HadMultipleCandidates);
5403
5404 if (ConvType->getAs<RecordType>()) {
5405 // The call is used to direct-initialize [...] the object that is the
5406 // destination of the copy-initialization.
5407 //
5408 // In C++17, this does not call a constructor if we enter /17.6.1:
5409 // - If the initializer expression is a prvalue and the cv-unqualified
5410 // version of the source type is the same as the class of the
5411 // destination [... do not make an extra copy]
5412 //
5413 // FIXME: Mark this copy as extraneous.
5414 if (!S.getLangOpts().CPlusPlus17 ||
5415 Function->getReturnType()->isReferenceType() ||
5416 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5417 Sequence.AddFinalCopy(DestType);
5418 else if (!S.Context.hasSameType(ConvType, DestType))
5419 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5420 return;
5421 }
5422
5423 // If the conversion following the call to the conversion function
5424 // is interesting, add it as a separate step.
5425 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5426 Best->FinalConversion.Third) {
5427 ImplicitConversionSequence ICS;
5428 ICS.setStandard();
5429 ICS.Standard = Best->FinalConversion;
5430 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5431 }
5432}
5433
5434/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5435/// a function with a pointer return type contains a 'return false;' statement.
5436/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5437/// code using that header.
5438///
5439/// Work around this by treating 'return false;' as zero-initializing the result
5440/// if it's used in a pointer-returning function in a system header.
5441static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5442 const InitializedEntity &Entity,
5443 const Expr *Init) {
5444 return S.getLangOpts().CPlusPlus11 &&
5445 Entity.getKind() == InitializedEntity::EK_Result &&
5446 Entity.getType()->isPointerType() &&
5447 isa<CXXBoolLiteralExpr>(Init) &&
5448 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5449 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5450}
5451
5452/// The non-zero enum values here are indexes into diagnostic alternatives.
5453enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5454
5455/// Determines whether this expression is an acceptable ICR source.
5456static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5457 bool isAddressOf, bool &isWeakAccess) {
5458 // Skip parens.
5459 e = e->IgnoreParens();
5460
5461 // Skip address-of nodes.
5462 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5463 if (op->getOpcode() == UO_AddrOf)
5464 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5465 isWeakAccess);
5466
5467 // Skip certain casts.
5468 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5469 switch (ce->getCastKind()) {
5470 case CK_Dependent:
5471 case CK_BitCast:
5472 case CK_LValueBitCast:
5473 case CK_NoOp:
5474 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5475
5476 case CK_ArrayToPointerDecay:
5477 return IIK_nonscalar;
5478
5479 case CK_NullToPointer:
5480 return IIK_okay;
5481
5482 default:
5483 break;
5484 }
5485
5486 // If we have a declaration reference, it had better be a local variable.
5487 } else if (isa<DeclRefExpr>(e)) {
5488 // set isWeakAccess to true, to mean that there will be an implicit
5489 // load which requires a cleanup.
5490 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5491 isWeakAccess = true;
5492
5493 if (!isAddressOf) return IIK_nonlocal;
5494
5495 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5496 if (!var) return IIK_nonlocal;
5497
5498 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5499
5500 // If we have a conditional operator, check both sides.
5501 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5502 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5503 isWeakAccess))
5504 return iik;
5505
5506 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5507
5508 // These are never scalar.
5509 } else if (isa<ArraySubscriptExpr>(e)) {
5510 return IIK_nonscalar;
5511
5512 // Otherwise, it needs to be a null pointer constant.
5513 } else {
5514 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5515 ? IIK_okay : IIK_nonlocal);
5516 }
5517
5518 return IIK_nonlocal;
5519}
5520
5521/// Check whether the given expression is a valid operand for an
5522/// indirect copy/restore.
5523static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5524 assert(src->isPRValue())(static_cast <bool> (src->isPRValue()) ? void (0) : __assert_fail
("src->isPRValue()", "clang/lib/Sema/SemaInit.cpp", 5524,
__extension__ __PRETTY_FUNCTION__))
;
5525 bool isWeakAccess = false;
5526 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5527 // If isWeakAccess to true, there will be an implicit
5528 // load which requires a cleanup.
5529 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5530 S.Cleanup.setExprNeedsCleanups(true);
5531
5532 if (iik == IIK_okay) return;
5533
5534 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5535 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5536 << src->getSourceRange();
5537}
5538
5539/// Determine whether we have compatible array types for the
5540/// purposes of GNU by-copy array initialization.
5541static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5542 const ArrayType *Source) {
5543 // If the source and destination array types are equivalent, we're
5544 // done.
5545 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5546 return true;
5547
5548 // Make sure that the element types are the same.
5549 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5550 return false;
5551
5552 // The only mismatch we allow is when the destination is an
5553 // incomplete array type and the source is a constant array type.
5554 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5555}
5556
5557static bool tryObjCWritebackConversion(Sema &S,
5558 InitializationSequence &Sequence,
5559 const InitializedEntity &Entity,
5560 Expr *Initializer) {
5561 bool ArrayDecay = false;
5562 QualType ArgType = Initializer->getType();
5563 QualType ArgPointee;
5564 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5565 ArrayDecay = true;
5566 ArgPointee = ArgArrayType->getElementType();
5567 ArgType = S.Context.getPointerType(ArgPointee);
5568 }
5569
5570 // Handle write-back conversion.
5571 QualType ConvertedArgType;
5572 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5573 ConvertedArgType))
5574 return false;
5575
5576 // We should copy unless we're passing to an argument explicitly
5577 // marked 'out'.
5578 bool ShouldCopy = true;
5579 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5580 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5581
5582 // Do we need an lvalue conversion?
5583 if (ArrayDecay || Initializer->isGLValue()) {
5584 ImplicitConversionSequence ICS;
5585 ICS.setStandard();
5586 ICS.Standard.setAsIdentityConversion();
5587
5588 QualType ResultType;
5589 if (ArrayDecay) {
5590 ICS.Standard.First = ICK_Array_To_Pointer;
5591 ResultType = S.Context.getPointerType(ArgPointee);
5592 } else {
5593 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5594 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5595 }
5596
5597 Sequence.AddConversionSequenceStep(ICS, ResultType);
5598 }
5599
5600 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5601 return true;
5602}
5603
5604static bool TryOCLSamplerInitialization(Sema &S,
5605 InitializationSequence &Sequence,
5606 QualType DestType,
5607 Expr *Initializer) {
5608 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5609 (!Initializer->isIntegerConstantExpr(S.Context) &&
5610 !Initializer->getType()->isSamplerT()))
5611 return false;
5612
5613 Sequence.AddOCLSamplerInitStep(DestType);
5614 return true;
5615}
5616
5617static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5618 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5619 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5620}
5621
5622static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5623 InitializationSequence &Sequence,
5624 QualType DestType,
5625 Expr *Initializer) {
5626 if (!S.getLangOpts().OpenCL)
5627 return false;
5628
5629 //
5630 // OpenCL 1.2 spec, s6.12.10
5631 //
5632 // The event argument can also be used to associate the
5633 // async_work_group_copy with a previous async copy allowing
5634 // an event to be shared by multiple async copies; otherwise
5635 // event should be zero.
5636 //
5637 if (DestType->isEventT() || DestType->isQueueT()) {
5638 if (!IsZeroInitializer(Initializer, S))
5639 return false;
5640
5641 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5642 return true;
5643 }
5644
5645 // We should allow zero initialization for all types defined in the
5646 // cl_intel_device_side_avc_motion_estimation extension, except
5647 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5648 if (S.getOpenCLOptions().isAvailableOption(
5649 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
5650 DestType->isOCLIntelSubgroupAVCType()) {
5651 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5652 DestType->isOCLIntelSubgroupAVCMceResultType())
5653 return false;
5654 if (!IsZeroInitializer(Initializer, S))
5655 return false;
5656
5657 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5658 return true;
5659 }
5660
5661 return false;
5662}
5663
5664InitializationSequence::InitializationSequence(
5665 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5666 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
5667 : FailedOverloadResult(OR_Success),
5668 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5669 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5670 TreatUnavailableAsInvalid);
5671}
5672
5673/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5674/// address of that function, this returns true. Otherwise, it returns false.
5675static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5676 auto *DRE = dyn_cast<DeclRefExpr>(E);
5677 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5678 return false;
5679
5680 return !S.checkAddressOfFunctionIsAvailable(
5681 cast<FunctionDecl>(DRE->getDecl()));
5682}
5683
5684/// Determine whether we can perform an elementwise array copy for this kind
5685/// of entity.
5686static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5687 switch (Entity.getKind()) {
5688 case InitializedEntity::EK_LambdaCapture:
5689 // C++ [expr.prim.lambda]p24:
5690 // For array members, the array elements are direct-initialized in
5691 // increasing subscript order.
5692 return true;
5693
5694 case InitializedEntity::EK_Variable:
5695 // C++ [dcl.decomp]p1:
5696 // [...] each element is copy-initialized or direct-initialized from the
5697 // corresponding element of the assignment-expression [...]
5698 return isa<DecompositionDecl>(Entity.getDecl());
5699
5700 case InitializedEntity::EK_Member:
5701 // C++ [class.copy.ctor]p14:
5702 // - if the member is an array, each element is direct-initialized with
5703 // the corresponding subobject of x
5704 return Entity.isImplicitMemberInitializer();
5705
5706 case InitializedEntity::EK_ArrayElement:
5707 // All the above cases are intended to apply recursively, even though none
5708 // of them actually say that.
5709 if (auto *E = Entity.getParent())
5710 return canPerformArrayCopy(*E);
5711 break;
5712
5713 default:
5714 break;
5715 }
5716
5717 return false;
5718}
5719
5720void InitializationSequence::InitializeFrom(Sema &S,
5721 const InitializedEntity &Entity,
5722 const InitializationKind &Kind,
5723 MultiExprArg Args,
5724 bool TopLevelOfInitList,
5725 bool TreatUnavailableAsInvalid) {
5726 ASTContext &Context = S.Context;
5727
5728 // Eliminate non-overload placeholder types in the arguments. We
5729 // need to do this before checking whether types are dependent
5730 // because lowering a pseudo-object expression might well give us
5731 // something of dependent type.
5732 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5733 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5734 // FIXME: should we be doing this here?
5735 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5736 if (result.isInvalid()) {
5737 SetFailed(FK_PlaceholderType);
5738 return;
5739 }
5740 Args[I] = result.get();
5741 }
5742
5743 // C++0x [dcl.init]p16:
5744 // The semantics of initializers are as follows. The destination type is
5745 // the type of the object or reference being initialized and the source
5746 // type is the type of the initializer expression. The source type is not
5747 // defined when the initializer is a braced-init-list or when it is a
5748 // parenthesized list of expressions.
5749 QualType DestType = Entity.getType();
5750
5751 if (DestType->isDependentType() ||
5752 Expr::hasAnyTypeDependentArguments(Args)) {
5753 SequenceKind = DependentSequence;
5754 return;
5755 }
5756
5757 // Almost everything is a normal sequence.
5758 setSequenceKind(NormalSequence);
5759
5760 QualType SourceType;
5761 Expr *Initializer = nullptr;
5762 if (Args.size() == 1) {
5763 Initializer = Args[0];
5764 if (S.getLangOpts().ObjC) {
5765 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
5766 DestType, Initializer->getType(),
5767 Initializer) ||
5768 S.CheckConversionToObjCLiteral(DestType, Initializer))
5769 Args[0] = Initializer;
5770 }
5771 if (!isa<InitListExpr>(Initializer))
5772 SourceType = Initializer->getType();
5773 }
5774
5775 // - If the initializer is a (non-parenthesized) braced-init-list, the
5776 // object is list-initialized (8.5.4).
5777 if (Kind.getKind() != InitializationKind::IK_Direct) {
5778 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5779 TryListInitialization(S, Entity, Kind, InitList, *this,
5780 TreatUnavailableAsInvalid);
5781 return;
5782 }
5783 }
5784
5785 // - If the destination type is a reference type, see 8.5.3.
5786 if (DestType->isReferenceType()) {
5787 // C++0x [dcl.init.ref]p1:
5788 // A variable declared to be a T& or T&&, that is, "reference to type T"
5789 // (8.3.2), shall be initialized by an object, or function, of type T or
5790 // by an object that can be converted into a T.
5791 // (Therefore, multiple arguments are not permitted.)
5792 if (Args.size() != 1)
5793 SetFailed(FK_TooManyInitsForReference);
5794 // C++17 [dcl.init.ref]p5:
5795 // A reference [...] is initialized by an expression [...] as follows:
5796 // If the initializer is not an expression, presumably we should reject,
5797 // but the standard fails to actually say so.
5798 else if (isa<InitListExpr>(Args[0]))
5799 SetFailed(FK_ParenthesizedListInitForReference);
5800 else
5801 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5802 return;
5803 }
5804
5805 // - If the initializer is (), the object is value-initialized.
5806 if (Kind.getKind() == InitializationKind::IK_Value ||
5807 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5808 TryValueInitialization(S, Entity, Kind, *this);
5809 return;
5810 }
5811
5812 // Handle default initialization.
5813 if (Kind.getKind() == InitializationKind::IK_Default) {
5814 TryDefaultInitialization(S, Entity, Kind, *this);
5815 return;
5816 }
5817
5818 // - If the destination type is an array of characters, an array of
5819 // char16_t, an array of char32_t, or an array of wchar_t, and the
5820 // initializer is a string literal, see 8.5.2.
5821 // - Otherwise, if the destination type is an array, the program is
5822 // ill-formed.
5823 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5824 if (Initializer && isa<VariableArrayType>(DestAT)) {
5825 SetFailed(FK_VariableLengthArrayHasInitializer);
5826 return;
5827 }
5828
5829 if (Initializer) {
5830 switch (IsStringInit(Initializer, DestAT, Context)) {
5831 case SIF_None:
5832 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5833 return;
5834 case SIF_NarrowStringIntoWideChar:
5835 SetFailed(FK_NarrowStringIntoWideCharArray);
5836 return;
5837 case SIF_WideStringIntoChar:
5838 SetFailed(FK_WideStringIntoCharArray);
5839 return;
5840 case SIF_IncompatWideStringIntoWideChar:
5841 SetFailed(FK_IncompatWideStringIntoWideChar);
5842 return;
5843 case SIF_PlainStringIntoUTF8Char:
5844 SetFailed(FK_PlainStringIntoUTF8Char);
5845 return;
5846 case SIF_UTF8StringIntoPlainChar:
5847 SetFailed(FK_UTF8StringIntoPlainChar);
5848 return;
5849 case SIF_Other:
5850 break;
5851 }
5852 }
5853
5854 // Some kinds of initialization permit an array to be initialized from
5855 // another array of the same type, and perform elementwise initialization.
5856 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5857 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5858 Entity.getType()) &&
5859 canPerformArrayCopy(Entity)) {
5860 // If source is a prvalue, use it directly.
5861 if (Initializer->isPRValue()) {
5862 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5863 return;
5864 }
5865
5866 // Emit element-at-a-time copy loop.
5867 InitializedEntity Element =
5868 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5869 QualType InitEltT =
5870 Context.getAsArrayType(Initializer->getType())->getElementType();
5871 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5872 Initializer->getValueKind(),
5873 Initializer->getObjectKind());
5874 Expr *OVEAsExpr = &OVE;
5875 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5876 TreatUnavailableAsInvalid);
5877 if (!Failed())
5878 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5879 return;
5880 }
5881
5882 // Note: as an GNU C extension, we allow initialization of an
5883 // array from a compound literal that creates an array of the same
5884 // type, so long as the initializer has no side effects.
5885 if (!S.getLangOpts().CPlusPlus && Initializer &&
5886 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5887 Initializer->getType()->isArrayType()) {
5888 const ArrayType *SourceAT
5889 = Context.getAsArrayType(Initializer->getType());
5890 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5891 SetFailed(FK_ArrayTypeMismatch);
5892 else if (Initializer->HasSideEffects(S.Context))
5893 SetFailed(FK_NonConstantArrayInit);
5894 else {
5895 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5896 }
5897 }
5898 // Note: as a GNU C++ extension, we allow list-initialization of a
5899 // class member of array type from a parenthesized initializer list.
5900 else if (S.getLangOpts().CPlusPlus &&
5901 Entity.getKind() == InitializedEntity::EK_Member &&
5902 Initializer && isa<InitListExpr>(Initializer)) {
5903 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5904 *this, TreatUnavailableAsInvalid);
5905 AddParenthesizedArrayInitStep(DestType);
5906 } else if (DestAT->getElementType()->isCharType())
5907 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5908 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5909 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5910 else
5911 SetFailed(FK_ArrayNeedsInitList);
5912
5913 return;
5914 }
5915
5916 // Determine whether we should consider writeback conversions for
5917 // Objective-C ARC.
5918 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5919 Entity.isParameterKind();
5920
5921 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5922 return;
5923
5924 // We're at the end of the line for C: it's either a write-back conversion
5925 // or it's a C assignment. There's no need to check anything else.
5926 if (!S.getLangOpts().CPlusPlus) {
5927 // If allowed, check whether this is an Objective-C writeback conversion.
5928 if (allowObjCWritebackConversion &&
5929 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5930 return;
5931 }
5932
5933 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
5934 return;
5935
5936 // Handle initialization in C
5937 AddCAssignmentStep(DestType);
5938 MaybeProduceObjCObject(S, *this, Entity);
5939 return;
5940 }
5941
5942 assert(S.getLangOpts().CPlusPlus)(static_cast <bool> (S.getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("S.getLangOpts().CPlusPlus", "clang/lib/Sema/SemaInit.cpp"
, 5942, __extension__ __PRETTY_FUNCTION__))
;
5943
5944 // - If the destination type is a (possibly cv-qualified) class type:
5945 if (DestType->isRecordType()) {
5946 // - If the initialization is direct-initialization, or if it is
5947 // copy-initialization where the cv-unqualified version of the
5948 // source type is the same class as, or a derived class of, the
5949 // class of the destination, constructors are considered. [...]
5950 if (Kind.getKind() == InitializationKind::IK_Direct ||
5951 (Kind.getKind() == InitializationKind::IK_Copy &&
5952 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5953 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
5954 TryConstructorInitialization(S, Entity, Kind, Args,
5955 DestType, DestType, *this);
5956 // - Otherwise (i.e., for the remaining copy-initialization cases),
5957 // user-defined conversion sequences that can convert from the source
5958 // type to the destination type or (when a conversion function is
5959 // used) to a derived class thereof are enumerated as described in
5960 // 13.3.1.4, and the best one is chosen through overload resolution
5961 // (13.3).
5962 else
5963 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5964 TopLevelOfInitList);
5965 return;
5966 }
5967
5968 assert(Args.size() >= 1 && "Zero-argument case handled above")(static_cast <bool> (Args.size() >= 1 && "Zero-argument case handled above"
) ? void (0) : __assert_fail ("Args.size() >= 1 && \"Zero-argument case handled above\""
, "clang/lib/Sema/SemaInit.cpp", 5968, __extension__ __PRETTY_FUNCTION__
))
;
5969
5970 // The remaining cases all need a source type.
5971 if (Args.size() > 1) {
5972 SetFailed(FK_TooManyInitsForScalar);
5973 return;
5974 } else if (isa<InitListExpr>(Args[0])) {
5975 SetFailed(FK_ParenthesizedListInitForScalar);
5976 return;
5977 }
5978
5979 // - Otherwise, if the source type is a (possibly cv-qualified) class
5980 // type, conversion functions are considered.
5981 if (!SourceType.isNull() && SourceType->isRecordType()) {
5982 // For a conversion to _Atomic(T) from either T or a class type derived
5983 // from T, initialize the T object then convert to _Atomic type.
5984 bool NeedAtomicConversion = false;
5985 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5986 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5987 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
5988 Atomic->getValueType())) {
5989 DestType = Atomic->getValueType();
5990 NeedAtomicConversion = true;
5991 }
5992 }
5993
5994 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5995 TopLevelOfInitList);
5996 MaybeProduceObjCObject(S, *this, Entity);
5997 if (!Failed() && NeedAtomicConversion)
5998 AddAtomicConversionStep(Entity.getType());
5999 return;
6000 }
6001
6002 // - Otherwise, if the initialization is direct-initialization, the source
6003 // type is std::nullptr_t, and the destination type is bool, the initial
6004 // value of the object being initialized is false.
6005 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6006 DestType->isBooleanType() &&
6007 Kind.getKind() == InitializationKind::IK_Direct) {
6008 AddConversionSequenceStep(
6009 ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
6010 Initializer->isGLValue()),
6011 DestType);
6012 return;
6013 }
6014
6015 // - Otherwise, the initial value of the object being initialized is the
6016 // (possibly converted) value of the initializer expression. Standard
6017 // conversions (Clause 4) will be used, if necessary, to convert the
6018 // initializer expression to the cv-unqualified version of the
6019 // destination type; no user-defined conversions are considered.
6020
6021 ImplicitConversionSequence ICS
6022 = S.TryImplicitConversion(Initializer, DestType,
6023 /*SuppressUserConversions*/true,
6024 Sema::AllowedExplicit::None,
6025 /*InOverloadResolution*/ false,
6026 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6027 allowObjCWritebackConversion);
6028
6029 if (ICS.isStandard() &&
6030 ICS.Standard.Second == ICK_Writeback_Conversion) {
6031 // Objective-C ARC writeback conversion.
6032
6033 // We should copy unless we're passing to an argument explicitly
6034 // marked 'out'.
6035 bool ShouldCopy = true;
6036 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6037 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6038
6039 // If there was an lvalue adjustment, add it as a separate conversion.
6040 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6041 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6042 ImplicitConversionSequence LvalueICS;
6043 LvalueICS.setStandard();
6044 LvalueICS.Standard.setAsIdentityConversion();
6045 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6046 LvalueICS.Standard.First = ICS.Standard.First;
6047 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6048 }
6049
6050 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6051 } else if (ICS.isBad()) {
6052 DeclAccessPair dap;
6053 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
6054 AddZeroInitializationStep(Entity.getType());
6055 } else if (Initializer->getType() == Context.OverloadTy &&
6056 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
6057 false, dap))
6058 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
6059 else if (Initializer->getType()->isFunctionType() &&
6060 isExprAnUnaddressableFunction(S, Initializer))
6061 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
6062 else
6063 SetFailed(InitializationSequence::FK_ConversionFailed);
6064 } else {
6065 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6066
6067 MaybeProduceObjCObject(S, *this, Entity);
6068 }
6069}
6070
6071InitializationSequence::~InitializationSequence() {
6072 for (auto &S : Steps)
6073 S.Destroy();
6074}
6075
6076//===----------------------------------------------------------------------===//
6077// Perform initialization
6078//===----------------------------------------------------------------------===//
6079static Sema::AssignmentAction
6080getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6081 switch(Entity.getKind()) {
6082 case InitializedEntity::EK_Variable:
6083 case InitializedEntity::EK_New:
6084 case InitializedEntity::EK_Exception:
6085 case InitializedEntity::EK_Base:
6086 case InitializedEntity::EK_Delegating:
6087 return Sema::AA_Initializing;
6088
6089 case InitializedEntity::EK_Parameter:
6090 if (Entity.getDecl() &&
6091 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6092 return Sema::AA_Sending;
6093
6094 return Sema::AA_Passing;
6095
6096 case InitializedEntity::EK_Parameter_CF_Audited:
6097 if (Entity.getDecl() &&
6098 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6099 return Sema::AA_Sending;
6100
6101 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6102
6103 case InitializedEntity::EK_Result:
6104 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6105 return Sema::AA_Returning;
6106
6107 case InitializedEntity::EK_Temporary:
6108 case InitializedEntity::EK_RelatedResult:
6109 // FIXME: Can we tell apart casting vs. converting?
6110 return Sema::AA_Casting;
6111
6112 case InitializedEntity::EK_TemplateParameter:
6113 // This is really initialization, but refer to it as conversion for
6114 // consistency with CheckConvertedConstantExpression.
6115 return Sema::AA_Converting;
6116
6117 case InitializedEntity::EK_Member:
6118 case InitializedEntity::EK_Binding:
6119 case InitializedEntity::EK_ArrayElement:
6120 case InitializedEntity::EK_VectorElement:
6121 case InitializedEntity::EK_ComplexElement:
6122 case InitializedEntity::EK_BlockElement:
6123 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6124 case InitializedEntity::EK_LambdaCapture:
6125 case InitializedEntity::EK_CompoundLiteralInit:
6126 return Sema::AA_Initializing;
6127 }
6128
6129 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 6129)
;
6130}
6131
6132/// Whether we should bind a created object as a temporary when
6133/// initializing the given entity.
6134static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6135 switch (Entity.getKind()) {
6136 case InitializedEntity::EK_ArrayElement:
6137 case InitializedEntity::EK_Member:
6138 case InitializedEntity::EK_Result:
6139 case InitializedEntity::EK_StmtExprResult:
6140 case InitializedEntity::EK_New:
6141 case InitializedEntity::EK_Variable:
6142 case InitializedEntity::EK_Base:
6143 case InitializedEntity::EK_Delegating:
6144 case InitializedEntity::EK_VectorElement:
6145 case InitializedEntity::EK_ComplexElement:
6146 case InitializedEntity::EK_Exception:
6147 case InitializedEntity::EK_BlockElement:
6148 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6149 case InitializedEntity::EK_LambdaCapture:
6150 case InitializedEntity::EK_CompoundLiteralInit:
6151 case InitializedEntity::EK_TemplateParameter:
6152 return false;
6153
6154 case InitializedEntity::EK_Parameter:
6155 case InitializedEntity::EK_Parameter_CF_Audited:
6156 case InitializedEntity::EK_Temporary:
6157 case InitializedEntity::EK_RelatedResult:
6158 case InitializedEntity::EK_Binding:
6159 return true;
6160 }
6161
6162 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "clang/lib/Sema/SemaInit.cpp", 6162)
;
6163}
6164
6165/// Whether the given entity, when initialized with an object
6166/// created for that initialization, requires destruction.
6167static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6168 switch (Entity.getKind()) {
6169 case InitializedEntity::EK_Result:
6170 case InitializedEntity::EK_StmtExprResult:
6171 case InitializedEntity::EK_New:
6172 case InitializedEntity::EK_Base:
6173 case InitializedEntity::EK_Delegating:
6174 case InitializedEntity::EK_VectorElement:
6175 case InitializedEntity::EK_ComplexElement:
6176 case InitializedEntity::EK_BlockElement:
6177 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6178 case InitializedEntity::EK_LambdaCapture:
6179 return false;
6180
6181 case InitializedEntity::EK_Member:
6182 case InitializedEntity::EK_Binding:
6183 case InitializedEntity::EK_Variable:
6184 case InitializedEntity::EK_Parameter:
6185 case InitializedEntity::EK_Parameter_CF_Audited:
6186 case InitializedEntity::EK_TemplateParameter:
6187 case InitializedEntity::EK_Temporary:
6188 case InitializedEntity::EK_ArrayElement:
6189 case InitializedEntity::EK_Exception:
6190 case InitializedEntity::EK_CompoundLiteralInit:
6191 case InitializedEntity::EK_RelatedResult:
6192 return true;
6193 }
6194
6195 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "clang/lib/Sema/SemaInit.cpp", 6195)
;
6196}
6197
6198/// Get the location at which initialization diagnostics should appear.
6199static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
6200 Expr *Initializer) {
6201 switch (Entity.getKind()) {
6202 case InitializedEntity::EK_Result:
6203 case InitializedEntity::EK_StmtExprResult:
6204 return Entity.getReturnLoc();
6205
6206 case InitializedEntity::EK_Exception:
6207 return Entity.getThrowLoc();
6208
6209 case InitializedEntity::EK_Variable:
6210 case InitializedEntity::EK_Binding:
6211 return Entity.getDecl()->getLocation();
6212
6213 case InitializedEntity::EK_LambdaCapture:
6214 return Entity.getCaptureLoc();
6215
6216 case InitializedEntity::EK_ArrayElement:
6217 case InitializedEntity::EK_Member:
6218 case InitializedEntity::EK_Parameter:
6219 case InitializedEntity::EK_Parameter_CF_Audited:
6220 case InitializedEntity::EK_TemplateParameter:
6221 case InitializedEntity::EK_Temporary:
6222 case InitializedEntity::EK_New:
6223 case InitializedEntity::EK_Base:
6224 case InitializedEntity::EK_Delegating:
6225 case InitializedEntity::EK_VectorElement:
6226 case InitializedEntity::EK_ComplexElement:
6227 case InitializedEntity::EK_BlockElement:
6228 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6229 case InitializedEntity::EK_CompoundLiteralInit:
6230 case InitializedEntity::EK_RelatedResult:
6231 return Initializer->getBeginLoc();
6232 }
6233 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "clang/lib/Sema/SemaInit.cpp", 6233)
;
6234}
6235
6236/// Make a (potentially elidable) temporary copy of the object
6237/// provided by the given initializer by calling the appropriate copy
6238/// constructor.
6239///
6240/// \param S The Sema object used for type-checking.
6241///
6242/// \param T The type of the temporary object, which must either be
6243/// the type of the initializer expression or a superclass thereof.
6244///
6245/// \param Entity The entity being initialized.
6246///
6247/// \param CurInit The initializer expression.
6248///
6249/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6250/// is permitted in C++03 (but not C++0x) when binding a reference to
6251/// an rvalue.
6252///
6253/// \returns An expression that copies the initializer expression into
6254/// a temporary object, or an error expression if a copy could not be
6255/// created.
6256static ExprResult CopyObject(Sema &S,
6257 QualType T,
6258 const InitializedEntity &Entity,
6259 ExprResult CurInit,
6260 bool IsExtraneousCopy) {
6261 if (CurInit.isInvalid())
6262 return CurInit;
6263 // Determine which class type we're copying to.
6264 Expr *CurInitExpr = (Expr *)CurInit.get();
6265 CXXRecordDecl *Class = nullptr;
6266 if (const RecordType *Record = T->getAs<RecordType>())
6267 Class = cast<CXXRecordDecl>(Record->getDecl());
6268 if (!Class)
6269 return CurInit;
6270
6271 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6272
6273 // Make sure that the type we are copying is complete.
6274 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6275 return CurInit;
6276
6277 // Perform overload resolution using the class's constructors. Per
6278 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6279 // is direct-initialization.
6280 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6281 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
6282
6283 OverloadCandidateSet::iterator Best;
6284 switch (ResolveConstructorOverload(
6285 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6286 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6287 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6288 /*SecondStepOfCopyInit=*/true)) {
6289 case OR_Success:
6290 break;
6291
6292 case OR_No_Viable_Function:
6293 CandidateSet.NoteCandidates(
6294 PartialDiagnosticAt(
6295 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6296 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6297 : diag::err_temp_copy_no_viable)
6298 << (int)Entity.getKind() << CurInitExpr->getType()
6299 << CurInitExpr->getSourceRange()),
6300 S, OCD_AllCandidates, CurInitExpr);
6301 if (!IsExtraneousCopy || S.isSFINAEContext())
6302 return ExprError();
6303 return CurInit;
6304
6305 case OR_Ambiguous:
6306 CandidateSet.NoteCandidates(
6307 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6308 << (int)Entity.getKind()
6309 << CurInitExpr->getType()
6310 << CurInitExpr->getSourceRange()),
6311 S, OCD_AmbiguousCandidates, CurInitExpr);
6312 return ExprError();
6313
6314 case OR_Deleted:
6315 S.Diag(Loc, diag::err_temp_copy_deleted)
6316 << (int)Entity.getKind() << CurInitExpr->getType()
6317 << CurInitExpr->getSourceRange();
6318 S.NoteDeletedFunction(Best->Function);
6319 return ExprError();
6320 }
6321
6322 bool HadMultipleCandidates = CandidateSet.size() > 1;
6323
6324 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6325 SmallVector<Expr*, 8> ConstructorArgs;
6326 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6327
6328 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6329 IsExtraneousCopy);
6330
6331 if (IsExtraneousCopy) {
6332 // If this is a totally extraneous copy for C++03 reference
6333 // binding purposes, just return the original initialization
6334 // expression. We don't generate an (elided) copy operation here
6335 // because doing so would require us to pass down a flag to avoid
6336 // infinite recursion, where each step adds another extraneous,
6337 // elidable copy.
6338
6339 // Instantiate the default arguments of any extra parameters in
6340 // the selected copy constructor, as if we were going to create a
6341 // proper call to the copy constructor.
6342 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6343 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6344 if (S.RequireCompleteType(Loc, Parm->getType(),
6345 diag::err_call_incomplete_argument))
6346 break;
6347
6348 // Build the default argument expression; we don't actually care
6349 // if this succeeds or not, because this routine will complain
6350 // if there was a problem.
6351 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6352 }
6353
6354 return CurInitExpr;
6355 }
6356
6357 // Determine the arguments required to actually perform the
6358 // constructor call (we might have derived-to-base conversions, or
6359 // the copy constructor may have default arguments).
6360 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6361 ConstructorArgs))
6362 return ExprError();
6363
6364 // C++0x [class.copy]p32:
6365 // When certain criteria are met, an implementation is allowed to
6366 // omit the copy/move construction of a class object, even if the
6367 // copy/move constructor and/or destructor for the object have
6368 // side effects. [...]
6369 // - when a temporary class object that has not been bound to a
6370 // reference (12.2) would be copied/moved to a class object
6371 // with the same cv-unqualified type, the copy/move operation
6372 // can be omitted by constructing the temporary object
6373 // directly into the target of the omitted copy/move
6374 //
6375 // Note that the other three bullets are handled elsewhere. Copy
6376 // elision for return statements and throw expressions are handled as part
6377 // of constructor initialization, while copy elision for exception handlers
6378 // is handled by the run-time.
6379 //
6380 // FIXME: If the function parameter is not the same type as the temporary, we
6381 // should still be able to elide the copy, but we don't have a way to
6382 // represent in the AST how much should be elided in this case.
6383 bool Elidable =
6384 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6385 S.Context.hasSameUnqualifiedType(
6386 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6387 CurInitExpr->getType());
6388
6389 // Actually perform the constructor call.
6390 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6391 Elidable,
6392 ConstructorArgs,
6393 HadMultipleCandidates,
6394 /*ListInit*/ false,
6395 /*StdInitListInit*/ false,
6396 /*ZeroInit*/ false,
6397 CXXConstructExpr::CK_Complete,
6398 SourceRange());
6399
6400 // If we're supposed to bind temporaries, do so.
6401 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6402 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6403 return CurInit;
6404}
6405
6406/// Check whether elidable copy construction for binding a reference to
6407/// a temporary would have succeeded if we were building in C++98 mode, for
6408/// -Wc++98-compat.
6409static void CheckCXX98CompatAccessibleCopy(Sema &S,
6410 const InitializedEntity &Entity,
6411 Expr *CurInitExpr) {
6412 assert(S.getLangOpts().CPlusPlus11)(static_cast <bool> (S.getLangOpts().CPlusPlus11) ? void
(0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "clang/lib/Sema/SemaInit.cpp"
, 6412, __extension__ __PRETTY_FUNCTION__))
;
6413
6414 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6415 if (!Record)
6416 return;
6417
6418 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6419 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6420 return;
6421
6422 // Find constructors which would have been considered.
6423 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6424 DeclContext::lookup_result Ctors =
6425 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6426
6427 // Perform overload resolution.
6428 OverloadCandidateSet::iterator Best;
6429 OverloadingResult OR = ResolveConstructorOverload(
6430 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6431 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6432 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6433 /*SecondStepOfCopyInit=*/true);
6434
6435 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6436 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6437 << CurInitExpr->getSourceRange();
6438
6439 switch (OR) {
6440 case OR_Success:
6441 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6442 Best->FoundDecl, Entity, Diag);
6443 // FIXME: Check default arguments as far as that's possible.
6444 break;
6445
6446 case OR_No_Viable_Function:
6447 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6448 OCD_AllCandidates, CurInitExpr);
6449 break;
6450
6451 case OR_Ambiguous:
6452 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6453 OCD_AmbiguousCandidates, CurInitExpr);
6454 break;
6455
6456 case OR_Deleted:
6457 S.Diag(Loc, Diag);
6458 S.NoteDeletedFunction(Best->Function);
6459 break;
6460 }
6461}
6462
6463void InitializationSequence::PrintInitLocationNote(Sema &S,
6464 const InitializedEntity &Entity) {
6465 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6466 if (Entity.getDecl()->getLocation().isInvalid())
6467 return;
6468
6469 if (Entity.getDecl()->getDeclName())
6470 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6471 << Entity.getDecl()->getDeclName();
6472 else
6473 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6474 }
6475 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6476 Entity.getMethodDecl())
6477 S.Diag(Entity.getMethodDecl()->getLocation(),
6478 diag::note_method_return_type_change)
6479 << Entity.getMethodDecl()->getDeclName();
6480}
6481
6482/// Returns true if the parameters describe a constructor initialization of
6483/// an explicit temporary object, e.g. "Point(x, y)".
6484static bool isExplicitTemporary(const InitializedEntity &Entity,
6485 const InitializationKind &Kind,
6486 unsigned NumArgs) {
6487 switch (Entity.getKind()) {
6488 case InitializedEntity::EK_Temporary:
6489 case InitializedEntity::EK_CompoundLiteralInit:
6490 case InitializedEntity::EK_RelatedResult:
6491 break;
6492 default:
6493 return false;
6494 }
6495
6496 switch (Kind.getKind()) {
6497 case InitializationKind::IK_DirectList:
6498 return true;
6499 // FIXME: Hack to work around cast weirdness.
6500 case InitializationKind::IK_Direct:
6501 case InitializationKind::IK_Value:
6502 return NumArgs != 1;
6503 default:
6504 return false;
6505 }
6506}
6507
6508static ExprResult
6509PerformConstructorInitialization(Sema &S,
6510 const InitializedEntity &Entity,
6511 const InitializationKind &Kind,
6512 MultiExprArg Args,
6513 const InitializationSequence::Step& Step,
6514 bool &ConstructorInitRequiresZeroInit,
6515 bool IsListInitialization,
6516 bool IsStdInitListInitialization,
6517 SourceLocation LBraceLoc,
6518 SourceLocation RBraceLoc) {
6519 unsigned NumArgs = Args.size();
6520 CXXConstructorDecl *Constructor
6521 = cast<CXXConstructorDecl>(Step.Function.Function);
6522 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6523
6524 // Build a call to the selected constructor.
6525 SmallVector<Expr*, 8> ConstructorArgs;
6526 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6527 ? Kind.getEqualLoc()
6528 : Kind.getLocation();
6529
6530 if (Kind.getKind() == InitializationKind::IK_Default) {
6531 // Force even a trivial, implicit default constructor to be
6532 // semantically checked. We do this explicitly because we don't build
6533 // the definition for completely trivial constructors.
6534 assert(Constructor->getParent() && "No parent class for constructor.")(static_cast <bool> (Constructor->getParent() &&
"No parent class for constructor.") ? void (0) : __assert_fail
("Constructor->getParent() && \"No parent class for constructor.\""
, "clang/lib/Sema/SemaInit.cpp", 6534, __extension__ __PRETTY_FUNCTION__
))
;
6535 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6536 Constructor->isTrivial() && !Constructor->isUsed(false)) {
6537 S.runWithSufficientStackSpace(Loc, [&] {
6538 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6539 });
6540 }
6541 }
6542
6543 ExprResult CurInit((Expr *)nullptr);
6544
6545 // C++ [over.match.copy]p1:
6546 // - When initializing a temporary to be bound to the first parameter
6547 // of a constructor that takes a reference to possibly cv-qualified
6548 // T as its first argument, called with a single argument in the
6549 // context of direct-initialization, explicit conversion functions
6550 // are also considered.
6551 bool AllowExplicitConv =
6552 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6553 hasCopyOrMoveCtorParam(S.Context,
6554 getConstructorInfo(Step.Function.FoundDecl));
6555
6556 // Determine the arguments required to actually perform the constructor
6557 // call.
6558 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
6559 ConstructorArgs, AllowExplicitConv,
6560 IsListInitialization))
6561 return ExprError();
6562
6563 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6564 // An explicitly-constructed temporary, e.g., X(1, 2).
6565 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6566 return ExprError();
6567
6568 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6569 if (!TSInfo)
6570 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6571 SourceRange ParenOrBraceRange =
6572 (Kind.getKind() == InitializationKind::IK_DirectList)
6573 ? SourceRange(LBraceLoc, RBraceLoc)
6574 : Kind.getParenOrBraceRange();
6575
6576 CXXConstructorDecl *CalleeDecl = Constructor;
6577 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6578 Step.Function.FoundDecl.getDecl())) {
6579 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
6580 if (S.DiagnoseUseOfDecl(CalleeDecl, Loc))
6581 return ExprError();
6582 }
6583 S.MarkFunctionReferenced(Loc, CalleeDecl);
6584
6585 CurInit = S.CheckForImmediateInvocation(
6586 CXXTemporaryObjectExpr::Create(
6587 S.Context, CalleeDecl,
6588 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6589 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6590 IsListInitialization, IsStdInitListInitialization,
6591 ConstructorInitRequiresZeroInit),
6592 CalleeDecl);
6593 } else {
6594 CXXConstructExpr::ConstructionKind ConstructKind =
6595 CXXConstructExpr::CK_Complete;
6596
6597 if (Entity.getKind() == InitializedEntity::EK_Base) {
6598 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6599 CXXConstructExpr::CK_VirtualBase :
6600 CXXConstructExpr::CK_NonVirtualBase;
6601 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6602 ConstructKind = CXXConstructExpr::CK_Delegating;
6603 }
6604
6605 // Only get the parenthesis or brace range if it is a list initialization or
6606 // direct construction.
6607 SourceRange ParenOrBraceRange;
6608 if (IsListInitialization)
6609 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6610 else if (Kind.getKind() == InitializationKind::IK_Direct)
6611 ParenOrBraceRange = Kind.getParenOrBraceRange();
6612
6613 // If the entity allows NRVO, mark the construction as elidable
6614 // unconditionally.
6615 if (Entity.allowsNRVO())
6616 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6617 Step.Function.FoundDecl,
6618 Constructor, /*Elidable=*/true,
6619 ConstructorArgs,
6620 HadMultipleCandidates,
6621 IsListInitialization,
6622 IsStdInitListInitialization,
6623 ConstructorInitRequiresZeroInit,
6624 ConstructKind,
6625 ParenOrBraceRange);
6626 else
6627 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6628 Step.Function.FoundDecl,
6629 Constructor,
6630 ConstructorArgs,
6631 HadMultipleCandidates,
6632 IsListInitialization,
6633 IsStdInitListInitialization,
6634 ConstructorInitRequiresZeroInit,
6635 ConstructKind,
6636 ParenOrBraceRange);
6637 }
6638 if (CurInit.isInvalid())
6639 return ExprError();
6640
6641 // Only check access if all of that succeeded.
6642 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
6643 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6644 return ExprError();
6645
6646 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
6647 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
6648 return ExprError();
6649
6650 if (shouldBindAsTemporary(Entity))
6651 CurInit = S.MaybeBindToTemporary(CurInit.get());
6652
6653 return CurInit;
6654}
6655
6656namespace {
6657enum LifetimeKind {
6658 /// The lifetime of a temporary bound to this entity ends at the end of the
6659 /// full-expression, and that's (probably) fine.
6660 LK_FullExpression,
6661
6662 /// The lifetime of a temporary bound to this entity is extended to the
6663 /// lifeitme of the entity itself.
6664 LK_Extended,
6665
6666 /// The lifetime of a temporary bound to this entity probably ends too soon,
6667 /// because the entity is allocated in a new-expression.
6668 LK_New,
6669
6670 /// The lifetime of a temporary bound to this entity ends too soon, because
6671 /// the entity is a return object.
6672 LK_Return,
6673
6674 /// The lifetime of a temporary bound to this entity ends too soon, because
6675 /// the entity is the result of a statement expression.
6676 LK_StmtExprResult,
6677
6678 /// This is a mem-initializer: if it would extend a temporary (other than via
6679 /// a default member initializer), the program is ill-formed.
6680 LK_MemInitializer,
6681};
6682using LifetimeResult =
6683 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6684}
6685
6686/// Determine the declaration which an initialized entity ultimately refers to,
6687/// for the purpose of lifetime-extending a temporary bound to a reference in
6688/// the initialization of \p Entity.
6689static LifetimeResult getEntityLifetime(
6690 const InitializedEntity *Entity,
6691 const InitializedEntity *InitField = nullptr) {
6692 // C++11 [class.temporary]p5:
6693 switch (Entity->getKind()) {
6694 case InitializedEntity::EK_Variable:
6695 // The temporary [...] persists for the lifetime of the reference
6696 return {Entity, LK_Extended};
6697
6698 case InitializedEntity::EK_Member:
6699 // For subobjects, we look at the complete object.
6700 if (Entity->getParent())
6701 return getEntityLifetime(Entity->getParent(), Entity);
6702
6703 // except:
6704 // C++17 [class.base.init]p8:
6705 // A temporary expression bound to a reference member in a
6706 // mem-initializer is ill-formed.
6707 // C++17 [class.base.init]p11:
6708 // A temporary expression bound to a reference member from a
6709 // default member initializer is ill-formed.
6710 //
6711 // The context of p11 and its example suggest that it's only the use of a
6712 // default member initializer from a constructor that makes the program
6713 // ill-formed, not its mere existence, and that it can even be used by
6714 // aggregate initialization.
6715 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6716 : LK_MemInitializer};
6717
6718 case InitializedEntity::EK_Binding:
6719 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6720 // type.
6721 return {Entity, LK_Extended};
6722
6723 case InitializedEntity::EK_Parameter:
6724 case InitializedEntity::EK_Parameter_CF_Audited:
6725 // -- A temporary bound to a reference parameter in a function call
6726 // persists until the completion of the full-expression containing
6727 // the call.
6728 return {nullptr, LK_FullExpression};
6729
6730 case InitializedEntity::EK_TemplateParameter:
6731 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
6732 return {nullptr, LK_FullExpression};
6733
6734 case InitializedEntity::EK_Result:
6735 // -- The lifetime of a temporary bound to the returned value in a
6736 // function return statement is not extended; the temporary is
6737 // destroyed at the end of the full-expression in the return statement.
6738 return {nullptr, LK_Return};
6739
6740 case InitializedEntity::EK_StmtExprResult:
6741 // FIXME: Should we lifetime-extend through the result of a statement
6742 // expression?
6743 return {nullptr, LK_StmtExprResult};
6744
6745 case InitializedEntity::EK_New:
6746 // -- A temporary bound to a reference in a new-initializer persists
6747 // until the completion of the full-expression containing the
6748 // new-initializer.
6749 return {nullptr, LK_New};
6750
6751 case InitializedEntity::EK_Temporary:
6752 case InitializedEntity::EK_CompoundLiteralInit:
6753 case InitializedEntity::EK_RelatedResult:
6754 // We don't yet know the storage duration of the surrounding temporary.
6755 // Assume it's got full-expression duration for now, it will patch up our
6756 // storage duration if that's not correct.
6757 return {nullptr, LK_FullExpression};
6758
6759 case InitializedEntity::EK_ArrayElement:
6760 // For subobjects, we look at the complete object.
6761 return getEntityLifetime(Entity->getParent(), InitField);
6762
6763 case InitializedEntity::EK_Base:
6764 // For subobjects, we look at the complete object.
6765 if (Entity->getParent())
6766 return getEntityLifetime(Entity->getParent(), InitField);
6767 return {InitField, LK_MemInitializer};
6768
6769 case InitializedEntity::EK_Delegating:
6770 // We can reach this case for aggregate initialization in a constructor:
6771 // struct A { int &&r; };
6772 // struct B : A { B() : A{0} {} };
6773 // In this case, use the outermost field decl as the context.
6774 return {InitField, LK_MemInitializer};
6775
6776 case InitializedEntity::EK_BlockElement:
6777 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6778 case InitializedEntity::EK_LambdaCapture:
6779 case InitializedEntity::EK_VectorElement:
6780 case InitializedEntity::EK_ComplexElement:
6781 return {nullptr, LK_FullExpression};
6782
6783 case InitializedEntity::EK_Exception:
6784 // FIXME: Can we diagnose lifetime problems with exceptions?
6785 return {nullptr, LK_FullExpression};
6786 }
6787 llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "clang/lib/Sema/SemaInit.cpp"
, 6787)
;
6788}
6789
6790namespace {
6791enum ReferenceKind {
6792 /// Lifetime would be extended by a reference binding to a temporary.
6793 RK_ReferenceBinding,
6794 /// Lifetime would be extended by a std::initializer_list object binding to
6795 /// its backing array.
6796 RK_StdInitializerList,
6797};
6798
6799/// A temporary or local variable. This will be one of:
6800/// * A MaterializeTemporaryExpr.
6801/// * A DeclRefExpr whose declaration is a local.
6802/// * An AddrLabelExpr.
6803/// * A BlockExpr for a block with captures.
6804using Local = Expr*;
6805
6806/// Expressions we stepped over when looking for the local state. Any steps
6807/// that would inhibit lifetime extension or take us out of subexpressions of
6808/// the initializer are included.
6809struct IndirectLocalPathEntry {
6810 enum EntryKind {
6811 DefaultInit,
6812 AddressOf,
6813 VarInit,
6814 LValToRVal,
6815 LifetimeBoundCall,
6816 TemporaryCopy,
6817 LambdaCaptureInit,
6818 GslReferenceInit,
6819 GslPointerInit
6820 } Kind;
6821 Expr *E;
6822 union {
6823 const Decl *D = nullptr;
6824 const LambdaCapture *Capture;
6825 };
6826 IndirectLocalPathEntry() {}
6827 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
6828 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6829 : Kind(K), E(E), D(D) {}
6830 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
6831 : Kind(K), E(E), Capture(Capture) {}
6832};
6833
6834using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
6835
6836struct RevertToOldSizeRAII {
6837 IndirectLocalPath &Path;
6838 unsigned OldSize = Path.size();
6839 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
6840 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6841};
6842
6843using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6844 ReferenceKind RK)>;
6845}
6846
6847static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6848 for (auto E : Path)
6849 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6850 return true;
6851 return false;
6852}
6853
6854static bool pathContainsInit(IndirectLocalPath &Path) {
6855 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
6856 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6857 E.Kind == IndirectLocalPathEntry::VarInit;
6858 });
6859}
6860
6861static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6862 Expr *Init, LocalVisitor Visit,
6863 bool RevisitSubinits,
6864 bool EnableLifetimeWarnings);
6865
6866static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6867 Expr *Init, ReferenceKind RK,
6868 LocalVisitor Visit,
6869 bool EnableLifetimeWarnings);
6870
6871template <typename T> static bool isRecordWithAttr(QualType Type) {
6872 if (auto *RD = Type->getAsCXXRecordDecl())
6873 return RD->hasAttr<T>();
6874 return false;
6875}
6876
6877// Decl::isInStdNamespace will return false for iterators in some STL
6878// implementations due to them being defined in a namespace outside of the std
6879// namespace.
6880static bool isInStlNamespace(const Decl *D) {
6881 const DeclContext *DC = D->getDeclContext();
6882 if (!DC)
6883 return false;
6884 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
6885 if (const IdentifierInfo *II = ND->getIdentifier()) {
6886 StringRef Name = II->getName();
6887 if (Name.size() >= 2 && Name.front() == '_' &&
6888 (Name[1] == '_' || isUppercase(Name[1])))
6889 return true;
6890 }
6891
6892 return DC->isStdNamespace();
6893}
6894
6895static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
6896 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
6897 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
6898 return true;
6899 if (!isInStlNamespace(Callee->getParent()))
6900 return false;
6901 if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
6902 !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
6903 return false;
6904 if (Callee->getReturnType()->isPointerType() ||
6905 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
6906 if (!Callee->getIdentifier())
6907 return false;
6908 return llvm::StringSwitch<bool>(Callee->getName())
6909 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
6910 .Cases("end", "rend", "cend", "crend", true)
6911 .Cases("c_str", "data", "get", true)
6912 // Map and set types.
6913 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
6914 .Default(false);
6915 } else if (Callee->getReturnType()->isReferenceType()) {
6916 if (!Callee->getIdentifier()) {
6917 auto OO = Callee->getOverloadedOperator();
6918 return OO == OverloadedOperatorKind::OO_Subscript ||
6919 OO == OverloadedOperatorKind::OO_Star;
6920 }
6921 return llvm::StringSwitch<bool>(Callee->getName())
6922 .Cases("front", "back", "at", "top", "value", true)
6923 .Default(false);
6924 }
6925 return false;
6926}
6927
6928static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
6929 if (!FD->getIdentifier() || FD->getNumParams() != 1)
6930 return false;
6931 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
6932 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
6933 return false;
6934 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
6935 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
6936 return false;
6937 if (FD->getReturnType()->isPointerType() ||
6938 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
6939 return llvm::StringSwitch<bool>(FD->getName())
6940 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
6941 .Cases("end", "rend", "cend", "crend", true)
6942 .Case("data", true)
6943 .Default(false);
6944 } else if (FD->getReturnType()->isReferenceType()) {
6945 return llvm::StringSwitch<bool>(FD->getName())
6946 .Cases("get", "any_cast", true)
6947 .Default(false);
6948 }
6949 return false;
6950}
6951
6952static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
6953 LocalVisitor Visit) {
6954 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
6955 // We are not interested in the temporary base objects of gsl Pointers:
6956 // Temp().ptr; // Here ptr might not dangle.
6957 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
6958 return;
6959 // Once we initialized a value with a reference, it can no longer dangle.
6960 if (!Value) {
6961 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
6962 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
6963 continue;
6964 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
6965 return;
6966 break;
6967 }
6968 }
6969 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
6970 : IndirectLocalPathEntry::GslReferenceInit,
6971 Arg, D});
6972 if (Arg->isGLValue())
6973 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6974 Visit,
6975 /*EnableLifetimeWarnings=*/true);
6976 else
6977 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
6978 /*EnableLifetimeWarnings=*/true);
6979 Path.pop_back();
6980 };
6981
6982 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6983 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
6984 if (MD && shouldTrackImplicitObjectArg(MD))
6985 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
6986 !MD->getReturnType()->isReferenceType());
6987 return;
6988 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
6989 FunctionDecl *Callee = OCE->getDirectCallee();
6990 if (Callee && Callee->isCXXInstanceMember() &&
6991 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
6992 VisitPointerArg(Callee, OCE->getArg(0),
6993 !Callee->getReturnType()->isReferenceType());
6994 return;
6995 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
6996 FunctionDecl *Callee = CE->getDirectCallee();
6997 if (Callee && shouldTrackFirstArgument(Callee))
6998 VisitPointerArg(Callee, CE->getArg(0),
6999 !Callee->getReturnType()->isReferenceType());
7000 return;
7001 }
7002
7003 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7004 const auto *Ctor = CCE->getConstructor();
7005 const CXXRecordDecl *RD = Ctor->getParent();
7006 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7007 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7008 }
7009}
7010
7011static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
7012 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
30
Calling 'DeclaratorDecl::getTypeSourceInfo'
33
Returning from 'DeclaratorDecl::getTypeSourceInfo'
7013 if (!TSI)
34
Assuming 'TSI' is non-null
35
Taking false branch
7014 return false;
7015 // Don't declare this variable in the second operand of the for-statement;
7016 // GCC miscompiles that by ending its lifetime before evaluating the
7017 // third operand. See gcc.gnu.org/PR86769.
7018 AttributedTypeLoc ATL;
7019 for (TypeLoc TL = TSI->getTypeLoc();
36
Loop condition is false. Execution continues on line 7029
7020 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7021 TL = ATL.getModifiedLoc()) {
7022 if (ATL.getAttrAs<LifetimeBoundAttr>())
7023 return true;
7024 }
7025
7026 // Assume that all assignment operators with a "normal" return type return
7027 // *this, that is, an lvalue reference that is the same type as the implicit
7028 // object parameter (or the LHS for a non-member operator$=).
7029 OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
7030 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
37
Assuming 'OO' is equal to OO_Equal
7031 QualType RetT = FD->getReturnType();
7032 if (RetT->isLValueReferenceType()) {
38
Taking true branch
7033 ASTContext &Ctx = FD->getASTContext();
7034 QualType LHST;
7035 auto *MD = dyn_cast<CXXMethodDecl>(FD);
39
Assuming 'FD' is not a 'CXXMethodDecl'
40
'MD' initialized to a null pointer value
7036 if (MD
40.1
'MD' is null
40.1
'MD' is null
&& MD->isCXXInstanceMember())
7037 LHST = Ctx.getLValueReferenceType(MD->getThisObjectType());
7038 else
7039 LHST = MD->getParamDecl(0)->getType();
41
Called C++ object pointer is null
7040 if (Ctx.hasSameType(RetT, LHST))
7041 return true;
7042 }
7043 }
7044
7045 return false;
7046}
7047
7048static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7049 LocalVisitor Visit) {
7050 const FunctionDecl *Callee;
7051 ArrayRef<Expr*> Args;
7052
7053 if (auto *CE
22.1
'CE' is non-null
22.1
'CE' is non-null
= dyn_cast<CallExpr>(Call)) {
22
'Call' is a 'CallExpr'
23
Taking true branch
7054 Callee = CE->getDirectCallee();
7055 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
7056 } else {
7057 auto *CCE = cast<CXXConstructExpr>(Call);
7058 Callee = CCE->getConstructor();
7059 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
7060 }
7061 if (!Callee
23.1
'Callee' is non-null
23.1
'Callee' is non-null
)
24
Taking false branch
7062 return;
7063
7064 Expr *ObjectArg = nullptr;
7065 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
25
Assuming 'Call' is not a 'CXXOperatorCallExpr'
7066 ObjectArg = Args[0];
7067 Args = Args.slice(1);
7068 } else if (auto *MCE
26.1
'MCE' is non-null
26.1
'MCE' is non-null
= dyn_cast<CXXMemberCallExpr>(Call)) {
26
Assuming 'Call' is a 'CXXMemberCallExpr'
27
Taking true branch
7069 ObjectArg = MCE->getImplicitObjectArgument();
7070 }
7071
7072 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7073 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7074 if (Arg->isGLValue())
7075 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7076 Visit,
7077 /*EnableLifetimeWarnings=*/false);
7078 else
7079 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7080 /*EnableLifetimeWarnings=*/false);
7081 Path.pop_back();
7082 };
7083
7084 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
28
Assuming 'ObjectArg' is non-null
29
Calling 'implicitObjectParamIsLifetimeBound'
7085 VisitLifetimeBoundArg(Callee, ObjectArg);
7086
7087 for (unsigned I = 0,
7088 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7089 I != N; ++I) {
7090 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7091 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7092 }
7093}
7094
7095/// Visit the locals that would be reachable through a reference bound to the
7096/// glvalue expression \c Init.
7097static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7098 Expr *Init, ReferenceKind RK,
7099 LocalVisitor Visit,
7100 bool EnableLifetimeWarnings) {
7101 RevertToOldSizeRAII RAII(Path);
7102
7103 // Walk past any constructs which we can lifetime-extend across.
7104 Expr *Old;
7105 do {
7106 Old = Init;
7107
7108 if (auto *FE = dyn_cast<FullExpr>(Init))
7109 Init = FE->getSubExpr();
7110
7111 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7112 // If this is just redundant braces around an initializer, step over it.
7113 if (ILE->isTransparent())
7114 Init = ILE->getInit(0);
7115 }
7116
7117 // Step over any subobject adjustments; we may have a materialized
7118 // temporary inside them.
7119 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7120
7121 // Per current approach for DR1376, look through casts to reference type
7122 // when performing lifetime extension.
7123 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7124 if (CE->getSubExpr()->isGLValue())
7125 Init = CE->getSubExpr();
7126
7127 // Per the current approach for DR1299, look through array element access
7128 // on array glvalues when performing lifetime extension.
7129 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7130 Init = ASE->getBase();
7131 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7132 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7133 Init = ICE->getSubExpr();
7134 else
7135 // We can't lifetime extend through this but we might still find some
7136 // retained temporaries.
7137 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7138 EnableLifetimeWarnings);
7139 }
7140
7141 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7142 // constructor inherits one as an implicit mem-initializer.
7143 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7144 Path.push_back(
7145 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7146 Init = DIE->getExpr();
7147 }
7148 } while (Init != Old);
7149
7150 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7151 if (Visit(Path, Local(MTE), RK))
7152 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7153 EnableLifetimeWarnings);
7154 }
7155
7156 if (isa<CallExpr>(Init)) {
7157 if (EnableLifetimeWarnings)
7158 handleGslAnnotatedTypes(Path, Init, Visit);
7159 return visitLifetimeBoundArguments(Path, Init, Visit);
7160 }
7161
7162 switch (Init->getStmtClass()) {
7163 case Stmt::DeclRefExprClass: {
7164 // If we find the name of a local non-reference parameter, we could have a
7165 // lifetime problem.
7166 auto *DRE = cast<DeclRefExpr>(Init);
7167 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7168 if (VD && VD->hasLocalStorage() &&
7169 !DRE->refersToEnclosingVariableOrCapture()) {
7170 if (!VD->getType()->isReferenceType()) {
7171 Visit(Path, Local(DRE), RK);
7172 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7173 // The lifetime of a reference parameter is unknown; assume it's OK
7174 // for now.
7175 break;
7176 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7177 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7178 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7179 RK_ReferenceBinding, Visit,
7180 EnableLifetimeWarnings);
7181 }
7182 }
7183 break;
7184 }
7185
7186 case Stmt::UnaryOperatorClass: {
7187 // The only unary operator that make sense to handle here
7188 // is Deref. All others don't resolve to a "name." This includes
7189 // handling all sorts of rvalues passed to a unary operator.
7190 const UnaryOperator *U = cast<UnaryOperator>(Init);
7191 if (U->getOpcode() == UO_Deref)
7192 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7193 EnableLifetimeWarnings);
7194 break;
7195 }
7196
7197 case Stmt::OMPArraySectionExprClass: {
7198 visitLocalsRetainedByInitializer(Path,
7199 cast<OMPArraySectionExpr>(Init)->getBase(),
7200 Visit, true, EnableLifetimeWarnings);
7201 break;
7202 }
7203
7204 case Stmt::ConditionalOperatorClass:
7205 case Stmt::BinaryConditionalOperatorClass: {
7206 auto *C = cast<AbstractConditionalOperator>(Init);
7207 if (!C->getTrueExpr()->getType()->isVoidType())
7208 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7209 EnableLifetimeWarnings);
7210 if (!C->getFalseExpr()->getType()->isVoidType())
7211 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7212 EnableLifetimeWarnings);
7213 break;
7214 }
7215
7216 // FIXME: Visit the left-hand side of an -> or ->*.
7217
7218 default:
7219 break;
7220 }
7221}
7222
7223/// Visit the locals that would be reachable through an object initialized by
7224/// the prvalue expression \c Init.
7225static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7226 Expr *Init, LocalVisitor Visit,
7227 bool RevisitSubinits,
7228 bool EnableLifetimeWarnings) {
7229 RevertToOldSizeRAII RAII(Path);
7230
7231 Expr *Old;
7232 do {
10
Loop condition is false. Exiting loop
7233 Old = Init;
7234
7235 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7236 // constructor inherits one as an implicit mem-initializer.
7237 if (auto *DIE
1.1
'DIE' is null
1.1
'DIE' is null
= dyn_cast<CXXDefaultInitExpr>(Init)) {
1
Assuming 'Init' is not a 'CXXDefaultInitExpr'
2
Taking false branch
7238 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7239 Init = DIE->getExpr();
7240 }
7241
7242 if (auto *FE
3.1
'FE' is null
3.1
'FE' is null
= dyn_cast<FullExpr>(Init))
3
Assuming 'Init' is not a 'FullExpr'
4
Taking false branch
7243 Init = FE->getSubExpr();
7244
7245 // Dig out the expression which constructs the extended temporary.
7246 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7247
7248 if (CXXBindTemporaryExpr *BTE
5.1
'BTE' is null
5.1
'BTE' is null
= dyn_cast<CXXBindTemporaryExpr>(Init))
5
Assuming 'Init' is not a 'CXXBindTemporaryExpr'
6
Taking false branch
7249 Init = BTE->getSubExpr();
7250
7251 Init = Init->IgnoreParens();
7252
7253 // Step over value-preserving rvalue casts.
7254 if (auto *CE
7.1
'CE' is null
7.1
'CE' is null
= dyn_cast<CastExpr>(Init)) {
7
Assuming 'Init' is not a 'CastExpr'
8
Taking false branch
7255 switch (CE->getCastKind()) {
7256 case CK_LValueToRValue:
7257 // If we can match the lvalue to a const object, we can look at its
7258 // initializer.
7259 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7260 return visitLocalsRetainedByReferenceBinding(
7261 Path, Init, RK_ReferenceBinding,
7262 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7263 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7264 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7265 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7266 !isVarOnPath(Path, VD)) {
7267 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7268 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7269 EnableLifetimeWarnings);
7270 }
7271 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7272 if (MTE->getType().isConstQualified())
7273 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7274 true, EnableLifetimeWarnings);
7275 }
7276 return false;
7277 }, EnableLifetimeWarnings);
7278
7279 // We assume that objects can be retained by pointers cast to integers,
7280 // but not if the integer is cast to floating-point type or to _Complex.
7281 // We assume that casts to 'bool' do not preserve enough information to
7282 // retain a local object.
7283 case CK_NoOp:
7284 case CK_BitCast:
7285 case CK_BaseToDerived:
7286 case CK_DerivedToBase:
7287 case CK_UncheckedDerivedToBase:
7288 case CK_Dynamic:
7289 case CK_ToUnion:
7290 case CK_UserDefinedConversion:
7291 case CK_ConstructorConversion:
7292 case CK_IntegralToPointer:
7293 case CK_PointerToIntegral:
7294 case CK_VectorSplat:
7295 case CK_IntegralCast:
7296 case CK_CPointerToObjCPointerCast:
7297 case CK_BlockPointerToObjCPointerCast:
7298 case CK_AnyPointerToBlockPointerCast:
7299 case CK_AddressSpaceConversion:
7300 break;
7301
7302 case CK_ArrayToPointerDecay:
7303 // Model array-to-pointer decay as taking the address of the array
7304 // lvalue.
7305 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7306 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7307 RK_ReferenceBinding, Visit,
7308 EnableLifetimeWarnings);
7309
7310 default:
7311 return;
7312 }
7313
7314 Init = CE->getSubExpr();
7315 }
7316 } while (Old != Init);
9
Assuming 'Old' is equal to 'Init'
7317
7318 // C++17 [dcl.init.list]p6:
7319 // initializing an initializer_list object from the array extends the
7320 // lifetime of the array exactly like binding a reference to a temporary.
7321 if (auto *ILE
11.1
'ILE' is null
11.1
'ILE' is null
= dyn_cast<CXXStdInitializerListExpr>(Init))
11
Assuming 'Init' is not a 'CXXStdInitializerListExpr'
12
Taking false branch
7322 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7323 RK_StdInitializerList, Visit,
7324 EnableLifetimeWarnings);
7325
7326 if (InitListExpr *ILE
13.1
'ILE' is null
13.1
'ILE' is null
= dyn_cast<InitListExpr>(Init)) {
13
Assuming 'Init' is not a 'InitListExpr'
14
Taking false branch
7327 // We already visited the elements of this initializer list while
7328 // performing the initialization. Don't visit them again unless we've
7329 // changed the lifetime of the initialized entity.
7330 if (!RevisitSubinits)
7331 return;
7332
7333 if (ILE->isTransparent())
7334 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7335 RevisitSubinits,
7336 EnableLifetimeWarnings);
7337
7338 if (ILE->getType()->isArrayType()) {
7339 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7340 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7341 RevisitSubinits,
7342 EnableLifetimeWarnings);
7343 return;
7344 }
7345
7346 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7347 assert(RD->isAggregate() && "aggregate init on non-aggregate")(static_cast <bool> (RD->isAggregate() && "aggregate init on non-aggregate"
) ? void (0) : __assert_fail ("RD->isAggregate() && \"aggregate init on non-aggregate\""
, "clang/lib/Sema/SemaInit.cpp", 7347, __extension__ __PRETTY_FUNCTION__
))
;
7348
7349 // If we lifetime-extend a braced initializer which is initializing an
7350 // aggregate, and that aggregate contains reference members which are
7351 // bound to temporaries, those temporaries are also lifetime-extended.
7352 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7353 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
7354 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
7355 RK_ReferenceBinding, Visit,
7356 EnableLifetimeWarnings);
7357 else {
7358 unsigned Index = 0;
7359 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7360 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7361 RevisitSubinits,
7362 EnableLifetimeWarnings);
7363 for (const auto *I : RD->fields()) {
7364 if (Index >= ILE->getNumInits())
7365 break;
7366 if (I->isUnnamedBitfield())
7367 continue;
7368 Expr *SubInit = ILE->getInit(Index);
7369 if (I->getType()->isReferenceType())
7370 visitLocalsRetainedByReferenceBinding(Path, SubInit,
7371 RK_ReferenceBinding, Visit,
7372 EnableLifetimeWarnings);
7373 else
7374 // This might be either aggregate-initialization of a member or
7375 // initialization of a std::initializer_list object. Regardless,
7376 // we should recursively lifetime-extend that initializer.
7377 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7378 RevisitSubinits,
7379 EnableLifetimeWarnings);
7380 ++Index;
7381 }
7382 }
7383 }
7384 return;
7385 }
7386
7387 // The lifetime of an init-capture is that of the closure object constructed
7388 // by a lambda-expression.
7389 if (auto *LE
15.1
'LE' is null
15.1
'LE' is null
= dyn_cast<LambdaExpr>(Init)) {
15
Assuming 'Init' is not a 'LambdaExpr'
16
Taking false branch
7390 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7391 for (Expr *E : LE->capture_inits()) {
7392 assert(CapI != LE->capture_end())(static_cast <bool> (CapI != LE->capture_end()) ? void
(0) : __assert_fail ("CapI != LE->capture_end()", "clang/lib/Sema/SemaInit.cpp"
, 7392, __extension__ __PRETTY_FUNCTION__))
;
7393 const LambdaCapture &Cap = *CapI++;
7394 if (!E)
7395 continue;
7396 if (Cap.capturesVariable())
7397 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7398 if (E->isGLValue())
7399 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7400 Visit, EnableLifetimeWarnings);
7401 else
7402 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7403 EnableLifetimeWarnings);
7404 if (Cap.capturesVariable())
7405 Path.pop_back();
7406 }
7407 }
7408
7409 // Assume that a copy or move from a temporary references the same objects
7410 // that the temporary does.
7411 if (auto *CCE
17.1
'CCE' is null
17.1
'CCE' is null
= dyn_cast<CXXConstructExpr>(Init)) {
17
Assuming 'Init' is not a 'CXXConstructExpr'
7412 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7413 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7414 Expr *Arg = MTE->getSubExpr();
7415 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7416 CCE->getConstructor()});
7417 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7418 /*EnableLifetimeWarnings*/false);
7419 Path.pop_back();
7420 }
7421 }
7422 }
7423
7424 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
18
Assuming 'Init' is a 'CallExpr'
7425 if (EnableLifetimeWarnings)
19
Assuming 'EnableLifetimeWarnings' is false
20
Taking false branch
7426 handleGslAnnotatedTypes(Path, Init, Visit);
7427 return visitLifetimeBoundArguments(Path, Init, Visit);
21
Calling 'visitLifetimeBoundArguments'
7428 }
7429
7430 switch (Init->getStmtClass()) {
7431 case Stmt::UnaryOperatorClass: {
7432 auto *UO = cast<UnaryOperator>(Init);
7433 // If the initializer is the address of a local, we could have a lifetime
7434 // problem.
7435 if (UO->getOpcode() == UO_AddrOf) {
7436 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7437 // it. Don't produce a redundant warning about the lifetime of the
7438 // temporary.
7439 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7440 return;
7441
7442 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7443 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7444 RK_ReferenceBinding, Visit,
7445 EnableLifetimeWarnings);
7446 }
7447 break;
7448 }
7449
7450 case Stmt::BinaryOperatorClass: {
7451 // Handle pointer arithmetic.
7452 auto *BO = cast<BinaryOperator>(Init);
7453 BinaryOperatorKind BOK = BO->getOpcode();
7454 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7455 break;
7456
7457 if (BO->getLHS()->getType()->isPointerType())
7458 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
7459 EnableLifetimeWarnings);
7460 else if (BO->getRHS()->getType()->isPointerType())
7461 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
7462 EnableLifetimeWarnings);
7463 break;
7464 }
7465
7466 case Stmt::ConditionalOperatorClass:
7467 case Stmt::BinaryConditionalOperatorClass: {
7468 auto *C = cast<AbstractConditionalOperator>(Init);
7469 // In C++, we can have a throw-expression operand, which has 'void' type
7470 // and isn't interesting from a lifetime perspective.
7471 if (!C->getTrueExpr()->getType()->isVoidType())
7472 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
7473 EnableLifetimeWarnings);
7474 if (!C->getFalseExpr()->getType()->isVoidType())
7475 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
7476 EnableLifetimeWarnings);
7477 break;
7478 }
7479
7480 case Stmt::BlockExprClass:
7481 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7482 // This is a local block, whose lifetime is that of the function.
7483 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7484 }
7485 break;
7486
7487 case Stmt::AddrLabelExprClass:
7488 // We want to warn if the address of a label would escape the function.
7489 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7490 break;
7491
7492 default:
7493 break;
7494 }
7495}
7496
7497/// Whether a path to an object supports lifetime extension.
7498enum PathLifetimeKind {
7499 /// Lifetime-extend along this path.
7500 Extend,
7501 /// We should lifetime-extend, but we don't because (due to technical
7502 /// limitations) we can't. This happens for default member initializers,
7503 /// which we don't clone for every use, so we don't have a unique
7504 /// MaterializeTemporaryExpr to update.
7505 ShouldExtend,
7506 /// Do not lifetime extend along this path.
7507 NoExtend
7508};
7509
7510/// Determine whether this is an indirect path to a temporary that we are
7511/// supposed to lifetime-extend along.
7512static PathLifetimeKind
7513shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
7514 PathLifetimeKind Kind = PathLifetimeKind::Extend;
7515 for (auto Elem : Path) {
7516 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
7517 Kind = PathLifetimeKind::ShouldExtend;
7518 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
7519 return PathLifetimeKind::NoExtend;
7520 }
7521 return Kind;
7522}
7523
7524/// Find the range for the first interesting entry in the path at or after I.
7525static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
7526 Expr *E) {
7527 for (unsigned N = Path.size(); I != N; ++I) {
7528 switch (Path[I].Kind) {
7529 case IndirectLocalPathEntry::AddressOf:
7530 case IndirectLocalPathEntry::LValToRVal:
7531 case IndirectLocalPathEntry::LifetimeBoundCall:
7532 case IndirectLocalPathEntry::TemporaryCopy:
7533 case IndirectLocalPathEntry::GslReferenceInit:
7534 case IndirectLocalPathEntry::GslPointerInit:
7535 // These exist primarily to mark the path as not permitting or
7536 // supporting lifetime extension.
7537 break;
7538
7539 case IndirectLocalPathEntry::VarInit:
7540 if (cast<VarDecl>(Path[I].D)->isImplicit())
7541 return SourceRange();
7542 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7543 case IndirectLocalPathEntry::DefaultInit:
7544 return Path[I].E->getSourceRange();
7545
7546 case IndirectLocalPathEntry::LambdaCaptureInit:
7547 if (!Path[I].Capture->capturesVariable())
7548 continue;
7549 return Path[I].E->getSourceRange();
7550 }
7551 }
7552 return E->getSourceRange();
7553}
7554
7555static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
7556 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
7557 if (It->Kind == IndirectLocalPathEntry::VarInit)
7558 continue;
7559 if (It->Kind == IndirectLocalPathEntry::AddressOf)
7560 continue;
7561 if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
7562 continue;
7563 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
7564 It->Kind == IndirectLocalPathEntry::GslReferenceInit;
7565 }
7566 return false;
7567}
7568
7569void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7570 Expr *Init) {
7571 LifetimeResult LR = getEntityLifetime(&Entity);
7572 LifetimeKind LK = LR.getInt();
7573 const InitializedEntity *ExtendingEntity = LR.getPointer();
7574
7575 // If this entity doesn't have an interesting lifetime, don't bother looking
7576 // for temporaries within its initializer.
7577 if (LK == LK_FullExpression)
7578 return;
7579
7580 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
7581 ReferenceKind RK) -> bool {
7582 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
7583 SourceLocation DiagLoc = DiagRange.getBegin();
7584
7585 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
7586
7587 bool IsGslPtrInitWithGslTempOwner = false;
7588 bool IsLocalGslOwner = false;
7589 if (pathOnlyInitializesGslPointer(Path)) {
7590 if (isa<DeclRefExpr>(L)) {
7591 // We do not want to follow the references when returning a pointer originating
7592 // from a local owner to avoid the following false positive:
7593 // int &p = *localUniquePtr;
7594 // someContainer.add(std::move(localUniquePtr));
7595 // return p;
7596 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
7597 if (pathContainsInit(Path) || !IsLocalGslOwner)
7598 return false;
7599 } else {
7600 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
7601 isRecordWithAttr<OwnerAttr>(MTE->getType());
7602 // Skipping a chain of initializing gsl::Pointer annotated objects.
7603 // We are looking only for the final source to find out if it was
7604 // a local or temporary owner or the address of a local variable/param.
7605 if (!IsGslPtrInitWithGslTempOwner)
7606 return true;
7607 }
7608 }
7609
7610 switch (LK) {
7611 case LK_FullExpression:
7612 llvm_unreachable("already handled this")::llvm::llvm_unreachable_internal("already handled this", "clang/lib/Sema/SemaInit.cpp"
, 7612)
;
7613
7614 case LK_Extended: {
7615 if (!MTE) {
7616 // The initialized entity has lifetime beyond the full-expression,
7617 // and the local entity does too, so don't warn.
7618 //
7619 // FIXME: We should consider warning if a static / thread storage
7620 // duration variable retains an automatic storage duration local.
7621 return false;
7622 }
7623
7624 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
7625 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7626 return false;
7627 }
7628
7629 switch (shouldLifetimeExtendThroughPath(Path)) {
7630 case PathLifetimeKind::Extend:
7631 // Update the storage duration of the materialized temporary.
7632 // FIXME: Rebuild the expression instead of mutating it.
7633 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
7634 ExtendingEntity->allocateManglingNumber());
7635 // Also visit the temporaries lifetime-extended by this initializer.
7636 return true;
7637
7638 case PathLifetimeKind::ShouldExtend:
7639 // We're supposed to lifetime-extend the temporary along this path (per
7640 // the resolution of DR1815), but we don't support that yet.
7641 //
7642 // FIXME: Properly handle this situation. Perhaps the easiest approach
7643 // would be to clone the initializer expression on each use that would
7644 // lifetime extend its temporaries.
7645 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
7646 << RK << DiagRange;
7647 break;
7648
7649 case PathLifetimeKind::NoExtend:
7650 // If the path goes through the initialization of a variable or field,
7651 // it can't possibly reach a temporary created in this full-expression.
7652 // We will have already diagnosed any problems with the initializer.
7653 if (pathContainsInit(Path))
7654 return false;
7655
7656 Diag(DiagLoc, diag::warn_dangling_variable)
7657 << RK << !Entity.getParent()
7658 << ExtendingEntity->getDecl()->isImplicit()
7659 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
7660 break;
7661 }
7662 break;
7663 }
7664
7665 case LK_MemInitializer: {
7666 if (isa<MaterializeTemporaryExpr>(L)) {
7667 // Under C++ DR1696, if a mem-initializer (or a default member
7668 // initializer used by the absence of one) would lifetime-extend a
7669 // temporary, the program is ill-formed.
7670 if (auto *ExtendingDecl =
7671 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7672 if (IsGslPtrInitWithGslTempOwner) {
7673 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
7674 << ExtendingDecl << DiagRange;
7675 Diag(ExtendingDecl->getLocation(),
7676 diag::note_ref_or_ptr_member_declared_here)
7677 << true;
7678 return false;
7679 }
7680 bool IsSubobjectMember = ExtendingEntity != &Entity;
7681 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
7682 PathLifetimeKind::NoExtend
7683 ? diag::err_dangling_member
7684 : diag::warn_dangling_member)
7685 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
7686 // Don't bother adding a note pointing to the field if we're inside
7687 // its default member initializer; our primary diagnostic points to
7688 // the same place in that case.
7689 if (Path.empty() ||
7690 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
7691 Diag(ExtendingDecl->getLocation(),
7692 diag::note_lifetime_extending_member_declared_here)
7693 << RK << IsSubobjectMember;
7694 }
7695 } else {
7696 // We have a mem-initializer but no particular field within it; this
7697 // is either a base class or a delegating initializer directly
7698 // initializing the base-class from something that doesn't live long
7699 // enough.
7700 //
7701 // FIXME: Warn on this.
7702 return false;
7703 }
7704 } else {
7705 // Paths via a default initializer can only occur during error recovery
7706 // (there's no other way that a default initializer can refer to a
7707 // local). Don't produce a bogus warning on those cases.
7708 if (pathContainsInit(Path))
7709 return false;
7710
7711 // Suppress false positives for code like the one below:
7712 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
7713 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
7714 return false;
7715
7716 auto *DRE = dyn_cast<DeclRefExpr>(L);
7717 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7718 if (!VD) {
7719 // A member was initialized to a local block.
7720 // FIXME: Warn on this.
7721 return false;
7722 }
7723
7724 if (auto *Member =
7725 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7726 bool IsPointer = !Member->getType()->isReferenceType();
7727 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
7728 : diag::warn_bind_ref_member_to_parameter)
7729 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
7730 Diag(Member->getLocation(),
7731 diag::note_ref_or_ptr_member_declared_here)
7732 << (unsigned)IsPointer;
7733 }
7734 }
7735 break;
7736 }
7737
7738 case LK_New:
7739 if (isa<MaterializeTemporaryExpr>(L)) {
7740 if (IsGslPtrInitWithGslTempOwner)
7741 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7742 else
7743 Diag(DiagLoc, RK == RK_ReferenceBinding
7744 ? diag::warn_new_dangling_reference
7745 : diag::warn_new_dangling_initializer_list)
7746 << !Entity.getParent() << DiagRange;
7747 } else {
7748 // We can't determine if the allocation outlives the local declaration.
7749 return false;
7750 }
7751 break;
7752
7753 case LK_Return:
7754 case LK_StmtExprResult:
7755 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7756 // We can't determine if the local variable outlives the statement
7757 // expression.
7758 if (LK == LK_StmtExprResult)
7759 return false;
7760 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7761 << Entity.getType()->isReferenceType() << DRE->getDecl()
7762 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7763 } else if (isa<BlockExpr>(L)) {
7764 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7765 } else if (isa<AddrLabelExpr>(L)) {
7766 // Don't warn when returning a label from a statement expression.
7767 // Leaving the scope doesn't end its lifetime.
7768 if (LK == LK_StmtExprResult)
7769 return false;
7770 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7771 } else {
7772 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7773 << Entity.getType()->isReferenceType() << DiagRange;
7774 }
7775 break;
7776 }
7777
7778 for (unsigned I = 0; I != Path.size(); ++I) {
7779 auto Elem = Path[I];
7780
7781 switch (Elem.Kind) {
7782 case IndirectLocalPathEntry::AddressOf:
7783 case IndirectLocalPathEntry::LValToRVal:
7784 // These exist primarily to mark the path as not permitting or
7785 // supporting lifetime extension.
7786 break;
7787
7788 case IndirectLocalPathEntry::LifetimeBoundCall:
7789 case IndirectLocalPathEntry::TemporaryCopy:
7790 case IndirectLocalPathEntry::GslPointerInit:
7791 case IndirectLocalPathEntry::GslReferenceInit:
7792 // FIXME: Consider adding a note for these.
7793 break;
7794
7795 case IndirectLocalPathEntry::DefaultInit: {
7796 auto *FD = cast<FieldDecl>(Elem.D);
7797 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
7798 << FD << nextPathEntryRange(Path, I + 1, L);
7799 break;
7800 }
7801
7802 case IndirectLocalPathEntry::VarInit: {
7803 const VarDecl *VD = cast<VarDecl>(Elem.D);
7804 Diag(VD->getLocation(), diag::note_local_var_initializer)
7805 << VD->getType()->isReferenceType()
7806 << VD->isImplicit() << VD->getDeclName()
7807 << nextPathEntryRange(Path, I + 1, L);
7808 break;
7809 }
7810
7811 case IndirectLocalPathEntry::LambdaCaptureInit:
7812 if (!Elem.Capture->capturesVariable())
7813 break;
7814 // FIXME: We can't easily tell apart an init-capture from a nested
7815 // capture of an init-capture.
7816 const VarDecl *VD = Elem.Capture->getCapturedVar();
7817 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
7818 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
7819 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
7820 << nextPathEntryRange(Path, I + 1, L);
7821 break;
7822 }
7823 }
7824
7825 // We didn't lifetime-extend, so don't go any further; we don't need more
7826 // warnings or errors on inner temporaries within this one's initializer.
7827 return false;
7828 };
7829
7830 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
7831 diag::warn_dangling_lifetime_pointer, SourceLocation());
7832 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
7833 if (Init->isGLValue())
7834 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7835 TemporaryVisitor,
7836 EnableLifetimeWarnings);
7837 else
7838 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
7839 EnableLifetimeWarnings);
7840}
7841
7842static void DiagnoseNarrowingInInitList(Sema &S,
7843 const ImplicitConversionSequence &ICS,
7844 QualType PreNarrowingType,
7845 QualType EntityType,
7846 const Expr *PostInit);
7847
7848/// Provide warnings when std::move is used on construction.
7849static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7850 bool IsReturnStmt) {
7851 if (!InitExpr)
7852 return;
7853
7854 if (S.inTemplateInstantiation())
7855 return;
7856
7857 QualType DestType = InitExpr->getType();
7858 if (!DestType->isRecordType())
7859 return;
7860
7861 unsigned DiagID = 0;
7862 if (IsReturnStmt) {
7863 const CXXConstructExpr *CCE =
7864 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7865 if (!CCE || CCE->getNumArgs() != 1)
7866 return;
7867
7868 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7869 return;
7870
7871 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7872 }
7873
7874 // Find the std::move call and get the argument.
7875 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7876 if (!CE || !CE->isCallToStdMove())
7877 return;
7878
7879 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7880
7881 if (IsReturnStmt) {
7882 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7883 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7884 return;
7885
7886 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7887 if (!VD || !VD->hasLocalStorage())
7888 return;
7889
7890 // __block variables are not moved implicitly.
7891 if (VD->hasAttr<BlocksAttr>())
7892 return;
7893
7894 QualType SourceType = VD->getType();
7895 if (!SourceType->isRecordType())
7896 return;
7897
7898 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7899 return;
7900 }
7901
7902 // If we're returning a function parameter, copy elision
7903 // is not possible.
7904 if (isa<ParmVarDecl>(VD))
7905 DiagID = diag::warn_redundant_move_on_return;
7906 else
7907 DiagID = diag::warn_pessimizing_move_on_return;
7908 } else {
7909 DiagID = diag::warn_pessimizing_move_on_initialization;
7910 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7911 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7912 return;
7913 }
7914
7915 S.Diag(CE->getBeginLoc(), DiagID);
7916
7917 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7918 // is within a macro.
7919 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7920 if (CallBegin.isMacroID())
7921 return;
7922 SourceLocation RParen = CE->getRParenLoc();
7923 if (RParen.isMacroID())
7924 return;
7925 SourceLocation LParen;
7926 SourceLocation ArgLoc = Arg->getBeginLoc();
7927
7928 // Special testing for the argument location. Since the fix-it needs the
7929 // location right before the argument, the argument location can be in a
7930 // macro only if it is at the beginning of the macro.
7931 while (ArgLoc.isMacroID() &&
7932 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
7933 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
7934 }
7935
7936 if (LParen.isMacroID())
7937 return;
7938
7939 LParen = ArgLoc.getLocWithOffset(-1);
7940
7941 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7942 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7943 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7944}
7945
7946static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7947 // Check to see if we are dereferencing a null pointer. If so, this is
7948 // undefined behavior, so warn about it. This only handles the pattern
7949 // "*null", which is a very syntactic check.
7950 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7951 if (UO->getOpcode() == UO_Deref &&
7952 UO->getSubExpr()->IgnoreParenCasts()->
7953 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7954 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7955 S.PDiag(diag::warn_binding_null_to_reference)
7956 << UO->getSubExpr()->getSourceRange());
7957 }
7958}
7959
7960MaterializeTemporaryExpr *
7961Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7962 bool BoundToLvalueReference) {
7963 auto MTE = new (Context)
7964 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7965
7966 // Order an ExprWithCleanups for lifetime marks.
7967 //
7968 // TODO: It'll be good to have a single place to check the access of the
7969 // destructor and generate ExprWithCleanups for various uses. Currently these
7970 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7971 // but there may be a chance to merge them.
7972 Cleanup.setExprNeedsCleanups(false);
7973 return MTE;
7974}
7975
7976ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7977 // In C++98, we don't want to implicitly create an xvalue.
7978 // FIXME: This means that AST consumers need to deal with "prvalues" that
7979 // denote materialized temporaries. Maybe we should add another ValueKind
7980 // for "xvalue pretending to be a prvalue" for C++98 support.
7981 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
7982 return E;
7983
7984 // C++1z [conv.rval]/1: T shall be a complete type.
7985 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7986 // If so, we should check for a non-abstract class type here too.
7987 QualType T = E->getType();
7988 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7989 return ExprError();
7990
7991 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7992}
7993
7994ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7995 ExprValueKind VK,
7996 CheckedConversionKind CCK) {
7997
7998 CastKind CK = CK_NoOp;
7999
8000 if (VK == VK_PRValue) {
8001 auto PointeeTy = Ty->getPointeeType();
8002 auto ExprPointeeTy = E->getType()->getPointeeType();
8003 if (!PointeeTy.isNull() &&
8004 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8005 CK = CK_AddressSpaceConversion;
8006 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8007 CK = CK_AddressSpaceConversion;
8008 }
8009
8010 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8011}
8012
8013ExprResult InitializationSequence::Perform(Sema &S,
8014 const InitializedEntity &Entity,
8015 const InitializationKind &Kind,
8016 MultiExprArg Args,
8017 QualType *ResultType) {
8018 if (Failed()) {
8019 Diagnose(S, Entity, Kind, Args);
8020 return ExprError();
8021 }
8022 if (!ZeroInitializationFixit.empty()) {
8023 unsigned DiagID = diag::err_default_init_const;
8024 if (Decl *D = Entity.getDecl())
8025 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
8026 DiagID = diag::ext_default_init_const;
8027
8028 // The initialization would have succeeded with this fixit. Since the fixit
8029 // is on the error, we need to build a valid AST in this case, so this isn't
8030 // handled in the Failed() branch above.
8031 QualType DestType = Entity.getType();
8032 S.Diag(Kind.getLocation(), DiagID)
8033 << DestType << (bool)DestType->getAs<RecordType>()
8034 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8035 ZeroInitializationFixit);
8036 }
8037
8038 if (getKind() == DependentSequence) {
8039 // If the declaration is a non-dependent, incomplete array type
8040 // that has an initializer, then its type will be completed once
8041 // the initializer is instantiated.
8042 if (ResultType && !Entity.getType()->isDependentType() &&
8043 Args.size() == 1) {
8044 QualType DeclType = Entity.getType();
8045 if (const IncompleteArrayType *ArrayT
8046 = S.Context.getAsIncompleteArrayType(DeclType)) {
8047 // FIXME: We don't currently have the ability to accurately
8048 // compute the length of an initializer list without
8049 // performing full type-checking of the initializer list
8050 // (since we have to determine where braces are implicitly
8051 // introduced and such). So, we fall back to making the array
8052 // type a dependently-sized array type with no specified
8053 // bound.
8054 if (isa<InitListExpr>((Expr *)Args[0])) {
8055 SourceRange Brackets;
8056
8057 // Scavange the location of the brackets from the entity, if we can.
8058 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8059 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8060 TypeLoc TL = TInfo->getTypeLoc();
8061 if (IncompleteArrayTypeLoc ArrayLoc =
8062 TL.getAs<IncompleteArrayTypeLoc>())
8063 Brackets = ArrayLoc.getBracketsRange();
8064 }
8065 }
8066
8067 *ResultType
8068 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8069 /*NumElts=*/nullptr,
8070 ArrayT->getSizeModifier(),
8071 ArrayT->getIndexTypeCVRQualifiers(),
8072 Brackets);
8073 }
8074
8075 }
8076 }
8077 if (Kind.getKind() == InitializationKind::IK_Direct &&
8078 !Kind.isExplicitCast()) {
8079 // Rebuild the ParenListExpr.
8080 SourceRange ParenRange = Kind.getParenOrBraceRange();
8081 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8082 Args);
8083 }
8084 assert(Kind.getKind() == InitializationKind::IK_Copy ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "clang/lib/Sema/SemaInit.cpp", 8086, __extension__ __PRETTY_FUNCTION__
))
8085 Kind.isExplicitCast() ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "clang/lib/Sema/SemaInit.cpp", 8086, __extension__ __PRETTY_FUNCTION__
))
8086 Kind.getKind() == InitializationKind::IK_DirectList)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "clang/lib/Sema/SemaInit.cpp", 8086, __extension__ __PRETTY_FUNCTION__
))
;
8087 return ExprResult(Args[0]);
8088 }
8089
8090 // No steps means no initialization.
8091 if (Steps.empty())
8092 return ExprResult((Expr *)nullptr);
8093
8094 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8095 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8096 !Entity.isParamOrTemplateParamKind()) {
8097 // Produce a C++98 compatibility warning if we are initializing a reference
8098 // from an initializer list. For parameters, we produce a better warning
8099 // elsewhere.
8100 Expr *Init = Args[0];
8101 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8102 << Init->getSourceRange();
8103 }
8104
8105 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8106 QualType ETy = Entity.getType();
8107 bool HasGlobalAS = ETy.hasAddressSpace() &&
8108 ETy.getAddressSpace() == LangAS::opencl_global;
8109
8110 if (S.getLangOpts().OpenCLVersion >= 200 &&
8111 ETy->isAtomicType() && !HasGlobalAS &&
8112 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8113 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8114 << 1
8115 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8116 return ExprError();
8117 }
8118
8119 QualType DestType = Entity.getType().getNonReferenceType();
8120 // FIXME: Ugly hack around the fact that Entity.getType() is not
8121 // the same as Entity.getDecl()->getType() in cases involving type merging,
8122 // and we want latter when it makes sense.
8123 if (ResultType)
8124 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8125 Entity.getType();
8126
8127 ExprResult CurInit((Expr *)nullptr);
8128 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8129
8130 // For initialization steps that start with a single initializer,
8131 // grab the only argument out the Args and place it into the "current"
8132 // initializer.
8133 switch (Steps.front().Kind) {
8134 case SK_ResolveAddressOfOverloadedFunction:
8135 case SK_CastDerivedToBasePRValue:
8136 case SK_CastDerivedToBaseXValue:
8137 case SK_CastDerivedToBaseLValue:
8138 case SK_BindReference:
8139 case SK_BindReferenceToTemporary:
8140 case SK_FinalCopy:
8141 case SK_ExtraneousCopyToTemporary:
8142 case SK_UserConversion:
8143 case SK_QualificationConversionLValue:
8144 case SK_QualificationConversionXValue:
8145 case SK_QualificationConversionPRValue:
8146 case SK_FunctionReferenceConversion:
8147 case SK_AtomicConversion:
8148 case SK_ConversionSequence:
8149 case SK_ConversionSequenceNoNarrowing:
8150 case SK_ListInitialization:
8151 case SK_UnwrapInitList:
8152 case SK_RewrapInitList:
8153 case SK_CAssignment:
8154 case SK_StringInit:
8155 case SK_ObjCObjectConversion:
8156 case SK_ArrayLoopIndex:
8157 case SK_ArrayLoopInit:
8158 case SK_ArrayInit:
8159 case SK_GNUArrayInit:
8160 case SK_ParenthesizedArrayInit:
8161 case SK_PassByIndirectCopyRestore:
8162 case SK_PassByIndirectRestore:
8163 case SK_ProduceObjCObject:
8164 case SK_StdInitializerList:
8165 case SK_OCLSamplerInit:
8166 case SK_OCLZeroOpaqueType: {
8167 assert(Args.size() == 1)(static_cast <bool> (Args.size() == 1) ? void (0) : __assert_fail
("Args.size() == 1", "clang/lib/Sema/SemaInit.cpp", 8167, __extension__
__PRETTY_FUNCTION__))
;
8168 CurInit = Args[0];
8169 if (!CurInit.get()) return ExprError();
8170 break;
8171 }
8172
8173 case SK_ConstructorInitialization:
8174 case SK_ConstructorInitializationFromList:
8175 case SK_StdInitializerListConstructorCall:
8176 case SK_ZeroInitialization:
8177 break;
8178 }
8179
8180 // Promote from an unevaluated context to an unevaluated list context in
8181 // C++11 list-initialization; we need to instantiate entities usable in
8182 // constant expressions here in order to perform narrowing checks =(
8183 EnterExpressionEvaluationContext Evaluated(
8184 S, EnterExpressionEvaluationContext::InitList,
8185 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8186
8187 // C++ [class.abstract]p2:
8188 // no objects of an abstract class can be created except as subobjects
8189 // of a class derived from it
8190 auto checkAbstractType = [&](QualType T) -> bool {
8191 if (Entity.getKind() == InitializedEntity::EK_Base ||
8192 Entity.getKind() == InitializedEntity::EK_Delegating)
8193 return false;
8194 return S.RequireNonAbstractType(Kind.getLocation(), T,
8195 diag::err_allocation_of_abstract_type);
8196 };
8197
8198 // Walk through the computed steps for the initialization sequence,
8199 // performing the specified conversions along the way.
8200 bool ConstructorInitRequiresZeroInit = false;
8201 for (step_iterator Step = step_begin(), StepEnd = step_end();
8202 Step != StepEnd; ++Step) {
8203 if (CurInit.isInvalid())
8204 return ExprError();
8205
8206 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8207
8208 switch (Step->Kind) {
8209 case SK_ResolveAddressOfOverloadedFunction:
8210 // Overload resolution determined which function invoke; update the
8211 // initializer to reflect that choice.
8212 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
8213 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8214 return ExprError();
8215 CurInit = S.FixOverloadedFunctionReference(CurInit,
8216 Step->Function.FoundDecl,
8217 Step->Function.Function);
8218 // We might get back another placeholder expression if we resolved to a
8219 // builtin.
8220 if (!CurInit.isInvalid())
8221 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8222 break;
8223
8224 case SK_CastDerivedToBasePRValue:
8225 case SK_CastDerivedToBaseXValue:
8226 case SK_CastDerivedToBaseLValue: {
8227 // We have a derived-to-base cast that produces either an rvalue or an
8228 // lvalue. Perform that cast.
8229
8230 CXXCastPath BasePath;
8231
8232 // Casts to inaccessible base classes are allowed with C-style casts.
8233 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8234 if (S.CheckDerivedToBaseConversion(
8235 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8236 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8237 return ExprError();
8238
8239 ExprValueKind VK =
8240 Step->Kind == SK_CastDerivedToBaseLValue
8241 ? VK_LValue
8242 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8243 : VK_PRValue);
8244 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8245 CK_DerivedToBase, CurInit.get(),
8246 &BasePath, VK, FPOptionsOverride());
8247 break;
8248 }
8249
8250 case SK_BindReference:
8251 // Reference binding does not have any corresponding ASTs.
8252
8253 // Check exception specifications
8254 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8255 return ExprError();
8256
8257 // We don't check for e.g. function pointers here, since address
8258 // availability checks should only occur when the function first decays
8259 // into a pointer or reference.
8260 if (CurInit.get()->getType()->isFunctionProtoType()) {
8261 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8262 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8263 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8264 DRE->getBeginLoc()))
8265 return ExprError();
8266 }
8267 }
8268 }
8269
8270 CheckForNullPointerDereference(S, CurInit.get());
8271 break;
8272
8273 case SK_BindReferenceToTemporary: {
8274 // Make sure the "temporary" is actually an rvalue.
8275 assert(CurInit.get()->isPRValue() && "not a temporary")(static_cast <bool> (CurInit.get()->isPRValue() &&
"not a temporary") ? void (0) : __assert_fail ("CurInit.get()->isPRValue() && \"not a temporary\""
, "clang/lib/Sema/SemaInit.cpp", 8275, __extension__ __PRETTY_FUNCTION__
))
;
8276
8277 // Check exception specifications
8278 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8279 return ExprError();
8280
8281 QualType MTETy = Step->Type;
8282
8283 // When this is an incomplete array type (such as when this is
8284 // initializing an array of unknown bounds from an init list), use THAT
8285 // type instead so that we propagate the array bounds.
8286 if (MTETy->isIncompleteArrayType() &&
8287 !CurInit.get()->getType()->isIncompleteArrayType() &&
8288 S.Context.hasSameType(
8289 MTETy->getPointeeOrArrayElementType(),
8290 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8291 MTETy = CurInit.get()->getType();
8292
8293 // Materialize the temporary into memory.
8294 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8295 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8296 CurInit = MTE;
8297
8298 // If we're extending this temporary to automatic storage duration -- we
8299 // need to register its cleanup during the full-expression's cleanups.
8300 if (MTE->getStorageDuration() == SD_Automatic &&
8301 MTE->getType().isDestructedType())
8302 S.Cleanup.setExprNeedsCleanups(true);
8303 break;
8304 }
8305
8306 case SK_FinalCopy:
8307 if (checkAbstractType(Step->Type))
8308 return ExprError();
8309
8310 // If the overall initialization is initializing a temporary, we already
8311 // bound our argument if it was necessary to do so. If not (if we're
8312 // ultimately initializing a non-temporary), our argument needs to be
8313 // bound since it's initializing a function parameter.
8314 // FIXME: This is a mess. Rationalize temporary destruction.
8315 if (!shouldBindAsTemporary(Entity))
8316 CurInit = S.MaybeBindToTemporary(CurInit.get());
8317 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8318 /*IsExtraneousCopy=*/false);
8319 break;
8320
8321 case SK_ExtraneousCopyToTemporary:
8322 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8323 /*IsExtraneousCopy=*/true);
8324 break;
8325
8326 case SK_UserConversion: {
8327 // We have a user-defined conversion that invokes either a constructor
8328 // or a conversion function.
8329 CastKind CastKind;
8330 FunctionDecl *Fn = Step->Function.Function;
8331 DeclAccessPair FoundFn = Step->Function.FoundDecl;
8332 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8333 bool CreatedObject = false;
8334 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8335 // Build a call to the selected constructor.
8336 SmallVector<Expr*, 8> ConstructorArgs;
8337 SourceLocation Loc = CurInit.get()->getBeginLoc();
8338
8339 // Determine the arguments required to actually perform the constructor
8340 // call.
8341 Expr *Arg = CurInit.get();
8342 if (S.CompleteConstructorCall(Constructor, Step->Type,
8343 MultiExprArg(&Arg, 1), Loc,
8344 ConstructorArgs))
8345 return ExprError();
8346
8347 // Build an expression that constructs a temporary.
8348 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
8349 FoundFn, Constructor,
8350 ConstructorArgs,
8351 HadMultipleCandidates,
8352 /*ListInit*/ false,
8353 /*StdInitListInit*/ false,
8354 /*ZeroInit*/ false,
8355 CXXConstructExpr::CK_Complete,
8356 SourceRange());
8357 if (CurInit.isInvalid())
8358 return ExprError();
8359
8360 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8361 Entity);
8362 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8363 return ExprError();
8364
8365 CastKind = CK_ConstructorConversion;
8366 CreatedObject = true;
8367 } else {
8368 // Build a call to the conversion function.
8369 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8370 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8371 FoundFn);
8372 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8373 return ExprError();
8374
8375 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8376 HadMultipleCandidates);
8377 if (CurInit.isInvalid())
8378 return ExprError();
8379
8380 CastKind = CK_UserDefinedConversion;
8381 CreatedObject = Conversion->getReturnType()->isRecordType();
8382 }
8383
8384 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8385 return ExprError();
8386
8387 CurInit = ImplicitCastExpr::Create(
8388 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8389 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8390
8391 if (shouldBindAsTemporary(Entity))
8392 // The overall entity is temporary, so this expression should be
8393 // destroyed at the end of its full-expression.
8394 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8395 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8396 // The object outlasts the full-expression, but we need to prepare for
8397 // a destructor being run on it.
8398 // FIXME: It makes no sense to do this here. This should happen
8399 // regardless of how we initialized the entity.
8400 QualType T = CurInit.get()->getType();
8401 if (const RecordType *Record = T->getAs<RecordType>()) {
8402 CXXDestructorDecl *Destructor
8403 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8404 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8405 S.PDiag(diag::err_access_dtor_temp) << T);
8406 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8407 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8408 return ExprError();
8409 }
8410 }
8411 break;
8412 }
8413
8414 case SK_QualificationConversionLValue:
8415 case SK_QualificationConversionXValue:
8416 case SK_QualificationConversionPRValue: {
8417 // Perform a qualification conversion; these can never go wrong.
8418 ExprValueKind VK =
8419 Step->Kind == SK_QualificationConversionLValue
8420 ? VK_LValue
8421 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8422 : VK_PRValue);
8423 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8424 break;
8425 }
8426
8427 case SK_FunctionReferenceConversion:
8428 assert(CurInit.get()->isLValue() &&(static_cast <bool> (CurInit.get()->isLValue() &&
"function reference should be lvalue") ? void (0) : __assert_fail
("CurInit.get()->isLValue() && \"function reference should be lvalue\""
, "clang/lib/Sema/SemaInit.cpp", 8429, __extension__ __PRETTY_FUNCTION__
))
8429 "function reference should be lvalue")(static_cast <bool> (CurInit.get()->isLValue() &&
"function reference should be lvalue") ? void (0) : __assert_fail
("CurInit.get()->isLValue() && \"function reference should be lvalue\""
, "clang/lib/Sema/SemaInit.cpp", 8429, __extension__ __PRETTY_FUNCTION__
))
;
8430 CurInit =
8431 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8432 break;
8433
8434 case SK_AtomicConversion: {
8435 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic")(static_cast <bool> (CurInit.get()->isPRValue() &&
"cannot convert glvalue to atomic") ? void (0) : __assert_fail
("CurInit.get()->isPRValue() && \"cannot convert glvalue to atomic\""
, "clang/lib/Sema/SemaInit.cpp", 8435, __extension__ __PRETTY_FUNCTION__
))
;
8436 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8437 CK_NonAtomicToAtomic, VK_PRValue);
8438 break;
8439 }
8440
8441 case SK_ConversionSequence:
8442 case SK_ConversionSequenceNoNarrowing: {
8443 if (const auto *FromPtrType =
8444 CurInit.get()->getType()->getAs<PointerType>()) {
8445 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8446 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8447 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8448 // Do not check static casts here because they are checked earlier
8449 // in Sema::ActOnCXXNamedCast()
8450 if (!Kind.isStaticCast()) {
8451 S.Diag(CurInit.get()->getExprLoc(),
8452 diag::warn_noderef_to_dereferenceable_pointer)
8453 << CurInit.get()->getSourceRange();
8454 }
8455 }
8456 }
8457 }
8458
8459 Sema::CheckedConversionKind CCK
8460 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
8461 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
8462 : Kind.isExplicitCast()? Sema::CCK_OtherCast
8463 : Sema::CCK_ImplicitConversion;
8464 ExprResult CurInitExprRes =
8465 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
8466 getAssignmentAction(Entity), CCK);
8467 if (CurInitExprRes.isInvalid())
8468 return ExprError();
8469
8470 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
8471
8472 CurInit = CurInitExprRes;
8473
8474 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
8475 S.getLangOpts().CPlusPlus)
8476 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8477 CurInit.get());
8478
8479 break;
8480 }
8481
8482 case SK_ListInitialization: {
8483 if (checkAbstractType(Step->Type))
8484 return ExprError();
8485
8486 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8487 // If we're not initializing the top-level entity, we need to create an
8488 // InitializeTemporary entity for our target type.
8489 QualType Ty = Step->Type;
8490 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8491 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
8492 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
8493 InitListChecker PerformInitList(S, InitEntity,
8494 InitList, Ty, /*VerifyOnly=*/false,
8495 /*TreatUnavailableAsInvalid=*/false);
8496 if (PerformInitList.HadError())
8497 return ExprError();
8498
8499 // Hack: We must update *ResultType if available in order to set the
8500 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8501 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8502 if (ResultType &&
8503 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8504 if ((*ResultType)->isRValueReferenceType())
8505 Ty = S.Context.getRValueReferenceType(Ty);
8506 else if ((*ResultType)->isLValueReferenceType())
8507 Ty = S.Context.getLValueReferenceType(Ty,
8508 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8509 *ResultType = Ty;
8510 }
8511
8512 InitListExpr *StructuredInitList =
8513 PerformInitList.getFullyStructuredList();
8514 CurInit.get();
8515 CurInit = shouldBindAsTemporary(InitEntity)
8516 ? S.MaybeBindToTemporary(StructuredInitList)
8517 : StructuredInitList;
8518 break;
8519 }
8520
8521 case SK_ConstructorInitializationFromList: {
8522 if (checkAbstractType(Step->Type))
8523 return ExprError();
8524
8525 // When an initializer list is passed for a parameter of type "reference
8526 // to object", we don't get an EK_Temporary entity, but instead an
8527 // EK_Parameter entity with reference type.
8528 // FIXME: This is a hack. What we really should do is create a user
8529 // conversion step for this case, but this makes it considerably more
8530 // complicated. For now, this will do.
8531 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8532 Entity.getType().getNonReferenceType());
8533 bool UseTemporary = Entity.getType()->isReferenceType();
8534 assert(Args.size() == 1 && "expected a single argument for list init")(static_cast <bool> (Args.size() == 1 && "expected a single argument for list init"
) ? void (0) : __assert_fail ("Args.size() == 1 && \"expected a single argument for list init\""
, "clang/lib/Sema/SemaInit.cpp", 8534, __extension__ __PRETTY_FUNCTION__
))
;
8535 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8536 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8537 << InitList->getSourceRange();
8538 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8539 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8540 Entity,
8541 Kind, Arg, *Step,
8542 ConstructorInitRequiresZeroInit,
8543 /*IsListInitialization*/true,
8544 /*IsStdInitListInit*/false,
8545 InitList->getLBraceLoc(),
8546 InitList->getRBraceLoc());
8547 break;
8548 }
8549
8550 case SK_UnwrapInitList:
8551 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8552 break;
8553
8554 case SK_RewrapInitList: {
8555 Expr *E = CurInit.get();
8556 InitListExpr *Syntactic = Step->WrappingSyntacticList;
8557 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8558 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8559 ILE->setSyntacticForm(Syntactic);
8560 ILE->setType(E->getType());
8561 ILE->setValueKind(E->getValueKind());
8562 CurInit = ILE;
8563 break;
8564 }
8565
8566 case SK_ConstructorInitialization:
8567 case SK_StdInitializerListConstructorCall: {
8568 if (checkAbstractType(Step->Type))
8569 return ExprError();
8570
8571 // When an initializer list is passed for a parameter of type "reference
8572 // to object", we don't get an EK_Temporary entity, but instead an
8573 // EK_Parameter entity with reference type.
8574 // FIXME: This is a hack. What we really should do is create a user
8575 // conversion step for this case, but this makes it considerably more
8576 // complicated. For now, this will do.
8577 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8578 Entity.getType().getNonReferenceType());
8579 bool UseTemporary = Entity.getType()->isReferenceType();
8580 bool IsStdInitListInit =
8581 Step->Kind == SK_StdInitializerListConstructorCall;
8582 Expr *Source = CurInit.get();
8583 SourceRange Range = Kind.hasParenOrBraceRange()
8584 ? Kind.getParenOrBraceRange()
8585 : SourceRange();
8586 CurInit = PerformConstructorInitialization(
8587 S, UseTemporary ? TempEntity : Entity, Kind,
8588 Source ? MultiExprArg(Source) : Args, *Step,
8589 ConstructorInitRequiresZeroInit,
8590 /*IsListInitialization*/ IsStdInitListInit,
8591 /*IsStdInitListInitialization*/ IsStdInitListInit,
8592 /*LBraceLoc*/ Range.getBegin(),
8593 /*RBraceLoc*/ Range.getEnd());
8594 break;
8595 }
8596
8597 case SK_ZeroInitialization: {
8598 step_iterator NextStep = Step;
8599 ++NextStep;
8600 if (NextStep != StepEnd &&
8601 (NextStep->Kind == SK_ConstructorInitialization ||
8602 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8603 // The need for zero-initialization is recorded directly into
8604 // the call to the object's constructor within the next step.
8605 ConstructorInitRequiresZeroInit = true;
8606 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8607 S.getLangOpts().CPlusPlus &&
8608 !Kind.isImplicitValueInit()) {
8609 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8610 if (!TSInfo)
8611 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
8612 Kind.getRange().getBegin());
8613
8614 CurInit = new (S.Context) CXXScalarValueInitExpr(
8615 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8616 Kind.getRange().getEnd());
8617 } else {
8618 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8619 }
8620 break;
8621 }
8622
8623 case SK_CAssignment: {
8624 QualType SourceType = CurInit.get()->getType();
8625
8626 // Save off the initial CurInit in case we need to emit a diagnostic
8627 ExprResult InitialCurInit = CurInit;
8628 ExprResult Result = CurInit;
8629 Sema::AssignConvertType ConvTy =
8630 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
8631 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
8632 if (Result.isInvalid())
8633 return ExprError();
8634 CurInit = Result;
8635
8636 // If this is a call, allow conversion to a transparent union.
8637 ExprResult CurInitExprRes = CurInit;
8638 if (ConvTy != Sema::Compatible &&
8639 Entity.isParameterKind() &&
8640 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
8641 == Sema::Compatible)
8642 ConvTy = Sema::Compatible;
8643 if (CurInitExprRes.isInvalid())
8644 return ExprError();
8645 CurInit = CurInitExprRes;
8646
8647 bool Complained;
8648 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8649 Step->Type, SourceType,
8650 InitialCurInit.get(),
8651 getAssignmentAction(Entity, true),
8652 &Complained)) {
8653 PrintInitLocationNote(S, Entity);
8654 return ExprError();
8655 } else if (Complained)
8656 PrintInitLocationNote(S, Entity);
8657 break;
8658 }
8659
8660 case SK_StringInit: {
8661 QualType Ty = Step->Type;
8662 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8663 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8664 S.Context.getAsArrayType(Ty), S);
8665 break;
8666 }
8667
8668 case SK_ObjCObjectConversion:
8669 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8670 CK_ObjCObjectLValueCast,
8671 CurInit.get()->getValueKind());
8672 break;
8673
8674 case SK_ArrayLoopIndex: {
8675 Expr *Cur = CurInit.get();
8676 Expr *BaseExpr = new (S.Context)
8677 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8678 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8679 Expr *IndexExpr =
8680 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8681 CurInit = S.CreateBuiltinArraySubscriptExpr(
8682 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8683 ArrayLoopCommonExprs.push_back(BaseExpr);
8684 break;
8685 }
8686
8687 case SK_ArrayLoopInit: {
8688 assert(!ArrayLoopCommonExprs.empty() &&(static_cast <bool> (!ArrayLoopCommonExprs.empty() &&
"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void (
0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\""
, "clang/lib/Sema/SemaInit.cpp", 8689, __extension__ __PRETTY_FUNCTION__
))
8689 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit")(static_cast <bool> (!ArrayLoopCommonExprs.empty() &&
"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void (
0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\""
, "clang/lib/Sema/SemaInit.cpp", 8689, __extension__ __PRETTY_FUNCTION__
))
;
8690 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8691 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8692 CurInit.get());
8693 break;
8694 }
8695
8696 case SK_GNUArrayInit:
8697 // Okay: we checked everything before creating this step. Note that
8698 // this is a GNU extension.
8699 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8700 << Step->Type << CurInit.get()->getType()
8701 << CurInit.get()->getSourceRange();
8702 updateGNUCompoundLiteralRValue(CurInit.get());
8703 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8704 case SK_ArrayInit:
8705 // If the destination type is an incomplete array type, update the
8706 // type accordingly.
8707 if (ResultType) {
8708 if (const IncompleteArrayType *IncompleteDest
8709 = S.Context.getAsIncompleteArrayType(Step->Type)) {
8710 if (const ConstantArrayType *ConstantSource
8711 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8712 *ResultType = S.Context.getConstantArrayType(
8713 IncompleteDest->getElementType(),
8714 ConstantSource->getSize(),
8715 ConstantSource->getSizeExpr(),
8716 ArrayType::Normal, 0);
8717 }
8718 }
8719 }
8720 break;
8721
8722 case SK_ParenthesizedArrayInit:
8723 // Okay: we checked everything before creating this step. Note that
8724 // this is a GNU extension.
8725 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8726 << CurInit.get()->getSourceRange();
8727 break;
8728
8729 case SK_PassByIndirectCopyRestore:
8730 case SK_PassByIndirectRestore:
8731 checkIndirectCopyRestoreSource(S, CurInit.get());
8732 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8733 CurInit.get(), Step->Type,
8734 Step->Kind == SK_PassByIndirectCopyRestore);
8735 break;
8736
8737 case SK_ProduceObjCObject:
8738 CurInit = ImplicitCastExpr::Create(
8739 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8740 VK_PRValue, FPOptionsOverride());
8741 break;
8742
8743 case SK_StdInitializerList: {
8744 S.Diag(CurInit.get()->getExprLoc(),
8745 diag::warn_cxx98_compat_initializer_list_init)
8746 << CurInit.get()->getSourceRange();
8747
8748 // Materialize the temporary into memory.
8749 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8750 CurInit.get()->getType(), CurInit.get(),
8751 /*BoundToLvalueReference=*/false);
8752
8753 // Wrap it in a construction of a std::initializer_list<T>.
8754 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8755
8756 // Bind the result, in case the library has given initializer_list a
8757 // non-trivial destructor.
8758 if (shouldBindAsTemporary(Entity))
8759 CurInit = S.MaybeBindToTemporary(CurInit.get());
8760 break;
8761 }
8762
8763 case SK_OCLSamplerInit: {
8764 // Sampler initialization have 5 cases:
8765 // 1. function argument passing
8766 // 1a. argument is a file-scope variable
8767 // 1b. argument is a function-scope variable
8768 // 1c. argument is one of caller function's parameters
8769 // 2. variable initialization
8770 // 2a. initializing a file-scope variable
8771 // 2b. initializing a function-scope variable
8772 //
8773 // For file-scope variables, since they cannot be initialized by function
8774 // call of __translate_sampler_initializer in LLVM IR, their references
8775 // need to be replaced by a cast from their literal initializers to
8776 // sampler type. Since sampler variables can only be used in function
8777 // calls as arguments, we only need to replace them when handling the
8778 // argument passing.
8779 assert(Step->Type->isSamplerT() &&(static_cast <bool> (Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.") ? void (0) : __assert_fail
("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\""
, "clang/lib/Sema/SemaInit.cpp", 8780, __extension__ __PRETTY_FUNCTION__
))
8780 "Sampler initialization on non-sampler type.")(static_cast <bool> (Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.") ? void (0) : __assert_fail
("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\""
, "clang/lib/Sema/SemaInit.cpp", 8780, __extension__ __PRETTY_FUNCTION__
))
;
8781 Expr *Init = CurInit.get()->IgnoreParens();
8782 QualType SourceType = Init->getType();
8783 // Case 1
8784 if (Entity.isParameterKind()) {
8785 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8786 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8787 << SourceType;
8788 break;
8789 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8790 auto Var = cast<VarDecl>(DRE->getDecl());
8791 // Case 1b and 1c
8792 // No cast from integer to sampler is needed.
8793 if (!Var->hasGlobalStorage()) {
8794 CurInit = ImplicitCastExpr::Create(
8795 S.Context, Step->Type, CK_LValueToRValue, Init,
8796 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8797 break;
8798 }
8799 // Case 1a
8800 // For function call with a file-scope sampler variable as argument,
8801 // get the integer literal.
8802 // Do not diagnose if the file-scope variable does not have initializer
8803 // since this has already been diagnosed when parsing the variable
8804 // declaration.
8805 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8806 break;
8807 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8808 Var->getInit()))->getSubExpr();
8809 SourceType = Init->getType();
8810 }
8811 } else {
8812 // Case 2
8813 // Check initializer is 32 bit integer constant.
8814 // If the initializer is taken from global variable, do not diagnose since
8815 // this has already been done when parsing the variable declaration.
8816 if (!Init->isConstantInitializer(S.Context, false))
8817 break;
8818
8819 if (!SourceType->isIntegerType() ||
8820 32 != S.Context.getIntWidth(SourceType)) {
8821 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8822 << SourceType;
8823 break;
8824 }
8825
8826 Expr::EvalResult EVResult;
8827 Init->EvaluateAsInt(EVResult, S.Context);
8828 llvm::APSInt Result = EVResult.Val.getInt();
8829 const uint64_t SamplerValue = Result.getLimitedValue();
8830 // 32-bit value of sampler's initializer is interpreted as
8831 // bit-field with the following structure:
8832 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8833 // |31 6|5 4|3 1| 0|
8834 // This structure corresponds to enum values of sampler properties
8835 // defined in SPIR spec v1.2 and also opencl-c.h
8836 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8837 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8838 if (FilterMode != 1 && FilterMode != 2 &&
8839 !S.getOpenCLOptions().isAvailableOption(
8840 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8841 S.Diag(Kind.getLocation(),
8842 diag::warn_sampler_initializer_invalid_bits)
8843 << "Filter Mode";
8844 if (AddressingMode > 4)
8845 S.Diag(Kind.getLocation(),
8846 diag::warn_sampler_initializer_invalid_bits)
8847 << "Addressing Mode";
8848 }
8849
8850 // Cases 1a, 2a and 2b
8851 // Insert cast from integer to sampler.
8852 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8853 CK_IntToOCLSampler);
8854 break;
8855 }
8856 case SK_OCLZeroOpaqueType: {
8857 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||(static_cast <bool> ((Step->Type->isEventT() || Step
->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType
()) && "Wrong type for initialization of OpenCL opaque type."
) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\""
, "clang/lib/Sema/SemaInit.cpp", 8859, __extension__ __PRETTY_FUNCTION__
))
8858 Step->Type->isOCLIntelSubgroupAVCType()) &&(static_cast <bool> ((Step->Type->isEventT() || Step
->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType
()) && "Wrong type for initialization of OpenCL opaque type."
) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\""
, "clang/lib/Sema/SemaInit.cpp", 8859, __extension__ __PRETTY_FUNCTION__
))
8859 "Wrong type for initialization of OpenCL opaque type.")(static_cast <bool> ((Step->Type->isEventT() || Step
->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType
()) && "Wrong type for initialization of OpenCL opaque type."
) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\""
, "clang/lib/Sema/SemaInit.cpp", 8859, __extension__ __PRETTY_FUNCTION__
))
;
8860
8861 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8862 CK_ZeroToOCLOpaqueType,
8863 CurInit.get()->getValueKind());
8864 break;
8865 }
8866 }
8867 }
8868
8869 // Check whether the initializer has a shorter lifetime than the initialized
8870 // entity, and if not, either lifetime-extend or warn as appropriate.
8871 if (auto *Init = CurInit.get())
8872 S.checkInitializerLifetime(Entity, Init);
8873
8874 // Diagnose non-fatal problems with the completed initialization.
8875 if (Entity.getKind() == InitializedEntity::EK_Member &&
8876 cast<FieldDecl>(Entity.getDecl())->isBitField())
8877 S.CheckBitFieldInitialization(Kind.getLocation(),
8878 cast<FieldDecl>(Entity.getDecl()),
8879 CurInit.get());
8880
8881 // Check for std::move on construction.
8882 if (const Expr *E = CurInit.get()) {
8883 CheckMoveOnConstruction(S, E,
8884 Entity.getKind() == InitializedEntity::EK_Result);
8885 }
8886
8887 return CurInit;
8888}
8889
8890/// Somewhere within T there is an uninitialized reference subobject.
8891/// Dig it out and diagnose it.
8892static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8893 QualType T) {
8894 if (T->isReferenceType()) {
8895 S.Diag(Loc, diag::err_reference_without_init)
8896 << T.getNonReferenceType();
8897 return true;
8898 }
8899
8900 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8901 if (!RD || !RD->hasUninitializedReferenceMember())
8902 return false;
8903
8904 for (const auto *FI : RD->fields()) {
8905 if (FI->isUnnamedBitfield())
8906 continue;
8907
8908 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8909 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8910 return true;
8911 }
8912 }
8913
8914 for (const auto &BI : RD->bases()) {
8915 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8916 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8917 return true;
8918 }
8919 }
8920
8921 return false;
8922}
8923
8924
8925//===----------------------------------------------------------------------===//
8926// Diagnose initialization failures
8927//===----------------------------------------------------------------------===//
8928
8929/// Emit notes associated with an initialization that failed due to a
8930/// "simple" conversion failure.
8931static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8932 Expr *op) {
8933 QualType destType = entity.getType();
8934 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8935 op->getType()->isObjCObjectPointerType()) {
8936
8937 // Emit a possible note about the conversion failing because the
8938 // operand is a message send with a related result type.
8939 S.EmitRelatedResultTypeNote(op);
8940
8941 // Emit a possible note about a return failing because we're
8942 // expecting a related result type.
8943 if (entity.getKind() == InitializedEntity::EK_Result)
8944 S.EmitRelatedResultTypeNoteForReturn(destType);
8945 }
8946 QualType fromType = op->getType();
8947 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8948 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8949 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8950 auto *destDecl = destType->getPointeeCXXRecordDecl();
8951 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8952 destDecl->getDeclKind() == Decl::CXXRecord &&
8953 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8954 !fromDecl->hasDefinition() &&
8955 destPointeeType.getQualifiers().compatiblyIncludes(
8956 fromPointeeType.getQualifiers()))
8957 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8958 << S.getASTContext().getTagDeclType(fromDecl)
8959 << S.getASTContext().getTagDeclType(destDecl);
8960}
8961
8962static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8963 InitListExpr *InitList) {
8964 QualType DestType = Entity.getType();
8965
8966 QualType E;
8967 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8968 QualType ArrayType = S.Context.getConstantArrayType(
8969 E.withConst(),
8970 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8971 InitList->getNumInits()),
8972 nullptr, clang::ArrayType::Normal, 0);
8973 InitializedEntity HiddenArray =
8974 InitializedEntity::InitializeTemporary(ArrayType);
8975 return diagnoseListInit(S, HiddenArray, InitList);
8976 }
8977
8978 if (DestType->isReferenceType()) {
8979 // A list-initialization failure for a reference means that we tried to
8980 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8981 // inner initialization failed.
8982 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8983 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
8984 SourceLocation Loc = InitList->getBeginLoc();
8985 if (auto *D = Entity.getDecl())
8986 Loc = D->getLocation();
8987 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8988 return;
8989 }
8990
8991 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8992 /*VerifyOnly=*/false,
8993 /*TreatUnavailableAsInvalid=*/false);
8994 assert(DiagnoseInitList.HadError() &&(static_cast <bool> (DiagnoseInitList.HadError() &&
"Inconsistent init list check result.") ? void (0) : __assert_fail
("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\""
, "clang/lib/Sema/SemaInit.cpp", 8995, __extension__ __PRETTY_FUNCTION__
))
8995 "Inconsistent init list check result.")(static_cast <bool> (DiagnoseInitList.HadError() &&
"Inconsistent init list check result.") ? void (0) : __assert_fail
("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\""
, "clang/lib/Sema/SemaInit.cpp", 8995, __extension__ __PRETTY_FUNCTION__
))
;
8996}
8997
8998bool InitializationSequence::Diagnose(Sema &S,
8999 const InitializedEntity &Entity,
9000 const InitializationKind &Kind,
9001 ArrayRef<Expr *> Args) {
9002 if (!Failed())
9003 return false;
9004
9005 // When we want to diagnose only one element of a braced-init-list,
9006 // we need to factor it out.
9007 Expr *OnlyArg;
9008 if (Args.size() == 1) {
9009 auto *List = dyn_cast<InitListExpr>(Args[0]);
9010 if (List && List->getNumInits() == 1)
9011 OnlyArg = List->getInit(0);
9012 else
9013 OnlyArg = Args[0];
9014 }
9015 else
9016 OnlyArg = nullptr;
9017
9018 QualType DestType = Entity.getType();
9019 switch (Failure) {
9020 case FK_TooManyInitsForReference:
9021 // FIXME: Customize for the initialized entity?
9022 if (Args.empty()) {
9023 // Dig out the reference subobject which is uninitialized and diagnose it.
9024 // If this is value-initialization, this could be nested some way within
9025 // the target type.
9026 assert(Kind.getKind() == InitializationKind::IK_Value ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail
("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()"
, "clang/lib/Sema/SemaInit.cpp", 9027, __extension__ __PRETTY_FUNCTION__
))
9027 DestType->isReferenceType())(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail
("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()"
, "clang/lib/Sema/SemaInit.cpp", 9027, __extension__ __PRETTY_FUNCTION__
))
;
9028 bool Diagnosed =
9029 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9030 assert(Diagnosed && "couldn't find uninitialized reference to diagnose")(static_cast <bool> (Diagnosed && "couldn't find uninitialized reference to diagnose"
) ? void (0) : __assert_fail ("Diagnosed && \"couldn't find uninitialized reference to diagnose\""
, "clang/lib/Sema/SemaInit.cpp", 9030, __extension__ __PRETTY_FUNCTION__
))
;
9031 (void)Diagnosed;
9032 } else // FIXME: diagnostic below could be better!
9033 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9034 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9035 break;
9036 case FK_ParenthesizedListInitForReference:
9037 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9038 << 1 << Entity.getType() << Args[0]->getSourceRange();
9039 break;
9040
9041 case FK_ArrayNeedsInitList:
9042 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9043 break;
9044 case FK_ArrayNeedsInitListOrStringLiteral:
9045 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9046 break;
9047 case FK_ArrayNeedsInitListOrWideStringLiteral:
9048 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9049 break;
9050 case FK_NarrowStringIntoWideCharArray:
9051 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9052 break;
9053 case FK_WideStringIntoCharArray:
9054 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9055 break;
9056 case FK_IncompatWideStringIntoWideChar:
9057 S.Diag(Kind.getLocation(),
9058 diag::err_array_init_incompat_wide_string_into_wchar);
9059 break;
9060 case FK_PlainStringIntoUTF8Char:
9061 S.Diag(Kind.getLocation(),
9062 diag::err_array_init_plain_string_into_char8_t);
9063 S.Diag(Args.front()->getBeginLoc(),
9064 diag::note_array_init_plain_string_into_char8_t)
9065 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9066 break;
9067 case FK_UTF8StringIntoPlainChar:
9068 S.Diag(Kind.getLocation(),
9069 diag::err_array_init_utf8_string_into_char)
9070 << S.getLangOpts().CPlusPlus20;
9071 break;
9072 case FK_ArrayTypeMismatch:
9073 case FK_NonConstantArrayInit:
9074 S.Diag(Kind.getLocation(),
9075 (Failure == FK_ArrayTypeMismatch
9076 ? diag::err_array_init_different_type
9077 : diag::err_array_init_non_constant_array))
9078 << DestType.getNonReferenceType()
9079 << OnlyArg->getType()
9080 << Args[0]->getSourceRange();
9081 break;
9082
9083 case FK_VariableLengthArrayHasInitializer:
9084 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9085 << Args[0]->getSourceRange();
9086 break;
9087
9088 case FK_AddressOfOverloadFailed: {
9089 DeclAccessPair Found;
9090 S.ResolveAddressOfOverloadedFunction(OnlyArg,
9091 DestType.getNonReferenceType(),
9092 true,
9093 Found);
9094 break;
9095 }
9096
9097 case FK_AddressOfUnaddressableFunction: {
9098 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9099 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9100 OnlyArg->getBeginLoc());
9101 break;
9102 }
9103
9104 case FK_ReferenceInitOverloadFailed:
9105 case FK_UserConversionOverloadFailed:
9106 switch (FailedOverloadResult) {
9107 case OR_Ambiguous:
9108
9109 FailedCandidateSet.NoteCandidates(
9110 PartialDiagnosticAt(
9111 Kind.getLocation(),
9112 Failure == FK_UserConversionOverloadFailed
9113 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9114 << OnlyArg->getType() << DestType
9115 << Args[0]->getSourceRange())
9116 : (S.PDiag(diag::err_ref_init_ambiguous)
9117 << DestType << OnlyArg->getType()
9118 << Args[0]->getSourceRange())),
9119 S, OCD_AmbiguousCandidates, Args);
9120 break;
9121
9122 case OR_No_Viable_Function: {
9123 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9124 if (!S.RequireCompleteType(Kind.getLocation(),
9125 DestType.getNonReferenceType(),
9126 diag::err_typecheck_nonviable_condition_incomplete,
9127 OnlyArg->getType(), Args[0]->getSourceRange()))
9128 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9129 << (Entity.getKind() == InitializedEntity::EK_Result)
9130 << OnlyArg->getType() << Args[0]->getSourceRange()
9131 << DestType.getNonReferenceType();
9132
9133 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9134 break;
9135 }
9136 case OR_Deleted: {
9137 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9138 << OnlyArg->getType() << DestType.getNonReferenceType()
9139 << Args[0]->getSourceRange();
9140 OverloadCandidateSet::iterator Best;
9141 OverloadingResult Ovl
9142 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9143 if (Ovl == OR_Deleted) {
9144 S.NoteDeletedFunction(Best->Function);
9145 } else {
9146 llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?"
, "clang/lib/Sema/SemaInit.cpp", 9146)
;
9147 }
9148 break;
9149 }
9150
9151 case OR_Success:
9152 llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!",
"clang/lib/Sema/SemaInit.cpp", 9152)
;
9153 }
9154 break;
9155
9156 case FK_NonConstLValueReferenceBindingToTemporary:
9157 if (isa<InitListExpr>(Args[0])) {
9158 S.Diag(Kind.getLocation(),
9159 diag::err_lvalue_reference_bind_to_initlist)
9160 << DestType.getNonReferenceType().isVolatileQualified()
9161 << DestType.getNonReferenceType()
9162 << Args[0]->getSourceRange();
9163 break;
9164 }
9165 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9166
9167 case FK_NonConstLValueReferenceBindingToUnrelated:
9168 S.Diag(Kind.getLocation(),
9169 Failure == FK_NonConstLValueReferenceBindingToTemporary
9170 ? diag::err_lvalue_reference_bind_to_temporary
9171 : diag::err_lvalue_reference_bind_to_unrelated)
9172 << DestType.getNonReferenceType().isVolatileQualified()
9173 << DestType.getNonReferenceType()
9174 << OnlyArg->getType()
9175 << Args[0]->getSourceRange();
9176 break;
9177
9178 case FK_NonConstLValueReferenceBindingToBitfield: {
9179 // We don't necessarily have an unambiguous source bit-field.
9180 FieldDecl *BitField = Args[0]->getSourceBitField();
9181 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9182 << DestType.isVolatileQualified()
9183 << (BitField ? BitField->getDeclName() : DeclarationName())
9184 << (BitField != nullptr)
9185 << Args[0]->getSourceRange();
9186 if (BitField)
9187 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9188 break;
9189 }
9190
9191 case FK_NonConstLValueReferenceBindingToVectorElement:
9192 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9193 << DestType.isVolatileQualified()
9194 << Args[0]->getSourceRange();
9195 break;
9196
9197 case FK_NonConstLValueReferenceBindingToMatrixElement:
9198 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9199 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9200 break;
9201
9202 case FK_RValueReferenceBindingToLValue:
9203 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9204 << DestType.getNonReferenceType() << OnlyArg->getType()
9205 << Args[0]->getSourceRange();
9206 break;
9207
9208 case FK_ReferenceAddrspaceMismatchTemporary:
9209 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9210 << DestType << Args[0]->getSourceRange();
9211 break;
9212
9213 case FK_ReferenceInitDropsQualifiers: {
9214 QualType SourceType = OnlyArg->getType();
9215 QualType NonRefType = DestType.getNonReferenceType();
9216 Qualifiers DroppedQualifiers =
9217 SourceType.getQualifiers() - NonRefType.getQualifiers();
9218
9219 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9220 SourceType.getQualifiers()))
9221 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9222 << NonRefType << SourceType << 1 /*addr space*/
9223 << Args[0]->getSourceRange();
9224 else if (DroppedQualifiers.hasQualifiers())
9225 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9226 << NonRefType << SourceType << 0 /*cv quals*/
9227 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9228 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9229 else
9230 // FIXME: Consider decomposing the type and explaining which qualifiers
9231 // were dropped where, or on which level a 'const' is missing, etc.
9232 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9233 << NonRefType << SourceType << 2 /*incompatible quals*/
9234 << Args[0]->getSourceRange();
9235 break;
9236 }
9237
9238 case FK_ReferenceInitFailed:
9239 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9240 << DestType.getNonReferenceType()
9241 << DestType.getNonReferenceType()->isIncompleteType()
9242 << OnlyArg->isLValue()
9243 << OnlyArg->getType()
9244 << Args[0]->getSourceRange();
9245 emitBadConversionNotes(S, Entity, Args[0]);
9246 break;
9247
9248 case FK_ConversionFailed: {
9249 QualType FromType = OnlyArg->getType();
9250 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9251 << (int)Entity.getKind()
9252 << DestType
9253 << OnlyArg->isLValue()
9254 << FromType
9255 << Args[0]->getSourceRange();
9256 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9257 S.Diag(Kind.getLocation(), PDiag);
9258 emitBadConversionNotes(S, Entity, Args[0]);
9259 break;
9260 }
9261
9262 case FK_ConversionFromPropertyFailed:
9263 // No-op. This error has already been reported.
9264 break;
9265
9266 case FK_TooManyInitsForScalar: {
9267 SourceRange R;
9268
9269 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9270 if (InitList && InitList->getNumInits() >= 1) {
9271 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9272 } else {
9273 assert(Args.size() > 1 && "Expected multiple initializers!")(static_cast <bool> (Args.size() > 1 && "Expected multiple initializers!"
) ? void (0) : __assert_fail ("Args.size() > 1 && \"Expected multiple initializers!\""
, "clang/lib/Sema/SemaInit.cpp", 9273, __extension__ __PRETTY_FUNCTION__
))
;
9274 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9275 }
9276
9277 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9278 if (Kind.isCStyleOrFunctionalCast())
9279 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9280 << R;
9281 else
9282 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9283 << /*scalar=*/2 << R;
9284 break;
9285 }
9286
9287 case FK_ParenthesizedListInitForScalar:
9288 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9289 << 0 << Entity.getType() << Args[0]->getSourceRange();
9290 break;
9291
9292 case FK_ReferenceBindingToInitList:
9293 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9294 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9295 break;
9296
9297 case FK_InitListBadDestinationType:
9298 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9299 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9300 break;
9301
9302 case FK_ListConstructorOverloadFailed:
9303 case FK_ConstructorOverloadFailed: {
9304 SourceRange ArgsRange;
9305 if (Args.size())
9306 ArgsRange =
9307 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9308
9309 if (Failure == FK_ListConstructorOverloadFailed) {
9310 assert(Args.size() == 1 &&(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\""
, "clang/lib/Sema/SemaInit.cpp", 9311, __extension__ __PRETTY_FUNCTION__
))
9311 "List construction from other than 1 argument.")(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\""
, "clang/lib/Sema/SemaInit.cpp", 9311, __extension__ __PRETTY_FUNCTION__
))
;
9312 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9313 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9314 }
9315
9316 // FIXME: Using "DestType" for the entity we're printing is probably
9317 // bad.
9318 switch (FailedOverloadResult) {
9319 case OR_Ambiguous:
9320 FailedCandidateSet.NoteCandidates(
9321 PartialDiagnosticAt(Kind.getLocation(),
9322 S.PDiag(diag::err_ovl_ambiguous_init)
9323 << DestType << ArgsRange),
9324 S, OCD_AmbiguousCandidates, Args);
9325 break;
9326
9327 case OR_No_Viable_Function:
9328 if (Kind.getKind() == InitializationKind::IK_Default &&
9329 (Entity.getKind() == InitializedEntity::EK_Base ||
9330 Entity.getKind() == InitializedEntity::EK_Member) &&
9331 isa<CXXConstructorDecl>(S.CurContext)) {
9332 // This is implicit default initialization of a member or
9333 // base within a constructor. If no viable function was
9334 // found, notify the user that they need to explicitly
9335 // initialize this base/member.
9336 CXXConstructorDecl *Constructor
9337 = cast<CXXConstructorDecl>(S.CurContext);
9338 const CXXRecordDecl *InheritedFrom = nullptr;
9339 if (auto Inherited = Constructor->getInheritedConstructor())
9340 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9341 if (Entity.getKind() == InitializedEntity::EK_Base) {
9342 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9343 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9344 << S.Context.getTypeDeclType(Constructor->getParent())
9345 << /*base=*/0
9346 << Entity.getType()
9347 << InheritedFrom;
9348
9349 RecordDecl *BaseDecl
9350 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9351 ->getDecl();
9352 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9353 << S.Context.getTagDeclType(BaseDecl);
9354 } else {
9355 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9356 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9357 << S.Context.getTypeDeclType(Constructor->getParent())
9358 << /*member=*/1
9359 << Entity.getName()
9360 << InheritedFrom;
9361 S.Diag(Entity.getDecl()->getLocation(),
9362 diag::note_member_declared_at);
9363
9364 if (const RecordType *Record
9365 = Entity.getType()->getAs<RecordType>())
9366 S.Diag(Record->getDecl()->getLocation(),
9367 diag::note_previous_decl)
9368 << S.Context.getTagDeclType(Record->getDecl());
9369 }
9370 break;
9371 }
9372
9373 FailedCandidateSet.NoteCandidates(
9374 PartialDiagnosticAt(
9375 Kind.getLocation(),
9376 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9377 << DestType << ArgsRange),
9378 S, OCD_AllCandidates, Args);
9379 break;
9380
9381 case OR_Deleted: {
9382 OverloadCandidateSet::iterator Best;
9383 OverloadingResult Ovl
9384 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9385 if (Ovl != OR_Deleted) {
9386 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9387 << DestType << ArgsRange;
9388 llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?"
, "clang/lib/Sema/SemaInit.cpp", 9388)
;
9389 break;
9390 }
9391
9392 // If this is a defaulted or implicitly-declared function, then
9393 // it was implicitly deleted. Make it clear that the deletion was
9394 // implicit.
9395 if (S.isImplicitlyDeleted(Best->Function))
9396 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9397 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9398 << DestType << ArgsRange;
9399 else
9400 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9401 << DestType << ArgsRange;
9402
9403 S.NoteDeletedFunction(Best->Function);
9404 break;
9405 }
9406
9407 case OR_Success:
9408 llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!",
"clang/lib/Sema/SemaInit.cpp", 9408)
;
9409 }
9410 }
9411 break;
9412
9413 case FK_DefaultInitOfConst:
9414 if (Entity.getKind() == InitializedEntity::EK_Member &&
9415 isa<CXXConstructorDecl>(S.CurContext)) {
9416 // This is implicit default-initialization of a const member in
9417 // a constructor. Complain that it needs to be explicitly
9418 // initialized.
9419 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9420 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9421 << (Constructor->getInheritedConstructor() ? 2 :
9422 Constructor->isImplicit() ? 1 : 0)
9423 << S.Context.getTypeDeclType(Constructor->getParent())
9424 << /*const=*/1
9425 << Entity.getName();
9426 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9427 << Entity.getName();
9428 } else {
9429 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9430 << DestType << (bool)DestType->getAs<RecordType>();
9431 }
9432 break;
9433
9434 case FK_Incomplete:
9435 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9436 diag::err_init_incomplete_type);
9437 break;
9438
9439 case FK_ListInitializationFailed: {
9440 // Run the init list checker again to emit diagnostics.
9441 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9442 diagnoseListInit(S, Entity, InitList);
9443 break;
9444 }
9445
9446 case FK_PlaceholderType: {
9447 // FIXME: Already diagnosed!
9448 break;
9449 }
9450
9451 case FK_ExplicitConstructor: {
9452 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9453 << Args[0]->getSourceRange();
9454 OverloadCandidateSet::iterator Best;
9455 OverloadingResult Ovl
9456 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9457 (void)Ovl;
9458 assert(Ovl == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (Ovl == OR_Success && "Inconsistent overload resolution"
) ? void (0) : __assert_fail ("Ovl == OR_Success && \"Inconsistent overload resolution\""
, "clang/lib/Sema/SemaInit.cpp", 9458, __extension__ __PRETTY_FUNCTION__
))
;
9459 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9460 S.Diag(CtorDecl->getLocation(),
9461 diag::note_explicit_ctor_deduction_guide_here) << false;
9462 break;
9463 }
9464 }
9465
9466 PrintInitLocationNote(S, Entity);
9467 return true;
9468}
9469
9470void InitializationSequence::dump(raw_ostream &OS) const {
9471 switch (SequenceKind) {
9472 case FailedSequence: {
9473 OS << "Failed sequence: ";
9474 switch (Failure) {
9475 case FK_TooManyInitsForReference:
9476 OS << "too many initializers for reference";
9477 break;
9478
9479 case FK_ParenthesizedListInitForReference:
9480 OS << "parenthesized list init for reference";
9481 break;
9482
9483 case FK_ArrayNeedsInitList:
9484 OS << "array requires initializer list";
9485 break;
9486
9487 case FK_AddressOfUnaddressableFunction:
9488 OS << "address of unaddressable function was taken";
9489 break;
9490
9491 case FK_ArrayNeedsInitListOrStringLiteral:
9492 OS << "array requires initializer list or string literal";
9493 break;
9494
9495 case FK_ArrayNeedsInitListOrWideStringLiteral:
9496 OS << "array requires initializer list or wide string literal";
9497 break;
9498
9499 case FK_NarrowStringIntoWideCharArray:
9500 OS << "narrow string into wide char array";
9501 break;
9502
9503 case FK_WideStringIntoCharArray:
9504 OS << "wide string into char array";
9505 break;
9506
9507 case FK_IncompatWideStringIntoWideChar:
9508 OS << "incompatible wide string into wide char array";
9509 break;
9510
9511 case FK_PlainStringIntoUTF8Char:
9512 OS << "plain string literal into char8_t array";
9513 break;
9514
9515 case FK_UTF8StringIntoPlainChar:
9516 OS << "u8 string literal into char array";
9517 break;
9518
9519 case FK_ArrayTypeMismatch:
9520 OS << "array type mismatch";
9521 break;
9522
9523 case FK_NonConstantArrayInit:
9524 OS << "non-constant array initializer";
9525 break;
9526
9527 case FK_AddressOfOverloadFailed:
9528 OS << "address of overloaded function failed";
9529 break;
9530
9531 case FK_ReferenceInitOverloadFailed:
9532 OS << "overload resolution for reference initialization failed";
9533 break;
9534
9535 case FK_NonConstLValueReferenceBindingToTemporary:
9536 OS << "non-const lvalue reference bound to temporary";
9537 break;
9538
9539 case FK_NonConstLValueReferenceBindingToBitfield:
9540 OS << "non-const lvalue reference bound to bit-field";
9541 break;
9542
9543 case FK_NonConstLValueReferenceBindingToVectorElement:
9544 OS << "non-const lvalue reference bound to vector element";
9545 break;
9546
9547 case FK_NonConstLValueReferenceBindingToMatrixElement:
9548 OS << "non-const lvalue reference bound to matrix element";
9549 break;
9550
9551 case FK_NonConstLValueReferenceBindingToUnrelated:
9552 OS << "non-const lvalue reference bound to unrelated type";
9553 break;
9554
9555 case FK_RValueReferenceBindingToLValue:
9556 OS << "rvalue reference bound to an lvalue";
9557 break;
9558
9559 case FK_ReferenceInitDropsQualifiers:
9560 OS << "reference initialization drops qualifiers";
9561 break;
9562
9563 case FK_ReferenceAddrspaceMismatchTemporary:
9564 OS << "reference with mismatching address space bound to temporary";
9565 break;
9566
9567 case FK_ReferenceInitFailed:
9568 OS << "reference initialization failed";
9569 break;
9570
9571 case FK_ConversionFailed:
9572 OS << "conversion failed";
9573 break;
9574
9575 case FK_ConversionFromPropertyFailed:
9576 OS << "conversion from property failed";
9577 break;
9578
9579 case FK_TooManyInitsForScalar:
9580 OS << "too many initializers for scalar";
9581 break;
9582
9583 case FK_ParenthesizedListInitForScalar:
9584 OS << "parenthesized list init for reference";
9585 break;
9586
9587 case FK_ReferenceBindingToInitList:
9588 OS << "referencing binding to initializer list";
9589 break;
9590
9591 case FK_InitListBadDestinationType:
9592 OS << "initializer list for non-aggregate, non-scalar type";
9593 break;
9594
9595 case FK_UserConversionOverloadFailed:
9596 OS << "overloading failed for user-defined conversion";
9597 break;
9598
9599 case FK_ConstructorOverloadFailed:
9600 OS << "constructor overloading failed";
9601 break;
9602
9603 case FK_DefaultInitOfConst:
9604 OS << "default initialization of a const variable";
9605 break;
9606
9607 case FK_Incomplete:
9608 OS << "initialization of incomplete type";
9609 break;
9610
9611 case FK_ListInitializationFailed:
9612 OS << "list initialization checker failure";
9613 break;
9614
9615 case FK_VariableLengthArrayHasInitializer:
9616 OS << "variable length array has an initializer";
9617 break;
9618
9619 case FK_PlaceholderType:
9620 OS << "initializer expression isn't contextually valid";
9621 break;
9622
9623 case FK_ListConstructorOverloadFailed:
9624 OS << "list constructor overloading failed";
9625 break;
9626
9627 case FK_ExplicitConstructor:
9628 OS << "list copy initialization chose explicit constructor";
9629 break;
9630 }
9631 OS << '\n';
9632 return;
9633 }
9634
9635 case DependentSequence:
9636 OS << "Dependent sequence\n";
9637 return;
9638
9639 case NormalSequence:
9640 OS << "Normal sequence: ";
9641 break;
9642 }
9643
9644 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9645 if (S != step_begin()) {
9646 OS << " -> ";
9647 }
9648
9649 switch (S->Kind) {
9650 case SK_ResolveAddressOfOverloadedFunction:
9651 OS << "resolve address of overloaded function";
9652 break;
9653
9654 case SK_CastDerivedToBasePRValue:
9655 OS << "derived-to-base (prvalue)";
9656 break;
9657
9658 case SK_CastDerivedToBaseXValue:
9659 OS << "derived-to-base (xvalue)";
9660 break;
9661
9662 case SK_CastDerivedToBaseLValue:
9663 OS << "derived-to-base (lvalue)";
9664 break;
9665
9666 case SK_BindReference:
9667 OS << "bind reference to lvalue";
9668 break;
9669
9670 case SK_BindReferenceToTemporary:
9671 OS << "bind reference to a temporary";
9672 break;
9673
9674 case SK_FinalCopy:
9675 OS << "final copy in class direct-initialization";
9676 break;
9677
9678 case SK_ExtraneousCopyToTemporary:
9679 OS << "extraneous C++03 copy to temporary";
9680 break;
9681
9682 case SK_UserConversion:
9683 OS << "user-defined conversion via " << *S->Function.Function;
9684 break;
9685
9686 case SK_QualificationConversionPRValue:
9687 OS << "qualification conversion (prvalue)";
9688 break;
9689
9690 case SK_QualificationConversionXValue:
9691 OS << "qualification conversion (xvalue)";
9692 break;
9693
9694 case SK_QualificationConversionLValue:
9695 OS << "qualification conversion (lvalue)";
9696 break;
9697
9698 case SK_FunctionReferenceConversion:
9699 OS << "function reference conversion";
9700 break;
9701
9702 case SK_AtomicConversion:
9703 OS << "non-atomic-to-atomic conversion";
9704 break;
9705
9706 case SK_ConversionSequence:
9707 OS << "implicit conversion sequence (";
9708 S->ICS->dump(); // FIXME: use OS
9709 OS << ")";
9710 break;
9711
9712 case SK_ConversionSequenceNoNarrowing:
9713 OS << "implicit conversion sequence with narrowing prohibited (";
9714 S->ICS->dump(); // FIXME: use OS
9715 OS << ")";
9716 break;
9717
9718 case SK_ListInitialization:
9719 OS << "list aggregate initialization";
9720 break;
9721
9722 case SK_UnwrapInitList:
9723 OS << "unwrap reference initializer list";
9724 break;
9725
9726 case SK_RewrapInitList:
9727 OS << "rewrap reference initializer list";
9728 break;
9729
9730 case SK_ConstructorInitialization:
9731 OS << "constructor initialization";
9732 break;
9733
9734 case SK_ConstructorInitializationFromList:
9735 OS << "list initialization via constructor";
9736 break;
9737
9738 case SK_ZeroInitialization:
9739 OS << "zero initialization";
9740 break;
9741
9742 case SK_CAssignment:
9743 OS << "C assignment";
9744 break;
9745
9746 case SK_StringInit:
9747 OS << "string initialization";
9748 break;
9749
9750 case SK_ObjCObjectConversion:
9751 OS << "Objective-C object conversion";
9752 break;
9753
9754 case SK_ArrayLoopIndex:
9755 OS << "indexing for array initialization loop";
9756 break;
9757
9758 case SK_ArrayLoopInit:
9759 OS << "array initialization loop";
9760 break;
9761
9762 case SK_ArrayInit:
9763 OS << "array initialization";
9764 break;
9765
9766 case SK_GNUArrayInit:
9767 OS << "array initialization (GNU extension)";
9768 break;
9769
9770 case SK_ParenthesizedArrayInit:
9771 OS << "parenthesized array initialization";
9772 break;
9773
9774 case SK_PassByIndirectCopyRestore:
9775 OS << "pass by indirect copy and restore";
9776 break;
9777
9778 case SK_PassByIndirectRestore:
9779 OS << "pass by indirect restore";
9780 break;
9781
9782 case SK_ProduceObjCObject:
9783 OS << "Objective-C object retension";
9784 break;
9785
9786 case SK_StdInitializerList:
9787 OS << "std::initializer_list from initializer list";
9788 break;
9789
9790 case SK_StdInitializerListConstructorCall:
9791 OS << "list initialization from std::initializer_list";
9792 break;
9793
9794 case SK_OCLSamplerInit:
9795 OS << "OpenCL sampler_t from integer constant";
9796 break;
9797
9798 case SK_OCLZeroOpaqueType:
9799 OS << "OpenCL opaque type from zero";
9800 break;
9801 }
9802
9803 OS << " [" << S->Type.getAsString() << ']';
9804 }
9805
9806 OS << '\n';
9807}
9808
9809void InitializationSequence::dump() const {
9810 dump(llvm::errs());
9811}
9812
9813static bool NarrowingErrs(const LangOptions &L) {
9814 return L.CPlusPlus11 &&
9815 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
9816}
9817
9818static void DiagnoseNarrowingInInitList(Sema &S,
9819 const ImplicitConversionSequence &ICS,
9820 QualType PreNarrowingType,
9821 QualType EntityType,
9822 const Expr *PostInit) {
9823 const StandardConversionSequence *SCS = nullptr;
9824 switch (ICS.getKind()) {
9825 case ImplicitConversionSequence::StandardConversion:
9826 SCS = &ICS.Standard;
9827 break;
9828 case ImplicitConversionSequence::UserDefinedConversion:
9829 SCS = &ICS.UserDefined.After;
9830 break;
9831 case ImplicitConversionSequence::AmbiguousConversion:
9832 case ImplicitConversionSequence::EllipsisConversion:
9833 case ImplicitConversionSequence::BadConversion:
9834 return;
9835 }
9836
9837 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9838 APValue ConstantValue;
9839 QualType ConstantType;
9840 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9841 ConstantType)) {
9842 case NK_Not_Narrowing:
9843 case NK_Dependent_Narrowing:
9844 // No narrowing occurred.
9845 return;
9846
9847 case NK_Type_Narrowing:
9848 // This was a floating-to-integer conversion, which is always considered a
9849 // narrowing conversion even if the value is a constant and can be
9850 // represented exactly as an integer.
9851 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
9852 ? diag::ext_init_list_type_narrowing
9853 : diag::warn_init_list_type_narrowing)
9854 << PostInit->getSourceRange()
9855 << PreNarrowingType.getLocalUnqualifiedType()
9856 << EntityType.getLocalUnqualifiedType();
9857 break;
9858
9859 case NK_Constant_Narrowing:
9860 // A constant value was narrowed.
9861 S.Diag(PostInit->getBeginLoc(),
9862 NarrowingErrs(S.getLangOpts())
9863 ? diag::ext_init_list_constant_narrowing
9864 : diag::warn_init_list_constant_narrowing)
9865 << PostInit->getSourceRange()
9866 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9867 << EntityType.getLocalUnqualifiedType();
9868 break;
9869
9870 case NK_Variable_Narrowing:
9871 // A variable's value may have been narrowed.
9872 S.Diag(PostInit->getBeginLoc(),
9873 NarrowingErrs(S.getLangOpts())
9874 ? diag::ext_init_list_variable_narrowing
9875 : diag::warn_init_list_variable_narrowing)
9876 << PostInit->getSourceRange()
9877 << PreNarrowingType.getLocalUnqualifiedType()
9878 << EntityType.getLocalUnqualifiedType();
9879 break;
9880 }
9881
9882 SmallString<128> StaticCast;
9883 llvm::raw_svector_ostream OS(StaticCast);
9884 OS << "static_cast<";
9885 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9886 // It's important to use the typedef's name if there is one so that the
9887 // fixit doesn't break code using types like int64_t.
9888 //
9889 // FIXME: This will break if the typedef requires qualification. But
9890 // getQualifiedNameAsString() includes non-machine-parsable components.
9891 OS << *TT->getDecl();
9892 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9893 OS << BT->getName(S.getLangOpts());
9894 else {
9895 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9896 // with a broken cast.
9897 return;
9898 }
9899 OS << ">(";
9900 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9901 << PostInit->getSourceRange()
9902 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9903 << FixItHint::CreateInsertion(
9904 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9905}
9906
9907//===----------------------------------------------------------------------===//
9908// Initialization helper functions
9909//===----------------------------------------------------------------------===//
9910bool
9911Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9912 ExprResult Init) {
9913 if (Init.isInvalid())
9914 return false;
9915
9916 Expr *InitE = Init.get();
9917 assert(InitE && "No initialization expression")(static_cast <bool> (InitE && "No initialization expression"
) ? void (0) : __assert_fail ("InitE && \"No initialization expression\""
, "clang/lib/Sema/SemaInit.cpp", 9917, __extension__ __PRETTY_FUNCTION__
))
;
9918
9919 InitializationKind Kind =
9920 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
9921 InitializationSequence Seq(*this, Entity, Kind, InitE);
9922 return !Seq.Failed();
9923}
9924
9925ExprResult
9926Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9927 SourceLocation EqualLoc,
9928 ExprResult Init,
9929 bool TopLevelOfInitList,
9930 bool AllowExplicit) {
9931 if (Init.isInvalid())
9932 return ExprError();
9933
9934 Expr *InitE = Init.get();
9935 assert(InitE && "No initialization expression?")(static_cast <bool> (InitE && "No initialization expression?"
) ? void (0) : __assert_fail ("InitE && \"No initialization expression?\""
, "clang/lib/Sema/SemaInit.cpp", 9935, __extension__ __PRETTY_FUNCTION__
))
;
9936
9937 if (EqualLoc.isInvalid())
9938 EqualLoc = InitE->getBeginLoc();
9939
9940 InitializationKind Kind = InitializationKind::CreateCopy(
9941 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9942 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
9943
9944 // Prevent infinite recursion when performing parameter copy-initialization.
9945 const bool ShouldTrackCopy =
9946 Entity.isParameterKind() && Seq.isConstructorInitialization();
9947 if (ShouldTrackCopy) {
9948 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
9949 Seq.SetOverloadFailure(
9950 InitializationSequence::FK_ConstructorOverloadFailed,
9951 OR_No_Viable_Function);
9952
9953 // Try to give a meaningful diagnostic note for the problematic
9954 // constructor.
9955 const auto LastStep = Seq.step_end() - 1;
9956 assert(LastStep->Kind ==(static_cast <bool> (LastStep->Kind == InitializationSequence
::SK_ConstructorInitialization) ? void (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization"
, "clang/lib/Sema/SemaInit.cpp", 9957, __extension__ __PRETTY_FUNCTION__
))
9957 InitializationSequence::SK_ConstructorInitialization)(static_cast <bool> (LastStep->Kind == InitializationSequence
::SK_ConstructorInitialization) ? void (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization"
, "clang/lib/Sema/SemaInit.cpp", 9957, __extension__ __PRETTY_FUNCTION__
))
;
9958 const FunctionDecl *Function = LastStep->Function.Function;
9959 auto Candidate =
9960 llvm::find_if(Seq.getFailedCandidateSet(),
9961 [Function](const OverloadCandidate &Candidate) -> bool {
9962 return Candidate.Viable &&
9963 Candidate.Function == Function &&
9964 Candidate.Conversions.size() > 0;
9965 });
9966 if (Candidate != Seq.getFailedCandidateSet().end() &&
9967 Function->getNumParams() > 0) {
9968 Candidate->Viable = false;
9969 Candidate->FailureKind = ovl_fail_bad_conversion;
9970 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9971 InitE,
9972 Function->getParamDecl(0)->getType());
9973 }
9974 }
9975 CurrentParameterCopyTypes.push_back(Entity.getType());
9976 }
9977
9978 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
9979
9980 if (ShouldTrackCopy)
9981 CurrentParameterCopyTypes.pop_back();
9982
9983 return Result;
9984}
9985
9986/// Determine whether RD is, or is derived from, a specialization of CTD.
9987static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9988 ClassTemplateDecl *CTD) {
9989 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9990 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9991 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9992 };
9993 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9994}
9995
9996QualType Sema::DeduceTemplateSpecializationFromInitializer(
9997 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9998 const InitializationKind &Kind, MultiExprArg Inits) {
9999 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10000 TSInfo->getType()->getContainedDeducedType());
10001 assert(DeducedTST && "not a deduced template specialization type")(static_cast <bool> (DeducedTST && "not a deduced template specialization type"
) ? void (0) : __assert_fail ("DeducedTST && \"not a deduced template specialization type\""
, "clang/lib/Sema/SemaInit.cpp", 10001, __extension__ __PRETTY_FUNCTION__
))
;
10002
10003 auto TemplateName = DeducedTST->getTemplateName();
10004 if (TemplateName.isDependent())
10005 return SubstAutoTypeDependent(TSInfo->getType());
10006
10007 // We can only perform deduction for class templates.
10008 auto *Template =
10009 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10010 if (!Template) {
10011 Diag(Kind.getLocation(),
10012 diag::err_deduced_non_class_template_specialization_type)
10013 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10014 if (auto *TD = TemplateName.getAsTemplateDecl())
10015 Diag(TD->getLocation(), diag::note_template_decl_here);
10016 return QualType();
10017 }
10018
10019 // Can't deduce from dependent arguments.
10020 if (Expr::hasAnyTypeDependentArguments(Inits)) {
10021 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10022 diag::warn_cxx14_compat_class_template_argument_deduction)
10023 << TSInfo->getTypeLoc().getSourceRange() << 0;
10024 return SubstAutoTypeDependent(TSInfo->getType());
10025 }
10026
10027 // FIXME: Perform "exact type" matching first, per CWG discussion?
10028 // Or implement this via an implied 'T(T) -> T' deduction guide?
10029
10030 // FIXME: Do we need/want a std::initializer_list<T> special case?
10031
10032 // Look up deduction guides, including those synthesized from constructors.
10033 //
10034 // C++1z [over.match.class.deduct]p1:
10035 // A set of functions and function templates is formed comprising:
10036 // - For each constructor of the class template designated by the
10037 // template-name, a function template [...]
10038 // - For each deduction-guide, a function or function template [...]
10039 DeclarationNameInfo NameInfo(
10040 Context.DeclarationNames.getCXXDeductionGuideName(Template),
10041 TSInfo->getTypeLoc().getEndLoc());
10042 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10043 LookupQualifiedName(Guides, Template->getDeclContext());
10044
10045 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10046 // clear on this, but they're not found by name so access does not apply.
10047 Guides.suppressDiagnostics();
10048
10049 // Figure out if this is list-initialization.
10050 InitListExpr *ListInit =
10051 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10052 ? dyn_cast<InitListExpr>(Inits[0])
10053 : nullptr;
10054
10055 // C++1z [over.match.class.deduct]p1:
10056 // Initialization and overload resolution are performed as described in
10057 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10058 // (as appropriate for the type of initialization performed) for an object
10059 // of a hypothetical class type, where the selected functions and function
10060 // templates are considered to be the constructors of that class type
10061 //
10062 // Since we know we're initializing a class type of a type unrelated to that
10063 // of the initializer, this reduces to something fairly reasonable.
10064 OverloadCandidateSet Candidates(Kind.getLocation(),
10065 OverloadCandidateSet::CSK_Normal);
10066 OverloadCandidateSet::iterator Best;
10067
10068 bool HasAnyDeductionGuide = false;
10069 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10070
10071 auto tryToResolveOverload =
10072 [&](bool OnlyListConstructors) -> OverloadingResult {
10073 Candidates.clear(OverloadCandidateSet::CSK_Normal);
10074 HasAnyDeductionGuide = false;
10075
10076 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10077 NamedDecl *D = (*I)->getUnderlyingDecl();
10078 if (D->isInvalidDecl())
10079 continue;
10080
10081 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10082 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
10083 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10084 if (!GD)
10085 continue;
10086
10087 if (!GD->isImplicit())
10088 HasAnyDeductionGuide = true;
10089
10090 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10091 // For copy-initialization, the candidate functions are all the
10092 // converting constructors (12.3.1) of that class.
10093 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10094 // The converting constructors of T are candidate functions.
10095 if (!AllowExplicit) {
10096 // Overload resolution checks whether the deduction guide is declared
10097 // explicit for us.
10098
10099 // When looking for a converting constructor, deduction guides that
10100 // could never be called with one argument are not interesting to
10101 // check or note.
10102 if (GD->getMinRequiredArguments() > 1 ||
10103 (GD->getNumParams() == 0 && !GD->isVariadic()))
10104 continue;
10105 }
10106
10107 // C++ [over.match.list]p1.1: (first phase list initialization)
10108 // Initially, the candidate functions are the initializer-list
10109 // constructors of the class T
10110 if (OnlyListConstructors && !isInitListConstructor(GD))
10111 continue;
10112
10113 // C++ [over.match.list]p1.2: (second phase list initialization)
10114 // the candidate functions are all the constructors of the class T
10115 // C++ [over.match.ctor]p1: (all other cases)
10116 // the candidate functions are all the constructors of the class of
10117 // the object being initialized
10118
10119 // C++ [over.best.ics]p4:
10120 // When [...] the constructor [...] is a candidate by
10121 // - [over.match.copy] (in all cases)
10122 // FIXME: The "second phase of [over.match.list] case can also
10123 // theoretically happen here, but it's not clear whether we can
10124 // ever have a parameter of the right type.
10125 bool SuppressUserConversions = Kind.isCopyInit();
10126
10127 if (TD)
10128 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
10129 Inits, Candidates, SuppressUserConversions,
10130 /*PartialOverloading*/ false,
10131 AllowExplicit);
10132 else
10133 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
10134 SuppressUserConversions,
10135 /*PartialOverloading*/ false, AllowExplicit);
10136 }
10137 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10138 };
10139
10140 OverloadingResult Result = OR_No_Viable_Function;
10141
10142 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10143 // try initializer-list constructors.
10144 if (ListInit) {
10145 bool TryListConstructors = true;
10146
10147 // Try list constructors unless the list is empty and the class has one or
10148 // more default constructors, in which case those constructors win.
10149 if (!ListInit->getNumInits()) {
10150 for (NamedDecl *D : Guides) {
10151 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10152 if (FD && FD->getMinRequiredArguments() == 0) {
10153 TryListConstructors = false;
10154 break;
10155 }
10156 }
10157 } else if (ListInit->getNumInits() == 1) {
10158 // C++ [over.match.class.deduct]:
10159 // As an exception, the first phase in [over.match.list] (considering
10160 // initializer-list constructors) is omitted if the initializer list
10161 // consists of a single expression of type cv U, where U is a
10162 // specialization of C or a class derived from a specialization of C.
10163 Expr *E = ListInit->getInit(0);
10164 auto *RD = E->getType()->getAsCXXRecordDecl();
10165 if (!isa<InitListExpr>(E) && RD &&
10166 isCompleteType(Kind.getLocation(), E->getType()) &&
10167 isOrIsDerivedFromSpecializationOf(RD, Template))
10168 TryListConstructors = false;
10169 }
10170
10171 if (TryListConstructors)
10172 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
10173 // Then unwrap the initializer list and try again considering all
10174 // constructors.
10175 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10176 }
10177
10178 // If list-initialization fails, or if we're doing any other kind of
10179 // initialization, we (eventually) consider constructors.
10180 if (Result == OR_No_Viable_Function)
10181 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
10182
10183 switch (Result) {
10184 case OR_Ambiguous:
10185 // FIXME: For list-initialization candidates, it'd usually be better to
10186 // list why they were not viable when given the initializer list itself as
10187 // an argument.
10188 Candidates.NoteCandidates(
10189 PartialDiagnosticAt(
10190 Kind.getLocation(),
10191 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10192 << TemplateName),
10193 *this, OCD_AmbiguousCandidates, Inits);
10194 return QualType();
10195
10196 case OR_No_Viable_Function: {
10197 CXXRecordDecl *Primary =
10198 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10199 bool Complete =
10200 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10201 Candidates.NoteCandidates(
10202 PartialDiagnosticAt(
10203 Kind.getLocation(),
10204 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10205 : diag::err_deduced_class_template_incomplete)
10206 << TemplateName << !Guides.empty()),
10207 *this, OCD_AllCandidates, Inits);
10208 return QualType();
10209 }
10210
10211 case OR_Deleted: {
10212 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10213 << TemplateName;
10214 NoteDeletedFunction(Best->Function);
10215 return QualType();
10216 }
10217
10218 case OR_Success:
10219 // C++ [over.match.list]p1:
10220 // In copy-list-initialization, if an explicit constructor is chosen, the
10221 // initialization is ill-formed.
10222 if (Kind.isCopyInit() && ListInit &&
10223 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10224 bool IsDeductionGuide = !Best->Function->isImplicit();
10225 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10226 << TemplateName << IsDeductionGuide;
10227 Diag(Best->Function->getLocation(),
10228 diag::note_explicit_ctor_deduction_guide_here)
10229 << IsDeductionGuide;
10230 return QualType();
10231 }
10232
10233 // Make sure we didn't select an unusable deduction guide, and mark it
10234 // as referenced.
10235 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10236 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10237 break;
10238 }
10239
10240 // C++ [dcl.type.class.deduct]p1:
10241 // The placeholder is replaced by the return type of the function selected
10242 // by overload resolution for class template deduction.
10243 QualType DeducedType =
10244 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10245 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10246 diag::warn_cxx14_compat_class_template_argument_deduction)
10247 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10248
10249 // Warn if CTAD was used on a type that does not have any user-defined
10250 // deduction guides.
10251 if (!HasAnyDeductionGuide) {
10252 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10253 diag::warn_ctad_maybe_unsupported)
10254 << TemplateName;
10255 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10256 }
10257
10258 return DeducedType;
10259}

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