Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 12801, column 16
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp

1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/NonTrivialTypeVisitor.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
43#include "clang/Sema/SemaInternal.h"
44#include "clang/Sema/Template.h"
45#include "llvm/ADT/SmallString.h"
46#include "llvm/ADT/Triple.h"
47#include <algorithm>
48#include <cstring>
49#include <functional>
50#include <unordered_map>
51
52using namespace clang;
53using namespace sema;
54
55Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 if (OwnedType) {
57 Decl *Group[2] = { OwnedType, Ptr };
58 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
59 }
60
61 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
62}
63
64namespace {
65
66class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
67 public:
68 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
69 bool AllowTemplates = false,
70 bool AllowNonTemplates = true)
71 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
72 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
73 WantExpressionKeywords = false;
74 WantCXXNamedCasts = false;
75 WantRemainingKeywords = false;
76 }
77
78 bool ValidateCandidate(const TypoCorrection &candidate) override {
79 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
80 if (!AllowInvalidDecl && ND->isInvalidDecl())
81 return false;
82
83 if (getAsTypeTemplateDecl(ND))
84 return AllowTemplates;
85
86 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
87 if (!IsType)
88 return false;
89
90 if (AllowNonTemplates)
91 return true;
92
93 // An injected-class-name of a class template (specialization) is valid
94 // as a template or as a non-template.
95 if (AllowTemplates) {
96 auto *RD = dyn_cast<CXXRecordDecl>(ND);
97 if (!RD || !RD->isInjectedClassName())
98 return false;
99 RD = cast<CXXRecordDecl>(RD->getDeclContext());
100 return RD->getDescribedClassTemplate() ||
101 isa<ClassTemplateSpecializationDecl>(RD);
102 }
103
104 return false;
105 }
106
107 return !WantClassName && candidate.isKeyword();
108 }
109
110 std::unique_ptr<CorrectionCandidateCallback> clone() override {
111 return std::make_unique<TypeNameValidatorCCC>(*this);
112 }
113
114 private:
115 bool AllowInvalidDecl;
116 bool WantClassName;
117 bool AllowTemplates;
118 bool AllowNonTemplates;
119};
120
121} // end anonymous namespace
122
123/// Determine whether the token kind starts a simple-type-specifier.
124bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
125 switch (Kind) {
126 // FIXME: Take into account the current language when deciding whether a
127 // token kind is a valid type specifier
128 case tok::kw_short:
129 case tok::kw_long:
130 case tok::kw___int64:
131 case tok::kw___int128:
132 case tok::kw_signed:
133 case tok::kw_unsigned:
134 case tok::kw_void:
135 case tok::kw_char:
136 case tok::kw_int:
137 case tok::kw_half:
138 case tok::kw_float:
139 case tok::kw_double:
140 case tok::kw__Float16:
141 case tok::kw___float128:
142 case tok::kw_wchar_t:
143 case tok::kw_bool:
144 case tok::kw___underlying_type:
145 case tok::kw___auto_type:
146 return true;
147
148 case tok::annot_typename:
149 case tok::kw_char16_t:
150 case tok::kw_char32_t:
151 case tok::kw_typeof:
152 case tok::annot_decltype:
153 case tok::kw_decltype:
154 return getLangOpts().CPlusPlus;
155
156 case tok::kw_char8_t:
157 return getLangOpts().Char8;
158
159 default:
160 break;
161 }
162
163 return false;
164}
165
166namespace {
167enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171};
172} // end anonymous namespace
173
174/// Tries to perform unqualified lookup of the type decls in bases for
175/// dependent class.
176/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177/// type decl, \a FoundType if only type decls are found.
178static UnqualifiedTypeNameLookupResult
179lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = nullptr;
189 if (auto *BaseTT = Base.getType()->getAs<TagType>())
190 BaseRD = BaseTT->getAsCXXRecordDecl();
191 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST || !TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
204 if (const ClassTemplatePartialSpecializationDecl *PS =
205 CTD->findPartialSpecialization(Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(&II)) {
213 if (!isa<TypeDecl>(ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232}
233
234static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
255 // lookup during template instantiation.
256 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
257
258 ASTContext &Context = S.Context;
259 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
260 cast<Type>(Context.getRecordType(RD)));
261 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
269 DepTL.setElaboratedKeywordLoc(SourceLocation());
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
272}
273
274/// If the identifier refers to a type name within this scope,
275/// return the declaration of that type.
276///
277/// This routine performs ordinary name lookup of the identifier II
278/// within the given scope, with optional C++ scope specifier SS, to
279/// determine whether the name refers to a type. If so, returns an
280/// opaque pointer (actually a QualType) corresponding to that
281/// type. Otherwise, returns NULL.
282ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
283 Scope *S, CXXScopeSpec *SS,
284 bool isClassName, bool HasTrailingDot,
285 ParsedType ObjectTypePtr,
286 bool IsCtorOrDtorName,
287 bool WantNontrivialTypeSourceInfo,
288 bool IsClassTemplateDeductionContext,
289 IdentifierInfo **CorrectedII) {
290 // FIXME: Consider allowing this outside C++1z mode as an extension.
291 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
292 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
293 !isClassName && !HasTrailingDot;
294
295 // Determine where we will perform name lookup.
296 DeclContext *LookupCtx = nullptr;
297 if (ObjectTypePtr) {
298 QualType ObjectType = ObjectTypePtr.get();
299 if (ObjectType->isRecordType())
300 LookupCtx = computeDeclContext(ObjectType);
301 } else if (SS && SS->isNotEmpty()) {
302 LookupCtx = computeDeclContext(*SS, false);
303
304 if (!LookupCtx) {
305 if (isDependentScopeSpecifier(*SS)) {
306 // C++ [temp.res]p3:
307 // A qualified-id that refers to a type and in which the
308 // nested-name-specifier depends on a template-parameter (14.6.2)
309 // shall be prefixed by the keyword typename to indicate that the
310 // qualified-id denotes a type, forming an
311 // elaborated-type-specifier (7.1.5.3).
312 //
313 // We therefore do not perform any name lookup if the result would
314 // refer to a member of an unknown specialization.
315 if (!isClassName && !IsCtorOrDtorName)
316 return nullptr;
317
318 // We know from the grammar that this name refers to a type,
319 // so build a dependent node to describe the type.
320 if (WantNontrivialTypeSourceInfo)
321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
322
323 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
324 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
325 II, NameLoc);
326 return ParsedType::make(T);
327 }
328
329 return nullptr;
330 }
331
332 if (!LookupCtx->isDependentContext() &&
333 RequireCompleteDeclContext(*SS, LookupCtx))
334 return nullptr;
335 }
336
337 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
338 // lookup for class-names.
339 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
340 LookupOrdinaryName;
341 LookupResult Result(*this, &II, NameLoc, Kind);
342 if (LookupCtx) {
343 // Perform "qualified" name lookup into the declaration context we
344 // computed, which is either the type of the base of a member access
345 // expression or the declaration context associated with a prior
346 // nested-name-specifier.
347 LookupQualifiedName(Result, LookupCtx);
348
349 if (ObjectTypePtr && Result.empty()) {
350 // C++ [basic.lookup.classref]p3:
351 // If the unqualified-id is ~type-name, the type-name is looked up
352 // in the context of the entire postfix-expression. If the type T of
353 // the object expression is of a class type C, the type-name is also
354 // looked up in the scope of class C. At least one of the lookups shall
355 // find a name that refers to (possibly cv-qualified) T.
356 LookupName(Result, S);
357 }
358 } else {
359 // Perform unqualified name lookup.
360 LookupName(Result, S);
361
362 // For unqualified lookup in a class template in MSVC mode, look into
363 // dependent base classes where the primary class template is known.
364 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
365 if (ParsedType TypeInBase =
366 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
367 return TypeInBase;
368 }
369 }
370
371 NamedDecl *IIDecl = nullptr;
372 switch (Result.getResultKind()) {
373 case LookupResult::NotFound:
374 case LookupResult::NotFoundInCurrentInstantiation:
375 if (CorrectedII) {
376 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
377 AllowDeducedTemplate);
378 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
379 S, SS, CCC, CTK_ErrorRecovery);
380 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
381 TemplateTy Template;
382 bool MemberOfUnknownSpecialization;
383 UnqualifiedId TemplateName;
384 TemplateName.setIdentifier(NewII, NameLoc);
385 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
386 CXXScopeSpec NewSS, *NewSSPtr = SS;
387 if (SS && NNS) {
388 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
389 NewSSPtr = &NewSS;
390 }
391 if (Correction && (NNS || NewII != &II) &&
392 // Ignore a correction to a template type as the to-be-corrected
393 // identifier is not a template (typo correction for template names
394 // is handled elsewhere).
395 !(getLangOpts().CPlusPlus && NewSSPtr &&
396 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
397 Template, MemberOfUnknownSpecialization))) {
398 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
399 isClassName, HasTrailingDot, ObjectTypePtr,
400 IsCtorOrDtorName,
401 WantNontrivialTypeSourceInfo,
402 IsClassTemplateDeductionContext);
403 if (Ty) {
404 diagnoseTypo(Correction,
405 PDiag(diag::err_unknown_type_or_class_name_suggest)
406 << Result.getLookupName() << isClassName);
407 if (SS && NNS)
408 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
409 *CorrectedII = NewII;
410 return Ty;
411 }
412 }
413 }
414 // If typo correction failed or was not performed, fall through
415 LLVM_FALLTHROUGH[[gnu::fallthrough]];
416 case LookupResult::FoundOverloaded:
417 case LookupResult::FoundUnresolvedValue:
418 Result.suppressDiagnostics();
419 return nullptr;
420
421 case LookupResult::Ambiguous:
422 // Recover from type-hiding ambiguities by hiding the type. We'll
423 // do the lookup again when looking for an object, and we can
424 // diagnose the error then. If we don't do this, then the error
425 // about hiding the type will be immediately followed by an error
426 // that only makes sense if the identifier was treated like a type.
427 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
428 Result.suppressDiagnostics();
429 return nullptr;
430 }
431
432 // Look to see if we have a type anywhere in the list of results.
433 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
434 Res != ResEnd; ++Res) {
435 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
436 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
437 if (!IIDecl ||
438 (*Res)->getLocation().getRawEncoding() <
439 IIDecl->getLocation().getRawEncoding())
440 IIDecl = *Res;
441 }
442 }
443
444 if (!IIDecl) {
445 // None of the entities we found is a type, so there is no way
446 // to even assume that the result is a type. In this case, don't
447 // complain about the ambiguity. The parser will either try to
448 // perform this lookup again (e.g., as an object name), which
449 // will produce the ambiguity, or will complain that it expected
450 // a type name.
451 Result.suppressDiagnostics();
452 return nullptr;
453 }
454
455 // We found a type within the ambiguous lookup; diagnose the
456 // ambiguity and then return that type. This might be the right
457 // answer, or it might not be, but it suppresses any attempt to
458 // perform the name lookup again.
459 break;
460
461 case LookupResult::Found:
462 IIDecl = Result.getFoundDecl();
463 break;
464 }
465
466 assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void
> (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 466, __PRETTY_FUNCTION__))
;
467
468 QualType T;
469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470 // C++ [class.qual]p2: A lookup that would find the injected-class-name
471 // instead names the constructors of the class, except when naming a class.
472 // This is ill-formed when we're not actually forming a ctor or dtor name.
473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476 FoundRD->isInjectedClassName() &&
477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479 << &II << /*Type*/1;
480
481 DiagnoseUseOfDecl(IIDecl, NameLoc);
482
483 T = Context.getTypeDeclType(TD);
484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487 if (!HasTrailingDot)
488 T = Context.getObjCInterfaceType(IDecl);
489 } else if (AllowDeducedTemplate) {
490 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492 QualType(), false);
493 }
494
495 if (T.isNull()) {
496 // If it's not plausibly a type, suppress diagnostics.
497 Result.suppressDiagnostics();
498 return nullptr;
499 }
500
501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502 // constructor or destructor name (in such a case, the scope specifier
503 // will be attached to the enclosing Expr or Decl node).
504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505 !isa<ObjCInterfaceDecl>(IIDecl)) {
506 if (WantNontrivialTypeSourceInfo) {
507 // Construct a type with type-source information.
508 TypeLocBuilder Builder;
509 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510
511 T = getElaboratedType(ETK_None, *SS, T);
512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513 ElabTL.setElaboratedKeywordLoc(SourceLocation());
514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516 } else {
517 T = getElaboratedType(ETK_None, *SS, T);
518 }
519 }
520
521 return ParsedType::make(T);
522}
523
524// Builds a fake NNS for the given decl context.
525static NestedNameSpecifier *
526synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527 for (;; DC = DC->getLookupParent()) {
528 DC = DC->getPrimaryContext();
529 auto *ND = dyn_cast<NamespaceDecl>(DC);
530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531 return NestedNameSpecifier::Create(Context, nullptr, ND);
532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534 RD->getTypeForDecl());
535 else if (isa<TranslationUnitDecl>(DC))
536 return NestedNameSpecifier::GlobalSpecifier(Context);
537 }
538 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 538)
;
539}
540
541/// Find the parent class with dependent bases of the innermost enclosing method
542/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543/// up allowing unqualified dependent type names at class-level, which MSVC
544/// correctly rejects.
545static const CXXRecordDecl *
546findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548 DC = DC->getPrimaryContext();
549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550 if (MD->getParent()->hasAnyDependentBases())
551 return MD->getParent();
552 }
553 return nullptr;
554}
555
556ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557 SourceLocation NameLoc,
558 bool IsTemplateTypeArg) {
559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 559, __PRETTY_FUNCTION__))
;
560
561 NestedNameSpecifier *NNS = nullptr;
562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563 // If we weren't able to parse a default template argument, delay lookup
564 // until instantiation time by making a non-dependent DependentTypeName. We
565 // pretend we saw a NestedNameSpecifier referring to the current scope, and
566 // lookup is retried.
567 // FIXME: This hurts our diagnostic quality, since we get errors like "no
568 // type named 'Foo' in 'current_namespace'" when the user didn't write any
569 // name specifiers.
570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572 } else if (const CXXRecordDecl *RD =
573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574 // Build a DependentNameType that will perform lookup into RD at
575 // instantiation time.
576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577 RD->getTypeForDecl());
578
579 // Diagnose that this identifier was undeclared, and retry the lookup during
580 // template instantiation.
581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582 << RD;
583 } else {
584 // This is not a situation that we should recover from.
585 return ParsedType();
586 }
587
588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589
590 // Build type location information. We synthesized the qualifier, so we have
591 // to build a fake NestedNameSpecifierLoc.
592 NestedNameSpecifierLocBuilder NNSLocBuilder;
593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595
596 TypeLocBuilder Builder;
597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598 DepTL.setNameLoc(NameLoc);
599 DepTL.setElaboratedKeywordLoc(SourceLocation());
600 DepTL.setQualifierLoc(QualifierLoc);
601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602}
603
604/// isTagName() - This method is called *for error recovery purposes only*
605/// to determine if the specified name is a valid tag name ("struct foo"). If
606/// so, this returns the TST for the tag corresponding to it (TST_enum,
607/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
608/// cases in C where the user forgot to specify the tag.
609DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610 // Do a tag name lookup in this scope.
611 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612 LookupName(R, S, false);
613 R.suppressDiagnostics();
614 if (R.getResultKind() == LookupResult::Found)
615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616 switch (TD->getTagKind()) {
617 case TTK_Struct: return DeclSpec::TST_struct;
618 case TTK_Interface: return DeclSpec::TST_interface;
619 case TTK_Union: return DeclSpec::TST_union;
620 case TTK_Class: return DeclSpec::TST_class;
621 case TTK_Enum: return DeclSpec::TST_enum;
622 }
623 }
624
625 return DeclSpec::TST_unspecified;
626}
627
628/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629/// if a CXXScopeSpec's type is equal to the type of one of the base classes
630/// then downgrade the missing typename error to a warning.
631/// This is needed for MSVC compatibility; Example:
632/// @code
633/// template<class T> class A {
634/// public:
635/// typedef int TYPE;
636/// };
637/// template<class T> class B : public A<T> {
638/// public:
639/// A<T>::TYPE a; // no typename required because A<T> is a base class.
640/// };
641/// @endcode
642bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643 if (CurContext->isRecord()) {
644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645 return true;
646
647 const Type *Ty = SS->getScopeRep()->getAsType();
648
649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650 for (const auto &Base : RD->bases())
651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
652 return true;
653 return S->isFunctionPrototypeScope();
654 }
655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
656}
657
658void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659 SourceLocation IILoc,
660 Scope *S,
661 CXXScopeSpec *SS,
662 ParsedType &SuggestedType,
663 bool IsTemplateName) {
664 // Don't report typename errors for editor placeholders.
665 if (II->isEditorPlaceholder())
666 return;
667 // We don't have anything to suggest (yet).
668 SuggestedType = nullptr;
669
670 // There may have been a typo in the name of the type. Look up typo
671 // results, in case we have something that we can suggest.
672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673 /*AllowTemplates=*/IsTemplateName,
674 /*AllowNonTemplates=*/!IsTemplateName);
675 if (TypoCorrection Corrected =
676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677 CCC, CTK_ErrorRecovery)) {
678 // FIXME: Support error recovery for the template-name case.
679 bool CanRecover = !IsTemplateName;
680 if (Corrected.isKeyword()) {
681 // We corrected to a keyword.
682 diagnoseTypo(Corrected,
683 PDiag(IsTemplateName ? diag::err_no_template_suggest
684 : diag::err_unknown_typename_suggest)
685 << II);
686 II = Corrected.getCorrectionAsIdentifierInfo();
687 } else {
688 // We found a similarly-named type or interface; suggest that.
689 if (!SS || !SS->isSet()) {
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II, CanRecover);
694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 II->getName().equals(CorrectedStr);
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName
700 ? diag::err_no_member_template_suggest
701 : diag::err_unknown_nested_typename_suggest)
702 << II << DC << DroppedSpecifier << SS->getRange(),
703 CanRecover);
704 } else {
705 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 705)
;
706 }
707
708 if (!CanRecover)
709 return;
710
711 CXXScopeSpec tmpSS;
712 if (Corrected.getCorrectionSpecifier())
713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714 SourceRange(IILoc));
715 // FIXME: Support class template argument deduction here.
716 SuggestedType =
717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719 /*IsCtorOrDtorName=*/false,
720 /*WantNontrivialTypeSourceInfo=*/true);
721 }
722 return;
723 }
724
725 if (getLangOpts().CPlusPlus && !IsTemplateName) {
726 // See if II is a class template that the user forgot to pass arguments to.
727 UnqualifiedId Name;
728 Name.setIdentifier(II, IILoc);
729 CXXScopeSpec EmptySS;
730 TemplateTy TemplateResult;
731 bool MemberOfUnknownSpecialization;
732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733 Name, nullptr, true, TemplateResult,
734 MemberOfUnknownSpecialization) == TNK_Type_template) {
735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736 return;
737 }
738 }
739
740 // FIXME: Should we move the logic that tries to recover from a missing tag
741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742
743 if (!SS || (!SS->isSet() && !SS->isInvalid()))
744 Diag(IILoc, IsTemplateName ? diag::err_no_template
745 : diag::err_unknown_typename)
746 << II;
747 else if (DeclContext *DC = computeDeclContext(*SS, false))
748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749 : diag::err_typename_nested_not_found)
750 << II << DC << SS->getRange();
751 else if (isDependentScopeSpecifier(*SS)) {
752 unsigned DiagID = diag::err_typename_missing;
753 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
754 DiagID = diag::ext_typename_missing;
755
756 Diag(SS->getRange().getBegin(), DiagID)
757 << SS->getScopeRep() << II->getName()
758 << SourceRange(SS->getRange().getBegin(), IILoc)
759 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
760 SuggestedType = ActOnTypenameType(S, SourceLocation(),
761 *SS, *II, IILoc).get();
762 } else {
763 assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 764, __PRETTY_FUNCTION__))
764 "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 764, __PRETTY_FUNCTION__))
;
765 }
766}
767
768/// Determine whether the given result set contains either a type name
769/// or
770static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
771 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
772 NextToken.is(tok::less);
773
774 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
775 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
776 return true;
777
778 if (CheckTemplate && isa<TemplateDecl>(*I))
779 return true;
780 }
781
782 return false;
783}
784
785static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
786 Scope *S, CXXScopeSpec &SS,
787 IdentifierInfo *&Name,
788 SourceLocation NameLoc) {
789 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
790 SemaRef.LookupParsedName(R, S, &SS);
791 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
792 StringRef FixItTagName;
793 switch (Tag->getTagKind()) {
794 case TTK_Class:
795 FixItTagName = "class ";
796 break;
797
798 case TTK_Enum:
799 FixItTagName = "enum ";
800 break;
801
802 case TTK_Struct:
803 FixItTagName = "struct ";
804 break;
805
806 case TTK_Interface:
807 FixItTagName = "__interface ";
808 break;
809
810 case TTK_Union:
811 FixItTagName = "union ";
812 break;
813 }
814
815 StringRef TagName = FixItTagName.drop_back();
816 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
817 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
818 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
819
820 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
821 I != IEnd; ++I)
822 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
823 << Name << TagName;
824
825 // Replace lookup results with just the tag decl.
826 Result.clear(Sema::LookupTagName);
827 SemaRef.LookupParsedName(Result, S, &SS);
828 return true;
829 }
830
831 return false;
832}
833
834/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
835static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
836 QualType T, SourceLocation NameLoc) {
837 ASTContext &Context = S.Context;
838
839 TypeLocBuilder Builder;
840 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
841
842 T = S.getElaboratedType(ETK_None, SS, T);
843 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
844 ElabTL.setElaboratedKeywordLoc(SourceLocation());
845 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
846 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
847}
848
849Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
850 IdentifierInfo *&Name,
851 SourceLocation NameLoc,
852 const Token &NextToken,
853 CorrectionCandidateCallback *CCC) {
854 DeclarationNameInfo NameInfo(Name, NameLoc);
855 ObjCMethodDecl *CurMethod = getCurMethodDecl();
856
857 assert(NextToken.isNot(tok::coloncolon) &&((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 858, __PRETTY_FUNCTION__))
858 "parse nested name specifiers before calling ClassifyName")((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 858, __PRETTY_FUNCTION__))
;
859 if (getLangOpts().CPlusPlus && SS.isSet() &&
860 isCurrentClassName(*Name, S, &SS)) {
861 // Per [class.qual]p2, this names the constructors of SS, not the
862 // injected-class-name. We don't have a classification for that.
863 // There's not much point caching this result, since the parser
864 // will reject it later.
865 return NameClassification::Unknown();
866 }
867
868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
869 LookupParsedName(Result, S, &SS, !CurMethod);
870
871 if (SS.isInvalid())
872 return NameClassification::Error();
873
874 // For unqualified lookup in a class template in MSVC mode, look into
875 // dependent base classes where the primary class template is known.
876 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
877 if (ParsedType TypeInBase =
878 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
879 return TypeInBase;
880 }
881
882 // Perform lookup for Objective-C instance variables (including automatically
883 // synthesized instance variables), if we're in an Objective-C method.
884 // FIXME: This lookup really, really needs to be folded in to the normal
885 // unqualified lookup mechanism.
886 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
887 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
888 if (Ivar.isInvalid())
889 return NameClassification::Error();
890 if (Ivar.isUsable())
891 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
892
893 // We defer builtin creation until after ivar lookup inside ObjC methods.
894 if (Result.empty())
895 LookupBuiltin(Result);
896 }
897
898 bool SecondTry = false;
899 bool IsFilteredTemplateName = false;
900
901Corrected:
902 switch (Result.getResultKind()) {
903 case LookupResult::NotFound:
904 // If an unqualified-id is followed by a '(', then we have a function
905 // call.
906 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
907 // In C++, this is an ADL-only call.
908 // FIXME: Reference?
909 if (getLangOpts().CPlusPlus)
910 return NameClassification::UndeclaredNonType();
911
912 // C90 6.3.2.2:
913 // If the expression that precedes the parenthesized argument list in a
914 // function call consists solely of an identifier, and if no
915 // declaration is visible for this identifier, the identifier is
916 // implicitly declared exactly as if, in the innermost block containing
917 // the function call, the declaration
918 //
919 // extern int identifier ();
920 //
921 // appeared.
922 //
923 // We also allow this in C99 as an extension.
924 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
925 return NameClassification::NonType(D);
926 }
927
928 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
929 // In C++20 onwards, this could be an ADL-only call to a function
930 // template, and we're required to assume that this is a template name.
931 //
932 // FIXME: Find a way to still do typo correction in this case.
933 TemplateName Template =
934 Context.getAssumedTemplateName(NameInfo.getName());
935 return NameClassification::UndeclaredTemplate(Template);
936 }
937
938 // In C, we first see whether there is a tag type by the same name, in
939 // which case it's likely that the user just forgot to write "enum",
940 // "struct", or "union".
941 if (!getLangOpts().CPlusPlus && !SecondTry &&
942 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
943 break;
944 }
945
946 // Perform typo correction to determine if there is another name that is
947 // close to this name.
948 if (!SecondTry && CCC) {
949 SecondTry = true;
950 if (TypoCorrection Corrected =
951 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
952 &SS, *CCC, CTK_ErrorRecovery)) {
953 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
954 unsigned QualifiedDiag = diag::err_no_member_suggest;
955
956 NamedDecl *FirstDecl = Corrected.getFoundDecl();
957 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
958 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
959 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
960 UnqualifiedDiag = diag::err_no_template_suggest;
961 QualifiedDiag = diag::err_no_member_template_suggest;
962 } else if (UnderlyingFirstDecl &&
963 (isa<TypeDecl>(UnderlyingFirstDecl) ||
964 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
965 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
966 UnqualifiedDiag = diag::err_unknown_typename_suggest;
967 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
968 }
969
970 if (SS.isEmpty()) {
971 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
972 } else {// FIXME: is this even reachable? Test it.
973 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
974 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
975 Name->getName().equals(CorrectedStr);
976 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
977 << Name << computeDeclContext(SS, false)
978 << DroppedSpecifier << SS.getRange());
979 }
980
981 // Update the name, so that the caller has the new name.
982 Name = Corrected.getCorrectionAsIdentifierInfo();
983
984 // Typo correction corrected to a keyword.
985 if (Corrected.isKeyword())
986 return Name;
987
988 // Also update the LookupResult...
989 // FIXME: This should probably go away at some point
990 Result.clear();
991 Result.setLookupName(Corrected.getCorrection());
992 if (FirstDecl)
993 Result.addDecl(FirstDecl);
994
995 // If we found an Objective-C instance variable, let
996 // LookupInObjCMethod build the appropriate expression to
997 // reference the ivar.
998 // FIXME: This is a gross hack.
999 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1000 DeclResult R =
1001 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1002 if (R.isInvalid())
1003 return NameClassification::Error();
1004 if (R.isUsable())
1005 return NameClassification::NonType(Ivar);
1006 }
1007
1008 goto Corrected;
1009 }
1010 }
1011
1012 // We failed to correct; just fall through and let the parser deal with it.
1013 Result.suppressDiagnostics();
1014 return NameClassification::Unknown();
1015
1016 case LookupResult::NotFoundInCurrentInstantiation: {
1017 // We performed name lookup into the current instantiation, and there were
1018 // dependent bases, so we treat this result the same way as any other
1019 // dependent nested-name-specifier.
1020
1021 // C++ [temp.res]p2:
1022 // A name used in a template declaration or definition and that is
1023 // dependent on a template-parameter is assumed not to name a type
1024 // unless the applicable name lookup finds a type name or the name is
1025 // qualified by the keyword typename.
1026 //
1027 // FIXME: If the next token is '<', we might want to ask the parser to
1028 // perform some heroics to see if we actually have a
1029 // template-argument-list, which would indicate a missing 'template'
1030 // keyword here.
1031 return NameClassification::DependentNonType();
1032 }
1033
1034 case LookupResult::Found:
1035 case LookupResult::FoundOverloaded:
1036 case LookupResult::FoundUnresolvedValue:
1037 break;
1038
1039 case LookupResult::Ambiguous:
1040 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1041 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1042 /*AllowDependent=*/false)) {
1043 // C++ [temp.local]p3:
1044 // A lookup that finds an injected-class-name (10.2) can result in an
1045 // ambiguity in certain cases (for example, if it is found in more than
1046 // one base class). If all of the injected-class-names that are found
1047 // refer to specializations of the same class template, and if the name
1048 // is followed by a template-argument-list, the reference refers to the
1049 // class template itself and not a specialization thereof, and is not
1050 // ambiguous.
1051 //
1052 // This filtering can make an ambiguous result into an unambiguous one,
1053 // so try again after filtering out template names.
1054 FilterAcceptableTemplateNames(Result);
1055 if (!Result.isAmbiguous()) {
1056 IsFilteredTemplateName = true;
1057 break;
1058 }
1059 }
1060
1061 // Diagnose the ambiguity and return an error.
1062 return NameClassification::Error();
1063 }
1064
1065 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1066 (IsFilteredTemplateName ||
1067 hasAnyAcceptableTemplateNames(
1068 Result, /*AllowFunctionTemplates=*/true,
1069 /*AllowDependent=*/false,
1070 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1071 getLangOpts().CPlusPlus2a))) {
1072 // C++ [temp.names]p3:
1073 // After name lookup (3.4) finds that a name is a template-name or that
1074 // an operator-function-id or a literal- operator-id refers to a set of
1075 // overloaded functions any member of which is a function template if
1076 // this is followed by a <, the < is always taken as the delimiter of a
1077 // template-argument-list and never as the less-than operator.
1078 // C++2a [temp.names]p2:
1079 // A name is also considered to refer to a template if it is an
1080 // unqualified-id followed by a < and name lookup finds either one
1081 // or more functions or finds nothing.
1082 if (!IsFilteredTemplateName)
1083 FilterAcceptableTemplateNames(Result);
1084
1085 bool IsFunctionTemplate;
1086 bool IsVarTemplate;
1087 TemplateName Template;
1088 if (Result.end() - Result.begin() > 1) {
1089 IsFunctionTemplate = true;
1090 Template = Context.getOverloadedTemplateName(Result.begin(),
1091 Result.end());
1092 } else if (!Result.empty()) {
1093 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1094 *Result.begin(), /*AllowFunctionTemplates=*/true,
1095 /*AllowDependent=*/false));
1096 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1097 IsVarTemplate = isa<VarTemplateDecl>(TD);
1098
1099 if (SS.isNotEmpty())
1100 Template =
1101 Context.getQualifiedTemplateName(SS.getScopeRep(),
1102 /*TemplateKeyword=*/false, TD);
1103 else
1104 Template = TemplateName(TD);
1105 } else {
1106 // All results were non-template functions. This is a function template
1107 // name.
1108 IsFunctionTemplate = true;
1109 Template = Context.getAssumedTemplateName(NameInfo.getName());
1110 }
1111
1112 if (IsFunctionTemplate) {
1113 // Function templates always go through overload resolution, at which
1114 // point we'll perform the various checks (e.g., accessibility) we need
1115 // to based on which function we selected.
1116 Result.suppressDiagnostics();
1117
1118 return NameClassification::FunctionTemplate(Template);
1119 }
1120
1121 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1122 : NameClassification::TypeTemplate(Template);
1123 }
1124
1125 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1126 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1127 DiagnoseUseOfDecl(Type, NameLoc);
1128 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1129 QualType T = Context.getTypeDeclType(Type);
1130 if (SS.isNotEmpty())
1131 return buildNestedType(*this, SS, T, NameLoc);
1132 return ParsedType::make(T);
1133 }
1134
1135 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1136 if (!Class) {
1137 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1138 if (ObjCCompatibleAliasDecl *Alias =
1139 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1140 Class = Alias->getClassInterface();
1141 }
1142
1143 if (Class) {
1144 DiagnoseUseOfDecl(Class, NameLoc);
1145
1146 if (NextToken.is(tok::period)) {
1147 // Interface. <something> is parsed as a property reference expression.
1148 // Just return "unknown" as a fall-through for now.
1149 Result.suppressDiagnostics();
1150 return NameClassification::Unknown();
1151 }
1152
1153 QualType T = Context.getObjCInterfaceType(Class);
1154 return ParsedType::make(T);
1155 }
1156
1157 if (isa<ConceptDecl>(FirstDecl))
1158 return NameClassification::Concept(
1159 TemplateName(cast<TemplateDecl>(FirstDecl)));
1160
1161 // We can have a type template here if we're classifying a template argument.
1162 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1163 !isa<VarTemplateDecl>(FirstDecl))
1164 return NameClassification::TypeTemplate(
1165 TemplateName(cast<TemplateDecl>(FirstDecl)));
1166
1167 // Check for a tag type hidden by a non-type decl in a few cases where it
1168 // seems likely a type is wanted instead of the non-type that was found.
1169 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1170 if ((NextToken.is(tok::identifier) ||
1171 (NextIsOp &&
1172 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1173 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1174 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1175 DiagnoseUseOfDecl(Type, NameLoc);
1176 QualType T = Context.getTypeDeclType(Type);
1177 if (SS.isNotEmpty())
1178 return buildNestedType(*this, SS, T, NameLoc);
1179 return ParsedType::make(T);
1180 }
1181
1182 // FIXME: This is context-dependent. We need to defer building the member
1183 // expression until the classification is consumed.
1184 if (FirstDecl->isCXXClassMember())
1185 return NameClassification::ContextIndependentExpr(
1186 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1187 S));
1188
1189 // If we already know which single declaration is referenced, just annotate
1190 // that declaration directly.
1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192 if (Result.isSingleResult() && !ADL)
1193 return NameClassification::NonType(Result.getRepresentativeDecl());
1194
1195 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1196 // context in which we performed classification, so it's safe to do now.
1197 return NameClassification::ContextIndependentExpr(
1198 BuildDeclarationNameExpr(SS, Result, ADL));
1199}
1200
1201ExprResult
1202Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203 SourceLocation NameLoc) {
1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((getLangOpts().CPlusPlus && "ADL-only call in C?") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1204, __PRETTY_FUNCTION__))
;
1205 CXXScopeSpec SS;
1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208}
1209
1210ExprResult
1211Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212 IdentifierInfo *Name,
1213 SourceLocation NameLoc,
1214 bool IsAddressOfOperand) {
1215 DeclarationNameInfo NameInfo(Name, NameLoc);
1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217 NameInfo, IsAddressOfOperand,
1218 /*TemplateArgs=*/nullptr);
1219}
1220
1221ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222 NamedDecl *Found,
1223 SourceLocation NameLoc,
1224 const Token &NextToken) {
1225 if (getCurMethodDecl() && SS.isEmpty())
1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227 return BuildIvarRefExpr(S, NameLoc, Ivar);
1228
1229 // Reconstruct the lookup result.
1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231 Result.addDecl(Found);
1232 Result.resolveKind();
1233
1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235 return BuildDeclarationNameExpr(SS, Result, ADL);
1236}
1237
1238Sema::TemplateNameKindForDiagnostics
1239Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1240 auto *TD = Name.getAsTemplateDecl();
1241 if (!TD)
1242 return TemplateNameKindForDiagnostics::DependentTemplate;
1243 if (isa<ClassTemplateDecl>(TD))
1244 return TemplateNameKindForDiagnostics::ClassTemplate;
1245 if (isa<FunctionTemplateDecl>(TD))
1246 return TemplateNameKindForDiagnostics::FunctionTemplate;
1247 if (isa<VarTemplateDecl>(TD))
1248 return TemplateNameKindForDiagnostics::VarTemplate;
1249 if (isa<TypeAliasTemplateDecl>(TD))
1250 return TemplateNameKindForDiagnostics::AliasTemplate;
1251 if (isa<TemplateTemplateParmDecl>(TD))
1252 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1253 if (isa<ConceptDecl>(TD))
1254 return TemplateNameKindForDiagnostics::Concept;
1255 return TemplateNameKindForDiagnostics::DependentTemplate;
1256}
1257
1258// Determines the context to return to after temporarily entering a
1259// context. This depends in an unnecessarily complicated way on the
1260// exact ordering of callbacks from the parser.
1261DeclContext *Sema::getContainingDC(DeclContext *DC) {
1262
1263 // Functions defined inline within classes aren't parsed until we've
1264 // finished parsing the top-level class, so the top-level class is
1265 // the context we'll need to return to.
1266 // A Lambda call operator whose parent is a class must not be treated
1267 // as an inline member function. A Lambda can be used legally
1268 // either as an in-class member initializer or a default argument. These
1269 // are parsed once the class has been marked complete and so the containing
1270 // context would be the nested class (when the lambda is defined in one);
1271 // If the class is not complete, then the lambda is being used in an
1272 // ill-formed fashion (such as to specify the width of a bit-field, or
1273 // in an array-bound) - in which case we still want to return the
1274 // lexically containing DC (which could be a nested class).
1275 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1276 DC = DC->getLexicalParent();
1277
1278 // A function not defined within a class will always return to its
1279 // lexical context.
1280 if (!isa<CXXRecordDecl>(DC))
1281 return DC;
1282
1283 // A C++ inline method/friend is parsed *after* the topmost class
1284 // it was declared in is fully parsed ("complete"); the topmost
1285 // class is the context we need to return to.
1286 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1287 DC = RD;
1288
1289 // Return the declaration context of the topmost class the inline method is
1290 // declared in.
1291 return DC;
1292 }
1293
1294 return DC->getLexicalParent();
1295}
1296
1297void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1298 assert(getContainingDC(DC) == CurContext &&((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1299, __PRETTY_FUNCTION__))
1299 "The next DeclContext should be lexically contained in the current one.")((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1299, __PRETTY_FUNCTION__))
;
1300 CurContext = DC;
1301 S->setEntity(DC);
1302}
1303
1304void Sema::PopDeclContext() {
1305 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1305, __PRETTY_FUNCTION__))
;
1306
1307 CurContext = getContainingDC(CurContext);
1308 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1308, __PRETTY_FUNCTION__))
;
1309}
1310
1311Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1312 Decl *D) {
1313 // Unlike PushDeclContext, the context to which we return is not necessarily
1314 // the containing DC of TD, because the new context will be some pre-existing
1315 // TagDecl definition instead of a fresh one.
1316 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1317 CurContext = cast<TagDecl>(D)->getDefinition();
1318 assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag"
) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1318, __PRETTY_FUNCTION__))
;
1319 // Start lookups from the parent of the current context; we don't want to look
1320 // into the pre-existing complete definition.
1321 S->setEntity(CurContext->getLookupParent());
1322 return Result;
1323}
1324
1325void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1326 CurContext = static_cast<decltype(CurContext)>(Context);
1327}
1328
1329/// EnterDeclaratorContext - Used when we must lookup names in the context
1330/// of a declarator's nested name specifier.
1331///
1332void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1333 // C++0x [basic.lookup.unqual]p13:
1334 // A name used in the definition of a static data member of class
1335 // X (after the qualified-id of the static member) is looked up as
1336 // if the name was used in a member function of X.
1337 // C++0x [basic.lookup.unqual]p14:
1338 // If a variable member of a namespace is defined outside of the
1339 // scope of its namespace then any name used in the definition of
1340 // the variable member (after the declarator-id) is looked up as
1341 // if the definition of the variable member occurred in its
1342 // namespace.
1343 // Both of these imply that we should push a scope whose context
1344 // is the semantic context of the declaration. We can't use
1345 // PushDeclContext here because that context is not necessarily
1346 // lexically contained in the current context. Fortunately,
1347 // the containing scope should have the appropriate information.
1348
1349 assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ?
static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1349, __PRETTY_FUNCTION__))
;
1350
1351#ifndef NDEBUG
1352 Scope *Ancestor = S->getParent();
1353 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1354 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch"
) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1354, __PRETTY_FUNCTION__))
;
1355#endif
1356
1357 CurContext = DC;
1358 S->setEntity(DC);
1359}
1360
1361void Sema::ExitDeclaratorContext(Scope *S) {
1362 assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!"
) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1362, __PRETTY_FUNCTION__))
;
1363
1364 // Switch back to the lexical context. The safety of this is
1365 // enforced by an assert in EnterDeclaratorContext.
1366 Scope *Ancestor = S->getParent();
1367 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1368 CurContext = Ancestor->getEntity();
1369
1370 // We don't need to do anything with the scope, which is going to
1371 // disappear.
1372}
1373
1374void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1375 // We assume that the caller has already called
1376 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1377 FunctionDecl *FD = D->getAsFunction();
1378 if (!FD)
1379 return;
1380
1381 // Same implementation as PushDeclContext, but enters the context
1382 // from the lexical parent, rather than the top-level class.
1383 assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1384, __PRETTY_FUNCTION__))
1384 "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1384, __PRETTY_FUNCTION__))
;
1385 CurContext = FD;
1386 S->setEntity(CurContext);
1387
1388 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1389 ParmVarDecl *Param = FD->getParamDecl(P);
1390 // If the parameter has an identifier, then add it to the scope
1391 if (Param->getIdentifier()) {
1392 S->AddDecl(Param);
1393 IdResolver.AddDecl(Param);
1394 }
1395 }
1396}
1397
1398void Sema::ActOnExitFunctionContext() {
1399 // Same implementation as PopDeclContext, but returns to the lexical parent,
1400 // rather than the top-level class.
1401 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1401, __PRETTY_FUNCTION__))
;
1402 CurContext = CurContext->getLexicalParent();
1403 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1403, __PRETTY_FUNCTION__))
;
1404}
1405
1406/// Determine whether we allow overloading of the function
1407/// PrevDecl with another declaration.
1408///
1409/// This routine determines whether overloading is possible, not
1410/// whether some new function is actually an overload. It will return
1411/// true in C++ (where we can always provide overloads) or, as an
1412/// extension, in C when the previous function is already an
1413/// overloaded function declaration or has the "overloadable"
1414/// attribute.
1415static bool AllowOverloadingOfFunction(LookupResult &Previous,
1416 ASTContext &Context,
1417 const FunctionDecl *New) {
1418 if (Context.getLangOpts().CPlusPlus)
1419 return true;
1420
1421 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1422 return true;
1423
1424 return Previous.getResultKind() == LookupResult::Found &&
1425 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1426 New->hasAttr<OverloadableAttr>());
1427}
1428
1429/// Add this decl to the scope shadowed decl chains.
1430void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1431 // Move up the scope chain until we find the nearest enclosing
1432 // non-transparent context. The declaration will be introduced into this
1433 // scope.
1434 while (S->getEntity() && S->getEntity()->isTransparentContext())
1435 S = S->getParent();
1436
1437 // Add scoped declarations into their context, so that they can be
1438 // found later. Declarations without a context won't be inserted
1439 // into any context.
1440 if (AddToContext)
1441 CurContext->addDecl(D);
1442
1443 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1444 // are function-local declarations.
1445 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1446 !D->getDeclContext()->getRedeclContext()->Equals(
1447 D->getLexicalDeclContext()->getRedeclContext()) &&
1448 !D->getLexicalDeclContext()->isFunctionOrMethod())
1449 return;
1450
1451 // Template instantiations should also not be pushed into scope.
1452 if (isa<FunctionDecl>(D) &&
1453 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1454 return;
1455
1456 // If this replaces anything in the current scope,
1457 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1458 IEnd = IdResolver.end();
1459 for (; I != IEnd; ++I) {
1460 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1461 S->RemoveDecl(*I);
1462 IdResolver.RemoveDecl(*I);
1463
1464 // Should only need to replace one decl.
1465 break;
1466 }
1467 }
1468
1469 S->AddDecl(D);
1470
1471 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1472 // Implicitly-generated labels may end up getting generated in an order that
1473 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1474 // the label at the appropriate place in the identifier chain.
1475 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1476 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1477 if (IDC == CurContext) {
1478 if (!S->isDeclScope(*I))
1479 continue;
1480 } else if (IDC->Encloses(CurContext))
1481 break;
1482 }
1483
1484 IdResolver.InsertDeclAfter(I, D);
1485 } else {
1486 IdResolver.AddDecl(D);
1487 }
1488}
1489
1490bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1491 bool AllowInlineNamespace) {
1492 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1493}
1494
1495Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1496 DeclContext *TargetDC = DC->getPrimaryContext();
1497 do {
1498 if (DeclContext *ScopeDC = S->getEntity())
1499 if (ScopeDC->getPrimaryContext() == TargetDC)
1500 return S;
1501 } while ((S = S->getParent()));
1502
1503 return nullptr;
1504}
1505
1506static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1507 DeclContext*,
1508 ASTContext&);
1509
1510/// Filters out lookup results that don't fall within the given scope
1511/// as determined by isDeclInScope.
1512void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1513 bool ConsiderLinkage,
1514 bool AllowInlineNamespace) {
1515 LookupResult::Filter F = R.makeFilter();
1516 while (F.hasNext()) {
1517 NamedDecl *D = F.next();
1518
1519 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1520 continue;
1521
1522 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1523 continue;
1524
1525 F.erase();
1526 }
1527
1528 F.done();
1529}
1530
1531/// We've determined that \p New is a redeclaration of \p Old. Check that they
1532/// have compatible owning modules.
1533bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1534 // FIXME: The Modules TS is not clear about how friend declarations are
1535 // to be treated. It's not meaningful to have different owning modules for
1536 // linkage in redeclarations of the same entity, so for now allow the
1537 // redeclaration and change the owning modules to match.
1538 if (New->getFriendObjectKind() &&
1539 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1540 New->setLocalOwningModule(Old->getOwningModule());
1541 makeMergedDefinitionVisible(New);
1542 return false;
1543 }
1544
1545 Module *NewM = New->getOwningModule();
1546 Module *OldM = Old->getOwningModule();
1547
1548 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1549 NewM = NewM->Parent;
1550 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1551 OldM = OldM->Parent;
1552
1553 if (NewM == OldM)
1554 return false;
1555
1556 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1557 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1558 if (NewIsModuleInterface || OldIsModuleInterface) {
1559 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1560 // if a declaration of D [...] appears in the purview of a module, all
1561 // other such declarations shall appear in the purview of the same module
1562 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1563 << New
1564 << NewIsModuleInterface
1565 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1566 << OldIsModuleInterface
1567 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1568 Diag(Old->getLocation(), diag::note_previous_declaration);
1569 New->setInvalidDecl();
1570 return true;
1571 }
1572
1573 return false;
1574}
1575
1576static bool isUsingDecl(NamedDecl *D) {
1577 return isa<UsingShadowDecl>(D) ||
1578 isa<UnresolvedUsingTypenameDecl>(D) ||
1579 isa<UnresolvedUsingValueDecl>(D);
1580}
1581
1582/// Removes using shadow declarations from the lookup results.
1583static void RemoveUsingDecls(LookupResult &R) {
1584 LookupResult::Filter F = R.makeFilter();
1585 while (F.hasNext())
1586 if (isUsingDecl(F.next()))
1587 F.erase();
1588
1589 F.done();
1590}
1591
1592/// Check for this common pattern:
1593/// @code
1594/// class S {
1595/// S(const S&); // DO NOT IMPLEMENT
1596/// void operator=(const S&); // DO NOT IMPLEMENT
1597/// };
1598/// @endcode
1599static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1600 // FIXME: Should check for private access too but access is set after we get
1601 // the decl here.
1602 if (D->doesThisDeclarationHaveABody())
1603 return false;
1604
1605 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1606 return CD->isCopyConstructor();
1607 return D->isCopyAssignmentOperator();
1608}
1609
1610// We need this to handle
1611//
1612// typedef struct {
1613// void *foo() { return 0; }
1614// } A;
1615//
1616// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1617// for example. If 'A', foo will have external linkage. If we have '*A',
1618// foo will have no linkage. Since we can't know until we get to the end
1619// of the typedef, this function finds out if D might have non-external linkage.
1620// Callers should verify at the end of the TU if it D has external linkage or
1621// not.
1622bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1623 const DeclContext *DC = D->getDeclContext();
1624 while (!DC->isTranslationUnit()) {
1625 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1626 if (!RD->hasNameForLinkage())
1627 return true;
1628 }
1629 DC = DC->getParent();
1630 }
1631
1632 return !D->isExternallyVisible();
1633}
1634
1635// FIXME: This needs to be refactored; some other isInMainFile users want
1636// these semantics.
1637static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1638 if (S.TUKind != TU_Complete)
1639 return false;
1640 return S.SourceMgr.isInMainFile(Loc);
1641}
1642
1643bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1644 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1644, __PRETTY_FUNCTION__))
;
1645
1646 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1647 return false;
1648
1649 // Ignore all entities declared within templates, and out-of-line definitions
1650 // of members of class templates.
1651 if (D->getDeclContext()->isDependentContext() ||
1652 D->getLexicalDeclContext()->isDependentContext())
1653 return false;
1654
1655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1656 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1657 return false;
1658 // A non-out-of-line declaration of a member specialization was implicitly
1659 // instantiated; it's the out-of-line declaration that we're interested in.
1660 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1661 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1662 return false;
1663
1664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1665 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1666 return false;
1667 } else {
1668 // 'static inline' functions are defined in headers; don't warn.
1669 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1670 return false;
1671 }
1672
1673 if (FD->doesThisDeclarationHaveABody() &&
1674 Context.DeclMustBeEmitted(FD))
1675 return false;
1676 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1677 // Constants and utility variables are defined in headers with internal
1678 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1679 // like "inline".)
1680 if (!isMainFileLoc(*this, VD->getLocation()))
1681 return false;
1682
1683 if (Context.DeclMustBeEmitted(VD))
1684 return false;
1685
1686 if (VD->isStaticDataMember() &&
1687 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688 return false;
1689 if (VD->isStaticDataMember() &&
1690 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1691 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1692 return false;
1693
1694 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1695 return false;
1696 } else {
1697 return false;
1698 }
1699
1700 // Only warn for unused decls internal to the translation unit.
1701 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1702 // for inline functions defined in the main source file, for instance.
1703 return mightHaveNonExternalLinkage(D);
1704}
1705
1706void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1707 if (!D)
1708 return;
1709
1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1711 const FunctionDecl *First = FD->getFirstDecl();
1712 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1713 return; // First should already be in the vector.
1714 }
1715
1716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1717 const VarDecl *First = VD->getFirstDecl();
1718 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1719 return; // First should already be in the vector.
1720 }
1721
1722 if (ShouldWarnIfUnusedFileScopedDecl(D))
1723 UnusedFileScopedDecls.push_back(D);
1724}
1725
1726static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1727 if (D->isInvalidDecl())
1728 return false;
1729
1730 bool Referenced = false;
1731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1732 // For a decomposition declaration, warn if none of the bindings are
1733 // referenced, instead of if the variable itself is referenced (which
1734 // it is, by the bindings' expressions).
1735 for (auto *BD : DD->bindings()) {
1736 if (BD->isReferenced()) {
1737 Referenced = true;
1738 break;
1739 }
1740 }
1741 } else if (!D->getDeclName()) {
1742 return false;
1743 } else if (D->isReferenced() || D->isUsed()) {
1744 Referenced = true;
1745 }
1746
1747 if (Referenced || D->hasAttr<UnusedAttr>() ||
1748 D->hasAttr<ObjCPreciseLifetimeAttr>())
1749 return false;
1750
1751 if (isa<LabelDecl>(D))
1752 return true;
1753
1754 // Except for labels, we only care about unused decls that are local to
1755 // functions.
1756 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1757 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1758 // For dependent types, the diagnostic is deferred.
1759 WithinFunction =
1760 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1761 if (!WithinFunction)
1762 return false;
1763
1764 if (isa<TypedefNameDecl>(D))
1765 return true;
1766
1767 // White-list anything that isn't a local variable.
1768 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1769 return false;
1770
1771 // Types of valid local variables should be complete, so this should succeed.
1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1773
1774 // White-list anything with an __attribute__((unused)) type.
1775 const auto *Ty = VD->getType().getTypePtr();
1776
1777 // Only look at the outermost level of typedef.
1778 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1779 if (TT->getDecl()->hasAttr<UnusedAttr>())
1780 return false;
1781 }
1782
1783 // If we failed to complete the type for some reason, or if the type is
1784 // dependent, don't diagnose the variable.
1785 if (Ty->isIncompleteType() || Ty->isDependentType())
1786 return false;
1787
1788 // Look at the element type to ensure that the warning behaviour is
1789 // consistent for both scalars and arrays.
1790 Ty = Ty->getBaseElementTypeUnsafe();
1791
1792 if (const TagType *TT = Ty->getAs<TagType>()) {
1793 const TagDecl *Tag = TT->getDecl();
1794 if (Tag->hasAttr<UnusedAttr>())
1795 return false;
1796
1797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1798 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1799 return false;
1800
1801 if (const Expr *Init = VD->getInit()) {
1802 if (const ExprWithCleanups *Cleanups =
1803 dyn_cast<ExprWithCleanups>(Init))
1804 Init = Cleanups->getSubExpr();
1805 const CXXConstructExpr *Construct =
1806 dyn_cast<CXXConstructExpr>(Init);
1807 if (Construct && !Construct->isElidable()) {
1808 CXXConstructorDecl *CD = Construct->getConstructor();
1809 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1810 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1811 return false;
1812 }
1813
1814 // Suppress the warning if we don't know how this is constructed, and
1815 // it could possibly be non-trivial constructor.
1816 if (Init->isTypeDependent())
1817 for (const CXXConstructorDecl *Ctor : RD->ctors())
1818 if (!Ctor->isTrivial())
1819 return false;
1820 }
1821 }
1822 }
1823
1824 // TODO: __attribute__((unused)) templates?
1825 }
1826
1827 return true;
1828}
1829
1830static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1831 FixItHint &Hint) {
1832 if (isa<LabelDecl>(D)) {
1833 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1834 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1835 true);
1836 if (AfterColon.isInvalid())
1837 return;
1838 Hint = FixItHint::CreateRemoval(
1839 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1840 }
1841}
1842
1843void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1844 if (D->getTypeForDecl()->isDependentType())
1845 return;
1846
1847 for (auto *TmpD : D->decls()) {
1848 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1849 DiagnoseUnusedDecl(T);
1850 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1851 DiagnoseUnusedNestedTypedefs(R);
1852 }
1853}
1854
1855/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1856/// unless they are marked attr(unused).
1857void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1858 if (!ShouldDiagnoseUnusedDecl(D))
1859 return;
1860
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1862 // typedefs can be referenced later on, so the diagnostics are emitted
1863 // at end-of-translation-unit.
1864 UnusedLocalTypedefNameCandidates.insert(TD);
1865 return;
1866 }
1867
1868 FixItHint Hint;
1869 GenerateFixForUnusedDecl(D, Context, Hint);
1870
1871 unsigned DiagID;
1872 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1873 DiagID = diag::warn_unused_exception_param;
1874 else if (isa<LabelDecl>(D))
1875 DiagID = diag::warn_unused_label;
1876 else
1877 DiagID = diag::warn_unused_variable;
1878
1879 Diag(D->getLocation(), DiagID) << D << Hint;
1880}
1881
1882static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1883 // Verify that we have no forward references left. If so, there was a goto
1884 // or address of a label taken, but no definition of it. Label fwd
1885 // definitions are indicated with a null substmt which is also not a resolved
1886 // MS inline assembly label name.
1887 bool Diagnose = false;
1888 if (L->isMSAsmLabel())
1889 Diagnose = !L->isResolvedMSAsmLabel();
1890 else
1891 Diagnose = L->getStmt() == nullptr;
1892 if (Diagnose)
1893 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1894}
1895
1896void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1897 S->mergeNRVOIntoParent();
1898
1899 if (S->decl_empty()) return;
1900 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1901, __PRETTY_FUNCTION__))
1901 "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1901, __PRETTY_FUNCTION__))
;
1902
1903 for (auto *TmpD : S->decls()) {
1904 assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast
<void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1904, __PRETTY_FUNCTION__))
;
1905
1906 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"
) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 1906, __PRETTY_FUNCTION__))
;
1907 NamedDecl *D = cast<NamedDecl>(TmpD);
1908
1909 // Diagnose unused variables in this scope.
1910 if (!S->hasUnrecoverableErrorOccurred()) {
1911 DiagnoseUnusedDecl(D);
1912 if (const auto *RD = dyn_cast<RecordDecl>(D))
1913 DiagnoseUnusedNestedTypedefs(RD);
1914 }
1915
1916 if (!D->getDeclName()) continue;
1917
1918 // If this was a forward reference to a label, verify it was defined.
1919 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1920 CheckPoppedLabel(LD, *this);
1921
1922 // Remove this name from our lexical scope, and warn on it if we haven't
1923 // already.
1924 IdResolver.RemoveDecl(D);
1925 auto ShadowI = ShadowingDecls.find(D);
1926 if (ShadowI != ShadowingDecls.end()) {
1927 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1928 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1929 << D << FD << FD->getParent();
1930 Diag(FD->getLocation(), diag::note_previous_declaration);
1931 }
1932 ShadowingDecls.erase(ShadowI);
1933 }
1934 }
1935}
1936
1937/// Look for an Objective-C class in the translation unit.
1938///
1939/// \param Id The name of the Objective-C class we're looking for. If
1940/// typo-correction fixes this name, the Id will be updated
1941/// to the fixed name.
1942///
1943/// \param IdLoc The location of the name in the translation unit.
1944///
1945/// \param DoTypoCorrection If true, this routine will attempt typo correction
1946/// if there is no class with the given name.
1947///
1948/// \returns The declaration of the named Objective-C class, or NULL if the
1949/// class could not be found.
1950ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1951 SourceLocation IdLoc,
1952 bool DoTypoCorrection) {
1953 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1954 // creation from this context.
1955 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1956
1957 if (!IDecl && DoTypoCorrection) {
1958 // Perform typo correction at the given location, but only if we
1959 // find an Objective-C class name.
1960 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1961 if (TypoCorrection C =
1962 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1963 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1964 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1965 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1966 Id = IDecl->getIdentifier();
1967 }
1968 }
1969 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1970 // This routine must always return a class definition, if any.
1971 if (Def && Def->getDefinition())
1972 Def = Def->getDefinition();
1973 return Def;
1974}
1975
1976/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1977/// from S, where a non-field would be declared. This routine copes
1978/// with the difference between C and C++ scoping rules in structs and
1979/// unions. For example, the following code is well-formed in C but
1980/// ill-formed in C++:
1981/// @code
1982/// struct S6 {
1983/// enum { BAR } e;
1984/// };
1985///
1986/// void test_S6() {
1987/// struct S6 a;
1988/// a.e = BAR;
1989/// }
1990/// @endcode
1991/// For the declaration of BAR, this routine will return a different
1992/// scope. The scope S will be the scope of the unnamed enumeration
1993/// within S6. In C++, this routine will return the scope associated
1994/// with S6, because the enumeration's scope is a transparent
1995/// context but structures can contain non-field names. In C, this
1996/// routine will return the translation unit scope, since the
1997/// enumeration's scope is a transparent context and structures cannot
1998/// contain non-field names.
1999Scope *Sema::getNonFieldDeclScope(Scope *S) {
2000 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2001 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2002 (S->isClassScope() && !getLangOpts().CPlusPlus))
2003 S = S->getParent();
2004 return S;
2005}
2006
2007/// Looks up the declaration of "struct objc_super" and
2008/// saves it for later use in building builtin declaration of
2009/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2010/// pre-existing declaration exists no action takes place.
2011static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2012 IdentifierInfo *II) {
2013 if (!II->isStr("objc_msgSendSuper"))
2014 return;
2015 ASTContext &Context = ThisSema.Context;
2016
2017 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2018 SourceLocation(), Sema::LookupTagName);
2019 ThisSema.LookupName(Result, S);
2020 if (Result.getResultKind() == LookupResult::Found)
2021 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2022 Context.setObjCSuperType(Context.getTagDeclType(TD));
2023}
2024
2025static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2026 ASTContext::GetBuiltinTypeError Error) {
2027 switch (Error) {
2028 case ASTContext::GE_None:
2029 return "";
2030 case ASTContext::GE_Missing_type:
2031 return BuiltinInfo.getHeaderName(ID);
2032 case ASTContext::GE_Missing_stdio:
2033 return "stdio.h";
2034 case ASTContext::GE_Missing_setjmp:
2035 return "setjmp.h";
2036 case ASTContext::GE_Missing_ucontext:
2037 return "ucontext.h";
2038 }
2039 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 2039)
;
2040}
2041
2042/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2043/// file scope. lazily create a decl for it. ForRedeclaration is true
2044/// if we're creating this built-in in anticipation of redeclaring the
2045/// built-in.
2046NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2047 Scope *S, bool ForRedeclaration,
2048 SourceLocation Loc) {
2049 LookupPredefedObjCSuperType(*this, S, II);
2050
2051 ASTContext::GetBuiltinTypeError Error;
2052 QualType R = Context.GetBuiltinType(ID, Error);
2053 if (Error) {
2054 if (!ForRedeclaration)
2055 return nullptr;
2056
2057 // If we have a builtin without an associated type we should not emit a
2058 // warning when we were not able to find a type for it.
2059 if (Error == ASTContext::GE_Missing_type)
2060 return nullptr;
2061
2062 // If we could not find a type for setjmp it is because the jmp_buf type was
2063 // not defined prior to the setjmp declaration.
2064 if (Error == ASTContext::GE_Missing_setjmp) {
2065 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2066 << Context.BuiltinInfo.getName(ID);
2067 return nullptr;
2068 }
2069
2070 // Generally, we emit a warning that the declaration requires the
2071 // appropriate header.
2072 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2073 << getHeaderName(Context.BuiltinInfo, ID, Error)
2074 << Context.BuiltinInfo.getName(ID);
2075 return nullptr;
2076 }
2077
2078 if (!ForRedeclaration &&
2079 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2080 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2081 Diag(Loc, diag::ext_implicit_lib_function_decl)
2082 << Context.BuiltinInfo.getName(ID) << R;
2083 if (Context.BuiltinInfo.getHeaderName(ID) &&
2084 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2085 Diag(Loc, diag::note_include_header_or_declare)
2086 << Context.BuiltinInfo.getHeaderName(ID)
2087 << Context.BuiltinInfo.getName(ID);
2088 }
2089
2090 if (R.isNull())
2091 return nullptr;
2092
2093 DeclContext *Parent = Context.getTranslationUnitDecl();
2094 if (getLangOpts().CPlusPlus) {
2095 LinkageSpecDecl *CLinkageDecl =
2096 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2097 LinkageSpecDecl::lang_c, false);
2098 CLinkageDecl->setImplicit();
2099 Parent->addDecl(CLinkageDecl);
2100 Parent = CLinkageDecl;
2101 }
2102
2103 FunctionDecl *New = FunctionDecl::Create(Context,
2104 Parent,
2105 Loc, Loc, II, R, /*TInfo=*/nullptr,
2106 SC_Extern,
2107 false,
2108 R->isFunctionProtoType());
2109 New->setImplicit();
2110
2111 // Create Decl objects for each parameter, adding them to the
2112 // FunctionDecl.
2113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2114 SmallVector<ParmVarDecl*, 16> Params;
2115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2116 ParmVarDecl *parm =
2117 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2118 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2119 SC_None, nullptr);
2120 parm->setScopeInfo(0, i);
2121 Params.push_back(parm);
2122 }
2123 New->setParams(Params);
2124 }
2125
2126 AddKnownFunctionAttributes(New);
2127 RegisterLocallyScopedExternCDecl(New, S);
2128
2129 // TUScope is the translation-unit scope to insert this function into.
2130 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2131 // relate Scopes to DeclContexts, and probably eliminate CurContext
2132 // entirely, but we're not there yet.
2133 DeclContext *SavedContext = CurContext;
2134 CurContext = Parent;
2135 PushOnScopeChains(New, TUScope);
2136 CurContext = SavedContext;
2137 return New;
2138}
2139
2140/// Typedef declarations don't have linkage, but they still denote the same
2141/// entity if their types are the same.
2142/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2143/// isSameEntity.
2144static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2145 TypedefNameDecl *Decl,
2146 LookupResult &Previous) {
2147 // This is only interesting when modules are enabled.
2148 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2149 return;
2150
2151 // Empty sets are uninteresting.
2152 if (Previous.empty())
2153 return;
2154
2155 LookupResult::Filter Filter = Previous.makeFilter();
2156 while (Filter.hasNext()) {
2157 NamedDecl *Old = Filter.next();
2158
2159 // Non-hidden declarations are never ignored.
2160 if (S.isVisible(Old))
2161 continue;
2162
2163 // Declarations of the same entity are not ignored, even if they have
2164 // different linkages.
2165 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2166 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2167 Decl->getUnderlyingType()))
2168 continue;
2169
2170 // If both declarations give a tag declaration a typedef name for linkage
2171 // purposes, then they declare the same entity.
2172 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2173 Decl->getAnonDeclWithTypedefName())
2174 continue;
2175 }
2176
2177 Filter.erase();
2178 }
2179
2180 Filter.done();
2181}
2182
2183bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2184 QualType OldType;
2185 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2186 OldType = OldTypedef->getUnderlyingType();
2187 else
2188 OldType = Context.getTypeDeclType(Old);
2189 QualType NewType = New->getUnderlyingType();
2190
2191 if (NewType->isVariablyModifiedType()) {
2192 // Must not redefine a typedef with a variably-modified type.
2193 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2194 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2195 << Kind << NewType;
2196 if (Old->getLocation().isValid())
2197 notePreviousDefinition(Old, New->getLocation());
2198 New->setInvalidDecl();
2199 return true;
2200 }
2201
2202 if (OldType != NewType &&
2203 !OldType->isDependentType() &&
2204 !NewType->isDependentType() &&
2205 !Context.hasSameType(OldType, NewType)) {
2206 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2207 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2208 << Kind << NewType << OldType;
2209 if (Old->getLocation().isValid())
2210 notePreviousDefinition(Old, New->getLocation());
2211 New->setInvalidDecl();
2212 return true;
2213 }
2214 return false;
2215}
2216
2217/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2218/// same name and scope as a previous declaration 'Old'. Figure out
2219/// how to resolve this situation, merging decls or emitting
2220/// diagnostics as appropriate. If there was an error, set New to be invalid.
2221///
2222void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2223 LookupResult &OldDecls) {
2224 // If the new decl is known invalid already, don't bother doing any
2225 // merging checks.
2226 if (New->isInvalidDecl()) return;
2227
2228 // Allow multiple definitions for ObjC built-in typedefs.
2229 // FIXME: Verify the underlying types are equivalent!
2230 if (getLangOpts().ObjC) {
2231 const IdentifierInfo *TypeID = New->getIdentifier();
2232 switch (TypeID->getLength()) {
2233 default: break;
2234 case 2:
2235 {
2236 if (!TypeID->isStr("id"))
2237 break;
2238 QualType T = New->getUnderlyingType();
2239 if (!T->isPointerType())
2240 break;
2241 if (!T->isVoidPointerType()) {
2242 QualType PT = T->castAs<PointerType>()->getPointeeType();
2243 if (!PT->isStructureType())
2244 break;
2245 }
2246 Context.setObjCIdRedefinitionType(T);
2247 // Install the built-in type for 'id', ignoring the current definition.
2248 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2249 return;
2250 }
2251 case 5:
2252 if (!TypeID->isStr("Class"))
2253 break;
2254 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2255 // Install the built-in type for 'Class', ignoring the current definition.
2256 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2257 return;
2258 case 3:
2259 if (!TypeID->isStr("SEL"))
2260 break;
2261 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2262 // Install the built-in type for 'SEL', ignoring the current definition.
2263 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2264 return;
2265 }
2266 // Fall through - the typedef name was not a builtin type.
2267 }
2268
2269 // Verify the old decl was also a type.
2270 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2271 if (!Old) {
2272 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2273 << New->getDeclName();
2274
2275 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2276 if (OldD->getLocation().isValid())
2277 notePreviousDefinition(OldD, New->getLocation());
2278
2279 return New->setInvalidDecl();
2280 }
2281
2282 // If the old declaration is invalid, just give up here.
2283 if (Old->isInvalidDecl())
2284 return New->setInvalidDecl();
2285
2286 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2287 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2288 auto *NewTag = New->getAnonDeclWithTypedefName();
2289 NamedDecl *Hidden = nullptr;
2290 if (OldTag && NewTag &&
2291 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2292 !hasVisibleDefinition(OldTag, &Hidden)) {
2293 // There is a definition of this tag, but it is not visible. Use it
2294 // instead of our tag.
2295 New->setTypeForDecl(OldTD->getTypeForDecl());
2296 if (OldTD->isModed())
2297 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2298 OldTD->getUnderlyingType());
2299 else
2300 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2301
2302 // Make the old tag definition visible.
2303 makeMergedDefinitionVisible(Hidden);
2304
2305 // If this was an unscoped enumeration, yank all of its enumerators
2306 // out of the scope.
2307 if (isa<EnumDecl>(NewTag)) {
2308 Scope *EnumScope = getNonFieldDeclScope(S);
2309 for (auto *D : NewTag->decls()) {
2310 auto *ED = cast<EnumConstantDecl>(D);
2311 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 2311, __PRETTY_FUNCTION__))
;
2312 EnumScope->RemoveDecl(ED);
2313 IdResolver.RemoveDecl(ED);
2314 ED->getLexicalDeclContext()->removeDecl(ED);
2315 }
2316 }
2317 }
2318 }
2319
2320 // If the typedef types are not identical, reject them in all languages and
2321 // with any extensions enabled.
2322 if (isIncompatibleTypedef(Old, New))
2323 return;
2324
2325 // The types match. Link up the redeclaration chain and merge attributes if
2326 // the old declaration was a typedef.
2327 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2328 New->setPreviousDecl(Typedef);
2329 mergeDeclAttributes(New, Old);
2330 }
2331
2332 if (getLangOpts().MicrosoftExt)
2333 return;
2334
2335 if (getLangOpts().CPlusPlus) {
2336 // C++ [dcl.typedef]p2:
2337 // In a given non-class scope, a typedef specifier can be used to
2338 // redefine the name of any type declared in that scope to refer
2339 // to the type to which it already refers.
2340 if (!isa<CXXRecordDecl>(CurContext))
2341 return;
2342
2343 // C++0x [dcl.typedef]p4:
2344 // In a given class scope, a typedef specifier can be used to redefine
2345 // any class-name declared in that scope that is not also a typedef-name
2346 // to refer to the type to which it already refers.
2347 //
2348 // This wording came in via DR424, which was a correction to the
2349 // wording in DR56, which accidentally banned code like:
2350 //
2351 // struct S {
2352 // typedef struct A { } A;
2353 // };
2354 //
2355 // in the C++03 standard. We implement the C++0x semantics, which
2356 // allow the above but disallow
2357 //
2358 // struct S {
2359 // typedef int I;
2360 // typedef int I;
2361 // };
2362 //
2363 // since that was the intent of DR56.
2364 if (!isa<TypedefNameDecl>(Old))
2365 return;
2366
2367 Diag(New->getLocation(), diag::err_redefinition)
2368 << New->getDeclName();
2369 notePreviousDefinition(Old, New->getLocation());
2370 return New->setInvalidDecl();
2371 }
2372
2373 // Modules always permit redefinition of typedefs, as does C11.
2374 if (getLangOpts().Modules || getLangOpts().C11)
2375 return;
2376
2377 // If we have a redefinition of a typedef in C, emit a warning. This warning
2378 // is normally mapped to an error, but can be controlled with
2379 // -Wtypedef-redefinition. If either the original or the redefinition is
2380 // in a system header, don't emit this for compatibility with GCC.
2381 if (getDiagnostics().getSuppressSystemWarnings() &&
2382 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2383 (Old->isImplicit() ||
2384 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2385 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2386 return;
2387
2388 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2389 << New->getDeclName();
2390 notePreviousDefinition(Old, New->getLocation());
2391}
2392
2393/// DeclhasAttr - returns true if decl Declaration already has the target
2394/// attribute.
2395static bool DeclHasAttr(const Decl *D, const Attr *A) {
2396 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2397 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2398 for (const auto *i : D->attrs())
2399 if (i->getKind() == A->getKind()) {
2400 if (Ann) {
2401 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2402 return true;
2403 continue;
2404 }
2405 // FIXME: Don't hardcode this check
2406 if (OA && isa<OwnershipAttr>(i))
2407 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2408 return true;
2409 }
2410
2411 return false;
2412}
2413
2414static bool isAttributeTargetADefinition(Decl *D) {
2415 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2416 return VD->isThisDeclarationADefinition();
2417 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2418 return TD->isCompleteDefinition() || TD->isBeingDefined();
2419 return true;
2420}
2421
2422/// Merge alignment attributes from \p Old to \p New, taking into account the
2423/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2424///
2425/// \return \c true if any attributes were added to \p New.
2426static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2427 // Look for alignas attributes on Old, and pick out whichever attribute
2428 // specifies the strictest alignment requirement.
2429 AlignedAttr *OldAlignasAttr = nullptr;
2430 AlignedAttr *OldStrictestAlignAttr = nullptr;
2431 unsigned OldAlign = 0;
2432 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2433 // FIXME: We have no way of representing inherited dependent alignments
2434 // in a case like:
2435 // template<int A, int B> struct alignas(A) X;
2436 // template<int A, int B> struct alignas(B) X {};
2437 // For now, we just ignore any alignas attributes which are not on the
2438 // definition in such a case.
2439 if (I->isAlignmentDependent())
2440 return false;
2441
2442 if (I->isAlignas())
2443 OldAlignasAttr = I;
2444
2445 unsigned Align = I->getAlignment(S.Context);
2446 if (Align > OldAlign) {
2447 OldAlign = Align;
2448 OldStrictestAlignAttr = I;
2449 }
2450 }
2451
2452 // Look for alignas attributes on New.
2453 AlignedAttr *NewAlignasAttr = nullptr;
2454 unsigned NewAlign = 0;
2455 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2456 if (I->isAlignmentDependent())
2457 return false;
2458
2459 if (I->isAlignas())
2460 NewAlignasAttr = I;
2461
2462 unsigned Align = I->getAlignment(S.Context);
2463 if (Align > NewAlign)
2464 NewAlign = Align;
2465 }
2466
2467 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2468 // Both declarations have 'alignas' attributes. We require them to match.
2469 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2470 // fall short. (If two declarations both have alignas, they must both match
2471 // every definition, and so must match each other if there is a definition.)
2472
2473 // If either declaration only contains 'alignas(0)' specifiers, then it
2474 // specifies the natural alignment for the type.
2475 if (OldAlign == 0 || NewAlign == 0) {
2476 QualType Ty;
2477 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2478 Ty = VD->getType();
2479 else
2480 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2481
2482 if (OldAlign == 0)
2483 OldAlign = S.Context.getTypeAlign(Ty);
2484 if (NewAlign == 0)
2485 NewAlign = S.Context.getTypeAlign(Ty);
2486 }
2487
2488 if (OldAlign != NewAlign) {
2489 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2490 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2491 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2493 }
2494 }
2495
2496 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2497 // C++11 [dcl.align]p6:
2498 // if any declaration of an entity has an alignment-specifier,
2499 // every defining declaration of that entity shall specify an
2500 // equivalent alignment.
2501 // C11 6.7.5/7:
2502 // If the definition of an object does not have an alignment
2503 // specifier, any other declaration of that object shall also
2504 // have no alignment specifier.
2505 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2506 << OldAlignasAttr;
2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2508 << OldAlignasAttr;
2509 }
2510
2511 bool AnyAdded = false;
2512
2513 // Ensure we have an attribute representing the strictest alignment.
2514 if (OldAlign > NewAlign) {
2515 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2516 Clone->setInherited(true);
2517 New->addAttr(Clone);
2518 AnyAdded = true;
2519 }
2520
2521 // Ensure we have an alignas attribute if the old declaration had one.
2522 if (OldAlignasAttr && !NewAlignasAttr &&
2523 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2524 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2525 Clone->setInherited(true);
2526 New->addAttr(Clone);
2527 AnyAdded = true;
2528 }
2529
2530 return AnyAdded;
2531}
2532
2533static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2534 const InheritableAttr *Attr,
2535 Sema::AvailabilityMergeKind AMK) {
2536 // This function copies an attribute Attr from a previous declaration to the
2537 // new declaration D if the new declaration doesn't itself have that attribute
2538 // yet or if that attribute allows duplicates.
2539 // If you're adding a new attribute that requires logic different from
2540 // "use explicit attribute on decl if present, else use attribute from
2541 // previous decl", for example if the attribute needs to be consistent
2542 // between redeclarations, you need to call a custom merge function here.
2543 InheritableAttr *NewAttr = nullptr;
2544 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2545 NewAttr = S.mergeAvailabilityAttr(
2546 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2547 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2548 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2549 AA->getPriority());
2550 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2551 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2552 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2553 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2554 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2555 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2556 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2557 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2558 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2559 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2560 FA->getFirstArg());
2561 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2562 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2563 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2564 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2565 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2566 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2567 IA->getInheritanceModel());
2568 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2569 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2570 &S.Context.Idents.get(AA->getSpelling()));
2571 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2572 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2573 isa<CUDAGlobalAttr>(Attr))) {
2574 // CUDA target attributes are part of function signature for
2575 // overloading purposes and must not be merged.
2576 return false;
2577 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2578 NewAttr = S.mergeMinSizeAttr(D, *MA);
2579 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2580 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2581 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2582 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2583 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2584 NewAttr = S.mergeCommonAttr(D, *CommonA);
2585 else if (isa<AlignedAttr>(Attr))
2586 // AlignedAttrs are handled separately, because we need to handle all
2587 // such attributes on a declaration at the same time.
2588 NewAttr = nullptr;
2589 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2590 (AMK == Sema::AMK_Override ||
2591 AMK == Sema::AMK_ProtocolImplementation))
2592 NewAttr = nullptr;
2593 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2594 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2595 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2596 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2597 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2598 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2599 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2600 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2601
2602 if (NewAttr) {
2603 NewAttr->setInherited(true);
2604 D->addAttr(NewAttr);
2605 if (isa<MSInheritanceAttr>(NewAttr))
2606 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2607 return true;
2608 }
2609
2610 return false;
2611}
2612
2613static const NamedDecl *getDefinition(const Decl *D) {
2614 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2615 return TD->getDefinition();
2616 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2617 const VarDecl *Def = VD->getDefinition();
2618 if (Def)
2619 return Def;
2620 return VD->getActingDefinition();
2621 }
2622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2623 return FD->getDefinition();
2624 return nullptr;
2625}
2626
2627static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2628 for (const auto *Attribute : D->attrs())
2629 if (Attribute->getKind() == Kind)
2630 return true;
2631 return false;
2632}
2633
2634/// checkNewAttributesAfterDef - If we already have a definition, check that
2635/// there are no new attributes in this declaration.
2636static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2637 if (!New->hasAttrs())
2638 return;
2639
2640 const NamedDecl *Def = getDefinition(Old);
2641 if (!Def || Def == New)
2642 return;
2643
2644 AttrVec &NewAttributes = New->getAttrs();
2645 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2646 const Attr *NewAttribute = NewAttributes[I];
2647
2648 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2650 Sema::SkipBodyInfo SkipBody;
2651 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2652
2653 // If we're skipping this definition, drop the "alias" attribute.
2654 if (SkipBody.ShouldSkip) {
2655 NewAttributes.erase(NewAttributes.begin() + I);
2656 --E;
2657 continue;
2658 }
2659 } else {
2660 VarDecl *VD = cast<VarDecl>(New);
2661 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2662 VarDecl::TentativeDefinition
2663 ? diag::err_alias_after_tentative
2664 : diag::err_redefinition;
2665 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2666 if (Diag == diag::err_redefinition)
2667 S.notePreviousDefinition(Def, VD->getLocation());
2668 else
2669 S.Diag(Def->getLocation(), diag::note_previous_definition);
2670 VD->setInvalidDecl();
2671 }
2672 ++I;
2673 continue;
2674 }
2675
2676 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2677 // Tentative definitions are only interesting for the alias check above.
2678 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2679 ++I;
2680 continue;
2681 }
2682 }
2683
2684 if (hasAttribute(Def, NewAttribute->getKind())) {
2685 ++I;
2686 continue; // regular attr merging will take care of validating this.
2687 }
2688
2689 if (isa<C11NoReturnAttr>(NewAttribute)) {
2690 // C's _Noreturn is allowed to be added to a function after it is defined.
2691 ++I;
2692 continue;
2693 } else if (isa<UuidAttr>(NewAttribute)) {
2694 // msvc will allow a subsequent definition to add an uuid to a class
2695 ++I;
2696 continue;
2697 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2698 if (AA->isAlignas()) {
2699 // C++11 [dcl.align]p6:
2700 // if any declaration of an entity has an alignment-specifier,
2701 // every defining declaration of that entity shall specify an
2702 // equivalent alignment.
2703 // C11 6.7.5/7:
2704 // If the definition of an object does not have an alignment
2705 // specifier, any other declaration of that object shall also
2706 // have no alignment specifier.
2707 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2708 << AA;
2709 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2710 << AA;
2711 NewAttributes.erase(NewAttributes.begin() + I);
2712 --E;
2713 continue;
2714 }
2715 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2716 cast<VarDecl>(New)->isInline() &&
2717 !cast<VarDecl>(New)->isInlineSpecified()) {
2718 // Don't warn about applying selectany to implicitly inline variables.
2719 // Older compilers and language modes would require the use of selectany
2720 // to make such variables inline, and it would have no effect if we
2721 // honored it.
2722 ++I;
2723 continue;
2724 }
2725
2726 S.Diag(NewAttribute->getLocation(),
2727 diag::warn_attribute_precede_definition);
2728 S.Diag(Def->getLocation(), diag::note_previous_definition);
2729 NewAttributes.erase(NewAttributes.begin() + I);
2730 --E;
2731 }
2732}
2733
2734static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2735 const ConstInitAttr *CIAttr,
2736 bool AttrBeforeInit) {
2737 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2738
2739 // Figure out a good way to write this specifier on the old declaration.
2740 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2741 // enough of the attribute list spelling information to extract that without
2742 // heroics.
2743 std::string SuitableSpelling;
2744 if (S.getLangOpts().CPlusPlus2a)
2745 SuitableSpelling = std::string(
2746 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2747 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2748 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2749 InsertLoc, {tok::l_square, tok::l_square,
2750 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2751 S.PP.getIdentifierInfo("require_constant_initialization"),
2752 tok::r_square, tok::r_square}));
2753 if (SuitableSpelling.empty())
2754 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2755 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2756 S.PP.getIdentifierInfo("require_constant_initialization"),
2757 tok::r_paren, tok::r_paren}));
2758 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2759 SuitableSpelling = "constinit";
2760 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2761 SuitableSpelling = "[[clang::require_constant_initialization]]";
2762 if (SuitableSpelling.empty())
2763 SuitableSpelling = "__attribute__((require_constant_initialization))";
2764 SuitableSpelling += " ";
2765
2766 if (AttrBeforeInit) {
2767 // extern constinit int a;
2768 // int a = 0; // error (missing 'constinit'), accepted as extension
2769 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute"
) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 2769, __PRETTY_FUNCTION__))
;
2770 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2771 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2772 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2773 } else {
2774 // int a = 0;
2775 // constinit extern int a; // error (missing 'constinit')
2776 S.Diag(CIAttr->getLocation(),
2777 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2778 : diag::warn_require_const_init_added_too_late)
2779 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2780 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2781 << CIAttr->isConstinit()
2782 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2783 }
2784}
2785
2786/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2787void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2788 AvailabilityMergeKind AMK) {
2789 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2790 UsedAttr *NewAttr = OldAttr->clone(Context);
2791 NewAttr->setInherited(true);
2792 New->addAttr(NewAttr);
2793 }
2794
2795 if (!Old->hasAttrs() && !New->hasAttrs())
2796 return;
2797
2798 // [dcl.constinit]p1:
2799 // If the [constinit] specifier is applied to any declaration of a
2800 // variable, it shall be applied to the initializing declaration.
2801 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2802 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2803 if (bool(OldConstInit) != bool(NewConstInit)) {
2804 const auto *OldVD = cast<VarDecl>(Old);
2805 auto *NewVD = cast<VarDecl>(New);
2806
2807 // Find the initializing declaration. Note that we might not have linked
2808 // the new declaration into the redeclaration chain yet.
2809 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2810 if (!InitDecl &&
2811 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2812 InitDecl = NewVD;
2813
2814 if (InitDecl == NewVD) {
2815 // This is the initializing declaration. If it would inherit 'constinit',
2816 // that's ill-formed. (Note that we do not apply this to the attribute
2817 // form).
2818 if (OldConstInit && OldConstInit->isConstinit())
2819 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2820 /*AttrBeforeInit=*/true);
2821 } else if (NewConstInit) {
2822 // This is the first time we've been told that this declaration should
2823 // have a constant initializer. If we already saw the initializing
2824 // declaration, this is too late.
2825 if (InitDecl && InitDecl != NewVD) {
2826 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2827 /*AttrBeforeInit=*/false);
2828 NewVD->dropAttr<ConstInitAttr>();
2829 }
2830 }
2831 }
2832
2833 // Attributes declared post-definition are currently ignored.
2834 checkNewAttributesAfterDef(*this, New, Old);
2835
2836 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2837 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2838 if (!OldA->isEquivalent(NewA)) {
2839 // This redeclaration changes __asm__ label.
2840 Diag(New->getLocation(), diag::err_different_asm_label);
2841 Diag(OldA->getLocation(), diag::note_previous_declaration);
2842 }
2843 } else if (Old->isUsed()) {
2844 // This redeclaration adds an __asm__ label to a declaration that has
2845 // already been ODR-used.
2846 Diag(New->getLocation(), diag::err_late_asm_label_name)
2847 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2848 }
2849 }
2850
2851 // Re-declaration cannot add abi_tag's.
2852 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2853 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2854 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2855 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2856 NewTag) == OldAbiTagAttr->tags_end()) {
2857 Diag(NewAbiTagAttr->getLocation(),
2858 diag::err_new_abi_tag_on_redeclaration)
2859 << NewTag;
2860 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2861 }
2862 }
2863 } else {
2864 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2865 Diag(Old->getLocation(), diag::note_previous_declaration);
2866 }
2867 }
2868
2869 // This redeclaration adds a section attribute.
2870 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2871 if (auto *VD = dyn_cast<VarDecl>(New)) {
2872 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2873 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2874 Diag(Old->getLocation(), diag::note_previous_declaration);
2875 }
2876 }
2877 }
2878
2879 // Redeclaration adds code-seg attribute.
2880 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2881 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2882 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2883 Diag(New->getLocation(), diag::warn_mismatched_section)
2884 << 0 /*codeseg*/;
2885 Diag(Old->getLocation(), diag::note_previous_declaration);
2886 }
2887
2888 if (!Old->hasAttrs())
2889 return;
2890
2891 bool foundAny = New->hasAttrs();
2892
2893 // Ensure that any moving of objects within the allocated map is done before
2894 // we process them.
2895 if (!foundAny) New->setAttrs(AttrVec());
2896
2897 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2898 // Ignore deprecated/unavailable/availability attributes if requested.
2899 AvailabilityMergeKind LocalAMK = AMK_None;
2900 if (isa<DeprecatedAttr>(I) ||
2901 isa<UnavailableAttr>(I) ||
2902 isa<AvailabilityAttr>(I)) {
2903 switch (AMK) {
2904 case AMK_None:
2905 continue;
2906
2907 case AMK_Redeclaration:
2908 case AMK_Override:
2909 case AMK_ProtocolImplementation:
2910 LocalAMK = AMK;
2911 break;
2912 }
2913 }
2914
2915 // Already handled.
2916 if (isa<UsedAttr>(I))
2917 continue;
2918
2919 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2920 foundAny = true;
2921 }
2922
2923 if (mergeAlignedAttrs(*this, New, Old))
2924 foundAny = true;
2925
2926 if (!foundAny) New->dropAttrs();
2927}
2928
2929/// mergeParamDeclAttributes - Copy attributes from the old parameter
2930/// to the new one.
2931static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2932 const ParmVarDecl *oldDecl,
2933 Sema &S) {
2934 // C++11 [dcl.attr.depend]p2:
2935 // The first declaration of a function shall specify the
2936 // carries_dependency attribute for its declarator-id if any declaration
2937 // of the function specifies the carries_dependency attribute.
2938 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2939 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2940 S.Diag(CDA->getLocation(),
2941 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2942 // Find the first declaration of the parameter.
2943 // FIXME: Should we build redeclaration chains for function parameters?
2944 const FunctionDecl *FirstFD =
2945 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2946 const ParmVarDecl *FirstVD =
2947 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2948 S.Diag(FirstVD->getLocation(),
2949 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2950 }
2951
2952 if (!oldDecl->hasAttrs())
2953 return;
2954
2955 bool foundAny = newDecl->hasAttrs();
2956
2957 // Ensure that any moving of objects within the allocated map is
2958 // done before we process them.
2959 if (!foundAny) newDecl->setAttrs(AttrVec());
2960
2961 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2962 if (!DeclHasAttr(newDecl, I)) {
2963 InheritableAttr *newAttr =
2964 cast<InheritableParamAttr>(I->clone(S.Context));
2965 newAttr->setInherited(true);
2966 newDecl->addAttr(newAttr);
2967 foundAny = true;
2968 }
2969 }
2970
2971 if (!foundAny) newDecl->dropAttrs();
2972}
2973
2974static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2975 const ParmVarDecl *OldParam,
2976 Sema &S) {
2977 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2978 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2979 if (*Oldnullability != *Newnullability) {
2980 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2981 << DiagNullabilityKind(
2982 *Newnullability,
2983 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2984 != 0))
2985 << DiagNullabilityKind(
2986 *Oldnullability,
2987 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2988 != 0));
2989 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2990 }
2991 } else {
2992 QualType NewT = NewParam->getType();
2993 NewT = S.Context.getAttributedType(
2994 AttributedType::getNullabilityAttrKind(*Oldnullability),
2995 NewT, NewT);
2996 NewParam->setType(NewT);
2997 }
2998 }
2999}
3000
3001namespace {
3002
3003/// Used in MergeFunctionDecl to keep track of function parameters in
3004/// C.
3005struct GNUCompatibleParamWarning {
3006 ParmVarDecl *OldParm;
3007 ParmVarDecl *NewParm;
3008 QualType PromotedType;
3009};
3010
3011} // end anonymous namespace
3012
3013// Determine whether the previous declaration was a definition, implicit
3014// declaration, or a declaration.
3015template <typename T>
3016static std::pair<diag::kind, SourceLocation>
3017getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3018 diag::kind PrevDiag;
3019 SourceLocation OldLocation = Old->getLocation();
3020 if (Old->isThisDeclarationADefinition())
3021 PrevDiag = diag::note_previous_definition;
3022 else if (Old->isImplicit()) {
3023 PrevDiag = diag::note_previous_implicit_declaration;
3024 if (OldLocation.isInvalid())
3025 OldLocation = New->getLocation();
3026 } else
3027 PrevDiag = diag::note_previous_declaration;
3028 return std::make_pair(PrevDiag, OldLocation);
3029}
3030
3031/// canRedefineFunction - checks if a function can be redefined. Currently,
3032/// only extern inline functions can be redefined, and even then only in
3033/// GNU89 mode.
3034static bool canRedefineFunction(const FunctionDecl *FD,
3035 const LangOptions& LangOpts) {
3036 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3037 !LangOpts.CPlusPlus &&
3038 FD->isInlineSpecified() &&
3039 FD->getStorageClass() == SC_Extern);
3040}
3041
3042const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3043 const AttributedType *AT = T->getAs<AttributedType>();
3044 while (AT && !AT->isCallingConv())
3045 AT = AT->getModifiedType()->getAs<AttributedType>();
3046 return AT;
3047}
3048
3049template <typename T>
3050static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3051 const DeclContext *DC = Old->getDeclContext();
3052 if (DC->isRecord())
3053 return false;
3054
3055 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3056 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3057 return true;
3058 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3059 return true;
3060 return false;
3061}
3062
3063template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3064static bool isExternC(VarTemplateDecl *) { return false; }
3065
3066/// Check whether a redeclaration of an entity introduced by a
3067/// using-declaration is valid, given that we know it's not an overload
3068/// (nor a hidden tag declaration).
3069template<typename ExpectedDecl>
3070static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3071 ExpectedDecl *New) {
3072 // C++11 [basic.scope.declarative]p4:
3073 // Given a set of declarations in a single declarative region, each of
3074 // which specifies the same unqualified name,
3075 // -- they shall all refer to the same entity, or all refer to functions
3076 // and function templates; or
3077 // -- exactly one declaration shall declare a class name or enumeration
3078 // name that is not a typedef name and the other declarations shall all
3079 // refer to the same variable or enumerator, or all refer to functions
3080 // and function templates; in this case the class name or enumeration
3081 // name is hidden (3.3.10).
3082
3083 // C++11 [namespace.udecl]p14:
3084 // If a function declaration in namespace scope or block scope has the
3085 // same name and the same parameter-type-list as a function introduced
3086 // by a using-declaration, and the declarations do not declare the same
3087 // function, the program is ill-formed.
3088
3089 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3090 if (Old &&
3091 !Old->getDeclContext()->getRedeclContext()->Equals(
3092 New->getDeclContext()->getRedeclContext()) &&
3093 !(isExternC(Old) && isExternC(New)))
3094 Old = nullptr;
3095
3096 if (!Old) {
3097 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3098 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3099 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3100 return true;
3101 }
3102 return false;
3103}
3104
3105static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3106 const FunctionDecl *B) {
3107 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3107, __PRETTY_FUNCTION__))
;
3108
3109 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3110 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3111 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3112 if (AttrA == AttrB)
3113 return true;
3114 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3115 AttrA->isDynamic() == AttrB->isDynamic();
3116 };
3117
3118 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3119}
3120
3121/// If necessary, adjust the semantic declaration context for a qualified
3122/// declaration to name the correct inline namespace within the qualifier.
3123static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3124 DeclaratorDecl *OldD) {
3125 // The only case where we need to update the DeclContext is when
3126 // redeclaration lookup for a qualified name finds a declaration
3127 // in an inline namespace within the context named by the qualifier:
3128 //
3129 // inline namespace N { int f(); }
3130 // int ::f(); // Sema DC needs adjusting from :: to N::.
3131 //
3132 // For unqualified declarations, the semantic context *can* change
3133 // along the redeclaration chain (for local extern declarations,
3134 // extern "C" declarations, and friend declarations in particular).
3135 if (!NewD->getQualifier())
3136 return;
3137
3138 // NewD is probably already in the right context.
3139 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3140 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3141 if (NamedDC->Equals(SemaDC))
3142 return;
3143
3144 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3146, __PRETTY_FUNCTION__))
3145 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3146, __PRETTY_FUNCTION__))
3146 "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3146, __PRETTY_FUNCTION__))
;
3147
3148 auto *LexDC = NewD->getLexicalDeclContext();
3149 auto FixSemaDC = [=](NamedDecl *D) {
3150 if (!D)
3151 return;
3152 D->setDeclContext(SemaDC);
3153 D->setLexicalDeclContext(LexDC);
3154 };
3155
3156 FixSemaDC(NewD);
3157 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3158 FixSemaDC(FD->getDescribedFunctionTemplate());
3159 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3160 FixSemaDC(VD->getDescribedVarTemplate());
3161}
3162
3163/// MergeFunctionDecl - We just parsed a function 'New' from
3164/// declarator D which has the same name and scope as a previous
3165/// declaration 'Old'. Figure out how to resolve this situation,
3166/// merging decls or emitting diagnostics as appropriate.
3167///
3168/// In C++, New and Old must be declarations that are not
3169/// overloaded. Use IsOverload to determine whether New and Old are
3170/// overloaded, and to select the Old declaration that New should be
3171/// merged with.
3172///
3173/// Returns true if there was an error, false otherwise.
3174bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3175 Scope *S, bool MergeTypeWithOld) {
3176 // Verify the old decl was also a function.
3177 FunctionDecl *Old = OldD->getAsFunction();
3178 if (!Old) {
3179 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3180 if (New->getFriendObjectKind()) {
3181 Diag(New->getLocation(), diag::err_using_decl_friend);
3182 Diag(Shadow->getTargetDecl()->getLocation(),
3183 diag::note_using_decl_target);
3184 Diag(Shadow->getUsingDecl()->getLocation(),
3185 diag::note_using_decl) << 0;
3186 return true;
3187 }
3188
3189 // Check whether the two declarations might declare the same function.
3190 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3191 return true;
3192 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3193 } else {
3194 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3195 << New->getDeclName();
3196 notePreviousDefinition(OldD, New->getLocation());
3197 return true;
3198 }
3199 }
3200
3201 // If the old declaration is invalid, just give up here.
3202 if (Old->isInvalidDecl())
3203 return true;
3204
3205 // Disallow redeclaration of some builtins.
3206 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3207 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3208 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3209 << Old << Old->getType();
3210 return true;
3211 }
3212
3213 diag::kind PrevDiag;
3214 SourceLocation OldLocation;
3215 std::tie(PrevDiag, OldLocation) =
3216 getNoteDiagForInvalidRedeclaration(Old, New);
3217
3218 // Don't complain about this if we're in GNU89 mode and the old function
3219 // is an extern inline function.
3220 // Don't complain about specializations. They are not supposed to have
3221 // storage classes.
3222 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3223 New->getStorageClass() == SC_Static &&
3224 Old->hasExternalFormalLinkage() &&
3225 !New->getTemplateSpecializationInfo() &&
3226 !canRedefineFunction(Old, getLangOpts())) {
3227 if (getLangOpts().MicrosoftExt) {
3228 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3229 Diag(OldLocation, PrevDiag);
3230 } else {
3231 Diag(New->getLocation(), diag::err_static_non_static) << New;
3232 Diag(OldLocation, PrevDiag);
3233 return true;
3234 }
3235 }
3236
3237 if (New->hasAttr<InternalLinkageAttr>() &&
3238 !Old->hasAttr<InternalLinkageAttr>()) {
3239 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3240 << New->getDeclName();
3241 notePreviousDefinition(Old, New->getLocation());
3242 New->dropAttr<InternalLinkageAttr>();
3243 }
3244
3245 if (CheckRedeclarationModuleOwnership(New, Old))
3246 return true;
3247
3248 if (!getLangOpts().CPlusPlus) {
3249 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3250 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3251 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3252 << New << OldOvl;
3253
3254 // Try our best to find a decl that actually has the overloadable
3255 // attribute for the note. In most cases (e.g. programs with only one
3256 // broken declaration/definition), this won't matter.
3257 //
3258 // FIXME: We could do this if we juggled some extra state in
3259 // OverloadableAttr, rather than just removing it.
3260 const Decl *DiagOld = Old;
3261 if (OldOvl) {
3262 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3263 const auto *A = D->getAttr<OverloadableAttr>();
3264 return A && !A->isImplicit();
3265 });
3266 // If we've implicitly added *all* of the overloadable attrs to this
3267 // chain, emitting a "previous redecl" note is pointless.
3268 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3269 }
3270
3271 if (DiagOld)
3272 Diag(DiagOld->getLocation(),
3273 diag::note_attribute_overloadable_prev_overload)
3274 << OldOvl;
3275
3276 if (OldOvl)
3277 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3278 else
3279 New->dropAttr<OverloadableAttr>();
3280 }
3281 }
3282
3283 // If a function is first declared with a calling convention, but is later
3284 // declared or defined without one, all following decls assume the calling
3285 // convention of the first.
3286 //
3287 // It's OK if a function is first declared without a calling convention,
3288 // but is later declared or defined with the default calling convention.
3289 //
3290 // To test if either decl has an explicit calling convention, we look for
3291 // AttributedType sugar nodes on the type as written. If they are missing or
3292 // were canonicalized away, we assume the calling convention was implicit.
3293 //
3294 // Note also that we DO NOT return at this point, because we still have
3295 // other tests to run.
3296 QualType OldQType = Context.getCanonicalType(Old->getType());
3297 QualType NewQType = Context.getCanonicalType(New->getType());
3298 const FunctionType *OldType = cast<FunctionType>(OldQType);
3299 const FunctionType *NewType = cast<FunctionType>(NewQType);
3300 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3301 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3302 bool RequiresAdjustment = false;
3303
3304 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3305 FunctionDecl *First = Old->getFirstDecl();
3306 const FunctionType *FT =
3307 First->getType().getCanonicalType()->castAs<FunctionType>();
3308 FunctionType::ExtInfo FI = FT->getExtInfo();
3309 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3310 if (!NewCCExplicit) {
3311 // Inherit the CC from the previous declaration if it was specified
3312 // there but not here.
3313 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3314 RequiresAdjustment = true;
3315 } else if (New->getBuiltinID()) {
3316 // Calling Conventions on a Builtin aren't really useful and setting a
3317 // default calling convention and cdecl'ing some builtin redeclarations is
3318 // common, so warn and ignore the calling convention on the redeclaration.
3319 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3320 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3321 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3322 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3323 RequiresAdjustment = true;
3324 } else {
3325 // Calling conventions aren't compatible, so complain.
3326 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3327 Diag(New->getLocation(), diag::err_cconv_change)
3328 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3329 << !FirstCCExplicit
3330 << (!FirstCCExplicit ? "" :
3331 FunctionType::getNameForCallConv(FI.getCC()));
3332
3333 // Put the note on the first decl, since it is the one that matters.
3334 Diag(First->getLocation(), diag::note_previous_declaration);
3335 return true;
3336 }
3337 }
3338
3339 // FIXME: diagnose the other way around?
3340 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3341 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3342 RequiresAdjustment = true;
3343 }
3344
3345 // Merge regparm attribute.
3346 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3347 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3348 if (NewTypeInfo.getHasRegParm()) {
3349 Diag(New->getLocation(), diag::err_regparm_mismatch)
3350 << NewType->getRegParmType()
3351 << OldType->getRegParmType();
3352 Diag(OldLocation, diag::note_previous_declaration);
3353 return true;
3354 }
3355
3356 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3357 RequiresAdjustment = true;
3358 }
3359
3360 // Merge ns_returns_retained attribute.
3361 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3362 if (NewTypeInfo.getProducesResult()) {
3363 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3364 << "'ns_returns_retained'";
3365 Diag(OldLocation, diag::note_previous_declaration);
3366 return true;
3367 }
3368
3369 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3370 RequiresAdjustment = true;
3371 }
3372
3373 if (OldTypeInfo.getNoCallerSavedRegs() !=
3374 NewTypeInfo.getNoCallerSavedRegs()) {
3375 if (NewTypeInfo.getNoCallerSavedRegs()) {
3376 AnyX86NoCallerSavedRegistersAttr *Attr =
3377 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3378 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3379 Diag(OldLocation, diag::note_previous_declaration);
3380 return true;
3381 }
3382
3383 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3384 RequiresAdjustment = true;
3385 }
3386
3387 if (RequiresAdjustment) {
3388 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3389 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3390 New->setType(QualType(AdjustedType, 0));
3391 NewQType = Context.getCanonicalType(New->getType());
3392 }
3393
3394 // If this redeclaration makes the function inline, we may need to add it to
3395 // UndefinedButUsed.
3396 if (!Old->isInlined() && New->isInlined() &&
3397 !New->hasAttr<GNUInlineAttr>() &&
3398 !getLangOpts().GNUInline &&
3399 Old->isUsed(false) &&
3400 !Old->isDefined() && !New->isThisDeclarationADefinition())
3401 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3402 SourceLocation()));
3403
3404 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3405 // about it.
3406 if (New->hasAttr<GNUInlineAttr>() &&
3407 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3408 UndefinedButUsed.erase(Old->getCanonicalDecl());
3409 }
3410
3411 // If pass_object_size params don't match up perfectly, this isn't a valid
3412 // redeclaration.
3413 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3414 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3415 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3416 << New->getDeclName();
3417 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3418 return true;
3419 }
3420
3421 if (getLangOpts().CPlusPlus) {
3422 // C++1z [over.load]p2
3423 // Certain function declarations cannot be overloaded:
3424 // -- Function declarations that differ only in the return type,
3425 // the exception specification, or both cannot be overloaded.
3426
3427 // Check the exception specifications match. This may recompute the type of
3428 // both Old and New if it resolved exception specifications, so grab the
3429 // types again after this. Because this updates the type, we do this before
3430 // any of the other checks below, which may update the "de facto" NewQType
3431 // but do not necessarily update the type of New.
3432 if (CheckEquivalentExceptionSpec(Old, New))
3433 return true;
3434 OldQType = Context.getCanonicalType(Old->getType());
3435 NewQType = Context.getCanonicalType(New->getType());
3436
3437 // Go back to the type source info to compare the declared return types,
3438 // per C++1y [dcl.type.auto]p13:
3439 // Redeclarations or specializations of a function or function template
3440 // with a declared return type that uses a placeholder type shall also
3441 // use that placeholder, not a deduced type.
3442 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3443 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3444 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3445 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3446 OldDeclaredReturnType)) {
3447 QualType ResQT;
3448 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3449 OldDeclaredReturnType->isObjCObjectPointerType())
3450 // FIXME: This does the wrong thing for a deduced return type.
3451 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3452 if (ResQT.isNull()) {
3453 if (New->isCXXClassMember() && New->isOutOfLine())
3454 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3455 << New << New->getReturnTypeSourceRange();
3456 else
3457 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3458 << New->getReturnTypeSourceRange();
3459 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3460 << Old->getReturnTypeSourceRange();
3461 return true;
3462 }
3463 else
3464 NewQType = ResQT;
3465 }
3466
3467 QualType OldReturnType = OldType->getReturnType();
3468 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3469 if (OldReturnType != NewReturnType) {
3470 // If this function has a deduced return type and has already been
3471 // defined, copy the deduced value from the old declaration.
3472 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3473 if (OldAT && OldAT->isDeduced()) {
3474 New->setType(
3475 SubstAutoType(New->getType(),
3476 OldAT->isDependentType() ? Context.DependentTy
3477 : OldAT->getDeducedType()));
3478 NewQType = Context.getCanonicalType(
3479 SubstAutoType(NewQType,
3480 OldAT->isDependentType() ? Context.DependentTy
3481 : OldAT->getDeducedType()));
3482 }
3483 }
3484
3485 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3486 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3487 if (OldMethod && NewMethod) {
3488 // Preserve triviality.
3489 NewMethod->setTrivial(OldMethod->isTrivial());
3490
3491 // MSVC allows explicit template specialization at class scope:
3492 // 2 CXXMethodDecls referring to the same function will be injected.
3493 // We don't want a redeclaration error.
3494 bool IsClassScopeExplicitSpecialization =
3495 OldMethod->isFunctionTemplateSpecialization() &&
3496 NewMethod->isFunctionTemplateSpecialization();
3497 bool isFriend = NewMethod->getFriendObjectKind();
3498
3499 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3500 !IsClassScopeExplicitSpecialization) {
3501 // -- Member function declarations with the same name and the
3502 // same parameter types cannot be overloaded if any of them
3503 // is a static member function declaration.
3504 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3506 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3507 return true;
3508 }
3509
3510 // C++ [class.mem]p1:
3511 // [...] A member shall not be declared twice in the
3512 // member-specification, except that a nested class or member
3513 // class template can be declared and then later defined.
3514 if (!inTemplateInstantiation()) {
3515 unsigned NewDiag;
3516 if (isa<CXXConstructorDecl>(OldMethod))
3517 NewDiag = diag::err_constructor_redeclared;
3518 else if (isa<CXXDestructorDecl>(NewMethod))
3519 NewDiag = diag::err_destructor_redeclared;
3520 else if (isa<CXXConversionDecl>(NewMethod))
3521 NewDiag = diag::err_conv_function_redeclared;
3522 else
3523 NewDiag = diag::err_member_redeclared;
3524
3525 Diag(New->getLocation(), NewDiag);
3526 } else {
3527 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3528 << New << New->getType();
3529 }
3530 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3531 return true;
3532
3533 // Complain if this is an explicit declaration of a special
3534 // member that was initially declared implicitly.
3535 //
3536 // As an exception, it's okay to befriend such methods in order
3537 // to permit the implicit constructor/destructor/operator calls.
3538 } else if (OldMethod->isImplicit()) {
3539 if (isFriend) {
3540 NewMethod->setImplicit();
3541 } else {
3542 Diag(NewMethod->getLocation(),
3543 diag::err_definition_of_implicitly_declared_member)
3544 << New << getSpecialMember(OldMethod);
3545 return true;
3546 }
3547 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3548 Diag(NewMethod->getLocation(),
3549 diag::err_definition_of_explicitly_defaulted_member)
3550 << getSpecialMember(OldMethod);
3551 return true;
3552 }
3553 }
3554
3555 // C++11 [dcl.attr.noreturn]p1:
3556 // The first declaration of a function shall specify the noreturn
3557 // attribute if any declaration of that function specifies the noreturn
3558 // attribute.
3559 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3560 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3561 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3562 Diag(Old->getFirstDecl()->getLocation(),
3563 diag::note_noreturn_missing_first_decl);
3564 }
3565
3566 // C++11 [dcl.attr.depend]p2:
3567 // The first declaration of a function shall specify the
3568 // carries_dependency attribute for its declarator-id if any declaration
3569 // of the function specifies the carries_dependency attribute.
3570 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3571 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3572 Diag(CDA->getLocation(),
3573 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3574 Diag(Old->getFirstDecl()->getLocation(),
3575 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3576 }
3577
3578 // (C++98 8.3.5p3):
3579 // All declarations for a function shall agree exactly in both the
3580 // return type and the parameter-type-list.
3581 // We also want to respect all the extended bits except noreturn.
3582
3583 // noreturn should now match unless the old type info didn't have it.
3584 QualType OldQTypeForComparison = OldQType;
3585 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3586 auto *OldType = OldQType->castAs<FunctionProtoType>();
3587 const FunctionType *OldTypeForComparison
3588 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3589 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3590 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3590, __PRETTY_FUNCTION__))
;
3591 }
3592
3593 if (haveIncompatibleLanguageLinkages(Old, New)) {
3594 // As a special case, retain the language linkage from previous
3595 // declarations of a friend function as an extension.
3596 //
3597 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3598 // and is useful because there's otherwise no way to specify language
3599 // linkage within class scope.
3600 //
3601 // Check cautiously as the friend object kind isn't yet complete.
3602 if (New->getFriendObjectKind() != Decl::FOK_None) {
3603 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3604 Diag(OldLocation, PrevDiag);
3605 } else {
3606 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3607 Diag(OldLocation, PrevDiag);
3608 return true;
3609 }
3610 }
3611
3612 // If the function types are compatible, merge the declarations. Ignore the
3613 // exception specifier because it was already checked above in
3614 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3615 // about incompatible types under -fms-compatibility.
3616 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3617 NewQType))
3618 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3619
3620 // If the types are imprecise (due to dependent constructs in friends or
3621 // local extern declarations), it's OK if they differ. We'll check again
3622 // during instantiation.
3623 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3624 return false;
3625
3626 // Fall through for conflicting redeclarations and redefinitions.
3627 }
3628
3629 // C: Function types need to be compatible, not identical. This handles
3630 // duplicate function decls like "void f(int); void f(enum X);" properly.
3631 if (!getLangOpts().CPlusPlus &&
3632 Context.typesAreCompatible(OldQType, NewQType)) {
3633 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3634 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3635 const FunctionProtoType *OldProto = nullptr;
3636 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3637 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3638 // The old declaration provided a function prototype, but the
3639 // new declaration does not. Merge in the prototype.
3640 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C"
) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3640, __PRETTY_FUNCTION__))
;
3641 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3642 NewQType =
3643 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3644 OldProto->getExtProtoInfo());
3645 New->setType(NewQType);
3646 New->setHasInheritedPrototype();
3647
3648 // Synthesize parameters with the same types.
3649 SmallVector<ParmVarDecl*, 16> Params;
3650 for (const auto &ParamType : OldProto->param_types()) {
3651 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3652 SourceLocation(), nullptr,
3653 ParamType, /*TInfo=*/nullptr,
3654 SC_None, nullptr);
3655 Param->setScopeInfo(0, Params.size());
3656 Param->setImplicit();
3657 Params.push_back(Param);
3658 }
3659
3660 New->setParams(Params);
3661 }
3662
3663 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3664 }
3665
3666 // Check if the function types are compatible when pointer size address
3667 // spaces are ignored.
3668 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3669 return false;
3670
3671 // GNU C permits a K&R definition to follow a prototype declaration
3672 // if the declared types of the parameters in the K&R definition
3673 // match the types in the prototype declaration, even when the
3674 // promoted types of the parameters from the K&R definition differ
3675 // from the types in the prototype. GCC then keeps the types from
3676 // the prototype.
3677 //
3678 // If a variadic prototype is followed by a non-variadic K&R definition,
3679 // the K&R definition becomes variadic. This is sort of an edge case, but
3680 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3681 // C99 6.9.1p8.
3682 if (!getLangOpts().CPlusPlus &&
3683 Old->hasPrototype() && !New->hasPrototype() &&
3684 New->getType()->getAs<FunctionProtoType>() &&
3685 Old->getNumParams() == New->getNumParams()) {
3686 SmallVector<QualType, 16> ArgTypes;
3687 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3688 const FunctionProtoType *OldProto
3689 = Old->getType()->getAs<FunctionProtoType>();
3690 const FunctionProtoType *NewProto
3691 = New->getType()->getAs<FunctionProtoType>();
3692
3693 // Determine whether this is the GNU C extension.
3694 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3695 NewProto->getReturnType());
3696 bool LooseCompatible = !MergedReturn.isNull();
3697 for (unsigned Idx = 0, End = Old->getNumParams();
3698 LooseCompatible && Idx != End; ++Idx) {
3699 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3700 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3701 if (Context.typesAreCompatible(OldParm->getType(),
3702 NewProto->getParamType(Idx))) {
3703 ArgTypes.push_back(NewParm->getType());
3704 } else if (Context.typesAreCompatible(OldParm->getType(),
3705 NewParm->getType(),
3706 /*CompareUnqualified=*/true)) {
3707 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3708 NewProto->getParamType(Idx) };
3709 Warnings.push_back(Warn);
3710 ArgTypes.push_back(NewParm->getType());
3711 } else
3712 LooseCompatible = false;
3713 }
3714
3715 if (LooseCompatible) {
3716 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3717 Diag(Warnings[Warn].NewParm->getLocation(),
3718 diag::ext_param_promoted_not_compatible_with_prototype)
3719 << Warnings[Warn].PromotedType
3720 << Warnings[Warn].OldParm->getType();
3721 if (Warnings[Warn].OldParm->getLocation().isValid())
3722 Diag(Warnings[Warn].OldParm->getLocation(),
3723 diag::note_previous_declaration);
3724 }
3725
3726 if (MergeTypeWithOld)
3727 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3728 OldProto->getExtProtoInfo()));
3729 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3730 }
3731
3732 // Fall through to diagnose conflicting types.
3733 }
3734
3735 // A function that has already been declared has been redeclared or
3736 // defined with a different type; show an appropriate diagnostic.
3737
3738 // If the previous declaration was an implicitly-generated builtin
3739 // declaration, then at the very least we should use a specialized note.
3740 unsigned BuiltinID;
3741 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3742 // If it's actually a library-defined builtin function like 'malloc'
3743 // or 'printf', just warn about the incompatible redeclaration.
3744 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3745 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3746 Diag(OldLocation, diag::note_previous_builtin_declaration)
3747 << Old << Old->getType();
3748
3749 // If this is a global redeclaration, just forget hereafter
3750 // about the "builtin-ness" of the function.
3751 //
3752 // Doing this for local extern declarations is problematic. If
3753 // the builtin declaration remains visible, a second invalid
3754 // local declaration will produce a hard error; if it doesn't
3755 // remain visible, a single bogus local redeclaration (which is
3756 // actually only a warning) could break all the downstream code.
3757 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3758 New->getIdentifier()->revertBuiltin();
3759
3760 return false;
3761 }
3762
3763 PrevDiag = diag::note_previous_builtin_declaration;
3764 }
3765
3766 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3767 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3768 return true;
3769}
3770
3771/// Completes the merge of two function declarations that are
3772/// known to be compatible.
3773///
3774/// This routine handles the merging of attributes and other
3775/// properties of function declarations from the old declaration to
3776/// the new declaration, once we know that New is in fact a
3777/// redeclaration of Old.
3778///
3779/// \returns false
3780bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3781 Scope *S, bool MergeTypeWithOld) {
3782 // Merge the attributes
3783 mergeDeclAttributes(New, Old);
3784
3785 // Merge "pure" flag.
3786 if (Old->isPure())
3787 New->setPure();
3788
3789 // Merge "used" flag.
3790 if (Old->getMostRecentDecl()->isUsed(false))
3791 New->setIsUsed();
3792
3793 // Merge attributes from the parameters. These can mismatch with K&R
3794 // declarations.
3795 if (New->getNumParams() == Old->getNumParams())
3796 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3797 ParmVarDecl *NewParam = New->getParamDecl(i);
3798 ParmVarDecl *OldParam = Old->getParamDecl(i);
3799 mergeParamDeclAttributes(NewParam, OldParam, *this);
3800 mergeParamDeclTypes(NewParam, OldParam, *this);
3801 }
3802
3803 if (getLangOpts().CPlusPlus)
3804 return MergeCXXFunctionDecl(New, Old, S);
3805
3806 // Merge the function types so the we get the composite types for the return
3807 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3808 // was visible.
3809 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3810 if (!Merged.isNull() && MergeTypeWithOld)
3811 New->setType(Merged);
3812
3813 return false;
3814}
3815
3816void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3817 ObjCMethodDecl *oldMethod) {
3818 // Merge the attributes, including deprecated/unavailable
3819 AvailabilityMergeKind MergeKind =
3820 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3821 ? AMK_ProtocolImplementation
3822 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3823 : AMK_Override;
3824
3825 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3826
3827 // Merge attributes from the parameters.
3828 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3829 oe = oldMethod->param_end();
3830 for (ObjCMethodDecl::param_iterator
3831 ni = newMethod->param_begin(), ne = newMethod->param_end();
3832 ni != ne && oi != oe; ++ni, ++oi)
3833 mergeParamDeclAttributes(*ni, *oi, *this);
3834
3835 CheckObjCMethodOverride(newMethod, oldMethod);
3836}
3837
3838static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3839 assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType()
)) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 3839, __PRETTY_FUNCTION__))
;
3840
3841 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3842 ? diag::err_redefinition_different_type
3843 : diag::err_redeclaration_different_type)
3844 << New->getDeclName() << New->getType() << Old->getType();
3845
3846 diag::kind PrevDiag;
3847 SourceLocation OldLocation;
3848 std::tie(PrevDiag, OldLocation)
3849 = getNoteDiagForInvalidRedeclaration(Old, New);
3850 S.Diag(OldLocation, PrevDiag);
3851 New->setInvalidDecl();
3852}
3853
3854/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3855/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3856/// emitting diagnostics as appropriate.
3857///
3858/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3859/// to here in AddInitializerToDecl. We can't check them before the initializer
3860/// is attached.
3861void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3862 bool MergeTypeWithOld) {
3863 if (New->isInvalidDecl() || Old->isInvalidDecl())
3864 return;
3865
3866 QualType MergedT;
3867 if (getLangOpts().CPlusPlus) {
3868 if (New->getType()->isUndeducedType()) {
3869 // We don't know what the new type is until the initializer is attached.
3870 return;
3871 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3872 // These could still be something that needs exception specs checked.
3873 return MergeVarDeclExceptionSpecs(New, Old);
3874 }
3875 // C++ [basic.link]p10:
3876 // [...] the types specified by all declarations referring to a given
3877 // object or function shall be identical, except that declarations for an
3878 // array object can specify array types that differ by the presence or
3879 // absence of a major array bound (8.3.4).
3880 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3881 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3882 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3883
3884 // We are merging a variable declaration New into Old. If it has an array
3885 // bound, and that bound differs from Old's bound, we should diagnose the
3886 // mismatch.
3887 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3888 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3889 PrevVD = PrevVD->getPreviousDecl()) {
3890 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3891 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3892 continue;
3893
3894 if (!Context.hasSameType(NewArray, PrevVDTy))
3895 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3896 }
3897 }
3898
3899 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3900 if (Context.hasSameType(OldArray->getElementType(),
3901 NewArray->getElementType()))
3902 MergedT = New->getType();
3903 }
3904 // FIXME: Check visibility. New is hidden but has a complete type. If New
3905 // has no array bound, it should not inherit one from Old, if Old is not
3906 // visible.
3907 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3908 if (Context.hasSameType(OldArray->getElementType(),
3909 NewArray->getElementType()))
3910 MergedT = Old->getType();
3911 }
3912 }
3913 else if (New->getType()->isObjCObjectPointerType() &&
3914 Old->getType()->isObjCObjectPointerType()) {
3915 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3916 Old->getType());
3917 }
3918 } else {
3919 // C 6.2.7p2:
3920 // All declarations that refer to the same object or function shall have
3921 // compatible type.
3922 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3923 }
3924 if (MergedT.isNull()) {
3925 // It's OK if we couldn't merge types if either type is dependent, for a
3926 // block-scope variable. In other cases (static data members of class
3927 // templates, variable templates, ...), we require the types to be
3928 // equivalent.
3929 // FIXME: The C++ standard doesn't say anything about this.
3930 if ((New->getType()->isDependentType() ||
3931 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3932 // If the old type was dependent, we can't merge with it, so the new type
3933 // becomes dependent for now. We'll reproduce the original type when we
3934 // instantiate the TypeSourceInfo for the variable.
3935 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3936 New->setType(Context.DependentTy);
3937 return;
3938 }
3939 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3940 }
3941
3942 // Don't actually update the type on the new declaration if the old
3943 // declaration was an extern declaration in a different scope.
3944 if (MergeTypeWithOld)
3945 New->setType(MergedT);
3946}
3947
3948static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3949 LookupResult &Previous) {
3950 // C11 6.2.7p4:
3951 // For an identifier with internal or external linkage declared
3952 // in a scope in which a prior declaration of that identifier is
3953 // visible, if the prior declaration specifies internal or
3954 // external linkage, the type of the identifier at the later
3955 // declaration becomes the composite type.
3956 //
3957 // If the variable isn't visible, we do not merge with its type.
3958 if (Previous.isShadowed())
3959 return false;
3960
3961 if (S.getLangOpts().CPlusPlus) {
3962 // C++11 [dcl.array]p3:
3963 // If there is a preceding declaration of the entity in the same
3964 // scope in which the bound was specified, an omitted array bound
3965 // is taken to be the same as in that earlier declaration.
3966 return NewVD->isPreviousDeclInSameBlockScope() ||
3967 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3968 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3969 } else {
3970 // If the old declaration was function-local, don't merge with its
3971 // type unless we're in the same function.
3972 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3973 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3974 }
3975}
3976
3977/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3978/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3979/// situation, merging decls or emitting diagnostics as appropriate.
3980///
3981/// Tentative definition rules (C99 6.9.2p2) are checked by
3982/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3983/// definitions here, since the initializer hasn't been attached.
3984///
3985void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3986 // If the new decl is already invalid, don't do any other checking.
3987 if (New->isInvalidDecl())
3988 return;
3989
3990 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3991 return;
3992
3993 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3994
3995 // Verify the old decl was also a variable or variable template.
3996 VarDecl *Old = nullptr;
3997 VarTemplateDecl *OldTemplate = nullptr;
3998 if (Previous.isSingleResult()) {
3999 if (NewTemplate) {
4000 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4001 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4002
4003 if (auto *Shadow =
4004 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4005 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4006 return New->setInvalidDecl();
4007 } else {
4008 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4009
4010 if (auto *Shadow =
4011 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4012 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4013 return New->setInvalidDecl();
4014 }
4015 }
4016 if (!Old) {
4017 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4018 << New->getDeclName();
4019 notePreviousDefinition(Previous.getRepresentativeDecl(),
4020 New->getLocation());
4021 return New->setInvalidDecl();
4022 }
4023
4024 // Ensure the template parameters are compatible.
4025 if (NewTemplate &&
4026 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4027 OldTemplate->getTemplateParameters(),
4028 /*Complain=*/true, TPL_TemplateMatch))
4029 return New->setInvalidDecl();
4030
4031 // C++ [class.mem]p1:
4032 // A member shall not be declared twice in the member-specification [...]
4033 //
4034 // Here, we need only consider static data members.
4035 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4036 Diag(New->getLocation(), diag::err_duplicate_member)
4037 << New->getIdentifier();
4038 Diag(Old->getLocation(), diag::note_previous_declaration);
4039 New->setInvalidDecl();
4040 }
4041
4042 mergeDeclAttributes(New, Old);
4043 // Warn if an already-declared variable is made a weak_import in a subsequent
4044 // declaration
4045 if (New->hasAttr<WeakImportAttr>() &&
4046 Old->getStorageClass() == SC_None &&
4047 !Old->hasAttr<WeakImportAttr>()) {
4048 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4049 notePreviousDefinition(Old, New->getLocation());
4050 // Remove weak_import attribute on new declaration.
4051 New->dropAttr<WeakImportAttr>();
4052 }
4053
4054 if (New->hasAttr<InternalLinkageAttr>() &&
4055 !Old->hasAttr<InternalLinkageAttr>()) {
4056 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4057 << New->getDeclName();
4058 notePreviousDefinition(Old, New->getLocation());
4059 New->dropAttr<InternalLinkageAttr>();
4060 }
4061
4062 // Merge the types.
4063 VarDecl *MostRecent = Old->getMostRecentDecl();
4064 if (MostRecent != Old) {
4065 MergeVarDeclTypes(New, MostRecent,
4066 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4067 if (New->isInvalidDecl())
4068 return;
4069 }
4070
4071 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4072 if (New->isInvalidDecl())
4073 return;
4074
4075 diag::kind PrevDiag;
4076 SourceLocation OldLocation;
4077 std::tie(PrevDiag, OldLocation) =
4078 getNoteDiagForInvalidRedeclaration(Old, New);
4079
4080 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4081 if (New->getStorageClass() == SC_Static &&
4082 !New->isStaticDataMember() &&
4083 Old->hasExternalFormalLinkage()) {
4084 if (getLangOpts().MicrosoftExt) {
4085 Diag(New->getLocation(), diag::ext_static_non_static)
4086 << New->getDeclName();
4087 Diag(OldLocation, PrevDiag);
4088 } else {
4089 Diag(New->getLocation(), diag::err_static_non_static)
4090 << New->getDeclName();
4091 Diag(OldLocation, PrevDiag);
4092 return New->setInvalidDecl();
4093 }
4094 }
4095 // C99 6.2.2p4:
4096 // For an identifier declared with the storage-class specifier
4097 // extern in a scope in which a prior declaration of that
4098 // identifier is visible,23) if the prior declaration specifies
4099 // internal or external linkage, the linkage of the identifier at
4100 // the later declaration is the same as the linkage specified at
4101 // the prior declaration. If no prior declaration is visible, or
4102 // if the prior declaration specifies no linkage, then the
4103 // identifier has external linkage.
4104 if (New->hasExternalStorage() && Old->hasLinkage())
4105 /* Okay */;
4106 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4107 !New->isStaticDataMember() &&
4108 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4109 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4110 Diag(OldLocation, PrevDiag);
4111 return New->setInvalidDecl();
4112 }
4113
4114 // Check if extern is followed by non-extern and vice-versa.
4115 if (New->hasExternalStorage() &&
4116 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4117 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4118 Diag(OldLocation, PrevDiag);
4119 return New->setInvalidDecl();
4120 }
4121 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4122 !New->hasExternalStorage()) {
4123 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4124 Diag(OldLocation, PrevDiag);
4125 return New->setInvalidDecl();
4126 }
4127
4128 if (CheckRedeclarationModuleOwnership(New, Old))
4129 return;
4130
4131 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4132
4133 // FIXME: The test for external storage here seems wrong? We still
4134 // need to check for mismatches.
4135 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4136 // Don't complain about out-of-line definitions of static members.
4137 !(Old->getLexicalDeclContext()->isRecord() &&
4138 !New->getLexicalDeclContext()->isRecord())) {
4139 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4140 Diag(OldLocation, PrevDiag);
4141 return New->setInvalidDecl();
4142 }
4143
4144 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4145 if (VarDecl *Def = Old->getDefinition()) {
4146 // C++1z [dcl.fcn.spec]p4:
4147 // If the definition of a variable appears in a translation unit before
4148 // its first declaration as inline, the program is ill-formed.
4149 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4150 Diag(Def->getLocation(), diag::note_previous_definition);
4151 }
4152 }
4153
4154 // If this redeclaration makes the variable inline, we may need to add it to
4155 // UndefinedButUsed.
4156 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4157 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4158 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4159 SourceLocation()));
4160
4161 if (New->getTLSKind() != Old->getTLSKind()) {
4162 if (!Old->getTLSKind()) {
4163 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4164 Diag(OldLocation, PrevDiag);
4165 } else if (!New->getTLSKind()) {
4166 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4167 Diag(OldLocation, PrevDiag);
4168 } else {
4169 // Do not allow redeclaration to change the variable between requiring
4170 // static and dynamic initialization.
4171 // FIXME: GCC allows this, but uses the TLS keyword on the first
4172 // declaration to determine the kind. Do we need to be compatible here?
4173 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4174 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4175 Diag(OldLocation, PrevDiag);
4176 }
4177 }
4178
4179 // C++ doesn't have tentative definitions, so go right ahead and check here.
4180 if (getLangOpts().CPlusPlus &&
4181 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4182 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4183 Old->getCanonicalDecl()->isConstexpr()) {
4184 // This definition won't be a definition any more once it's been merged.
4185 Diag(New->getLocation(),
4186 diag::warn_deprecated_redundant_constexpr_static_def);
4187 } else if (VarDecl *Def = Old->getDefinition()) {
4188 if (checkVarDeclRedefinition(Def, New))
4189 return;
4190 }
4191 }
4192
4193 if (haveIncompatibleLanguageLinkages(Old, New)) {
4194 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4195 Diag(OldLocation, PrevDiag);
4196 New->setInvalidDecl();
4197 return;
4198 }
4199
4200 // Merge "used" flag.
4201 if (Old->getMostRecentDecl()->isUsed(false))
4202 New->setIsUsed();
4203
4204 // Keep a chain of previous declarations.
4205 New->setPreviousDecl(Old);
4206 if (NewTemplate)
4207 NewTemplate->setPreviousDecl(OldTemplate);
4208 adjustDeclContextForDeclaratorDecl(New, Old);
4209
4210 // Inherit access appropriately.
4211 New->setAccess(Old->getAccess());
4212 if (NewTemplate)
4213 NewTemplate->setAccess(New->getAccess());
4214
4215 if (Old->isInline())
4216 New->setImplicitlyInline();
4217}
4218
4219void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4220 SourceManager &SrcMgr = getSourceManager();
4221 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4222 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4223 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4224 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4225 auto &HSI = PP.getHeaderSearchInfo();
4226 StringRef HdrFilename =
4227 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4228
4229 auto noteFromModuleOrInclude = [&](Module *Mod,
4230 SourceLocation IncLoc) -> bool {
4231 // Redefinition errors with modules are common with non modular mapped
4232 // headers, example: a non-modular header H in module A that also gets
4233 // included directly in a TU. Pointing twice to the same header/definition
4234 // is confusing, try to get better diagnostics when modules is on.
4235 if (IncLoc.isValid()) {
4236 if (Mod) {
4237 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4238 << HdrFilename.str() << Mod->getFullModuleName();
4239 if (!Mod->DefinitionLoc.isInvalid())
4240 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4241 << Mod->getFullModuleName();
4242 } else {
4243 Diag(IncLoc, diag::note_redefinition_include_same_file)
4244 << HdrFilename.str();
4245 }
4246 return true;
4247 }
4248
4249 return false;
4250 };
4251
4252 // Is it the same file and same offset? Provide more information on why
4253 // this leads to a redefinition error.
4254 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4255 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4256 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4257 bool EmittedDiag =
4258 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4259 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4260
4261 // If the header has no guards, emit a note suggesting one.
4262 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4263 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4264
4265 if (EmittedDiag)
4266 return;
4267 }
4268
4269 // Redefinition coming from different files or couldn't do better above.
4270 if (Old->getLocation().isValid())
4271 Diag(Old->getLocation(), diag::note_previous_definition);
4272}
4273
4274/// We've just determined that \p Old and \p New both appear to be definitions
4275/// of the same variable. Either diagnose or fix the problem.
4276bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4277 if (!hasVisibleDefinition(Old) &&
4278 (New->getFormalLinkage() == InternalLinkage ||
4279 New->isInline() ||
4280 New->getDescribedVarTemplate() ||
4281 New->getNumTemplateParameterLists() ||
4282 New->getDeclContext()->isDependentContext())) {
4283 // The previous definition is hidden, and multiple definitions are
4284 // permitted (in separate TUs). Demote this to a declaration.
4285 New->demoteThisDefinitionToDeclaration();
4286
4287 // Make the canonical definition visible.
4288 if (auto *OldTD = Old->getDescribedVarTemplate())
4289 makeMergedDefinitionVisible(OldTD);
4290 makeMergedDefinitionVisible(Old);
4291 return false;
4292 } else {
4293 Diag(New->getLocation(), diag::err_redefinition) << New;
4294 notePreviousDefinition(Old, New->getLocation());
4295 New->setInvalidDecl();
4296 return true;
4297 }
4298}
4299
4300/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4301/// no declarator (e.g. "struct foo;") is parsed.
4302Decl *
4303Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4304 RecordDecl *&AnonRecord) {
4305 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4306 AnonRecord);
4307}
4308
4309// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4310// disambiguate entities defined in different scopes.
4311// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4312// compatibility.
4313// We will pick our mangling number depending on which version of MSVC is being
4314// targeted.
4315static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4316 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4317 ? S->getMSCurManglingNumber()
4318 : S->getMSLastManglingNumber();
4319}
4320
4321void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4322 if (!Context.getLangOpts().CPlusPlus)
4323 return;
4324
4325 if (isa<CXXRecordDecl>(Tag->getParent())) {
4326 // If this tag is the direct child of a class, number it if
4327 // it is anonymous.
4328 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4329 return;
4330 MangleNumberingContext &MCtx =
4331 Context.getManglingNumberContext(Tag->getParent());
4332 Context.setManglingNumber(
4333 Tag, MCtx.getManglingNumber(
4334 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4335 return;
4336 }
4337
4338 // If this tag isn't a direct child of a class, number it if it is local.
4339 MangleNumberingContext *MCtx;
4340 Decl *ManglingContextDecl;
4341 std::tie(MCtx, ManglingContextDecl) =
4342 getCurrentMangleNumberContext(Tag->getDeclContext());
4343 if (MCtx) {
4344 Context.setManglingNumber(
4345 Tag, MCtx->getManglingNumber(
4346 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4347 }
4348}
4349
4350namespace {
4351struct NonCLikeKind {
4352 enum {
4353 None,
4354 BaseClass,
4355 DefaultMemberInit,
4356 Lambda,
4357 Friend,
4358 OtherMember,
4359 Invalid,
4360 } Kind = None;
4361 SourceRange Range;
4362
4363 explicit operator bool() { return Kind != None; }
4364};
4365}
4366
4367/// Determine whether a class is C-like, according to the rules of C++
4368/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4369static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4370 if (RD->isInvalidDecl())
4371 return {NonCLikeKind::Invalid, {}};
4372
4373 // C++ [dcl.typedef]p9: [P1766R1]
4374 // An unnamed class with a typedef name for linkage purposes shall not
4375 //
4376 // -- have any base classes
4377 if (RD->getNumBases())
4378 return {NonCLikeKind::BaseClass,
4379 SourceRange(RD->bases_begin()->getBeginLoc(),
4380 RD->bases_end()[-1].getEndLoc())};
4381 bool Invalid = false;
4382 for (Decl *D : RD->decls()) {
4383 // Don't complain about things we already diagnosed.
4384 if (D->isInvalidDecl()) {
4385 Invalid = true;
4386 continue;
4387 }
4388
4389 // -- have any [...] default member initializers
4390 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4391 if (FD->hasInClassInitializer()) {
4392 auto *Init = FD->getInClassInitializer();
4393 return {NonCLikeKind::DefaultMemberInit,
4394 Init ? Init->getSourceRange() : D->getSourceRange()};
4395 }
4396 continue;
4397 }
4398
4399 // FIXME: We don't allow friend declarations. This violates the wording of
4400 // P1766, but not the intent.
4401 if (isa<FriendDecl>(D))
4402 return {NonCLikeKind::Friend, D->getSourceRange()};
4403
4404 // -- declare any members other than non-static data members, member
4405 // enumerations, or member classes,
4406 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4407 isa<EnumDecl>(D))
4408 continue;
4409 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4410 if (!MemberRD)
4411 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4412
4413 // -- contain a lambda-expression,
4414 if (MemberRD->isLambda())
4415 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4416
4417 // and all member classes shall also satisfy these requirements
4418 // (recursively).
4419 if (MemberRD->isThisDeclarationADefinition()) {
4420 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4421 return Kind;
4422 }
4423 }
4424
4425 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4426}
4427
4428void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4429 TypedefNameDecl *NewTD) {
4430 if (TagFromDeclSpec->isInvalidDecl())
4431 return;
4432
4433 // Do nothing if the tag already has a name for linkage purposes.
4434 if (TagFromDeclSpec->hasNameForLinkage())
4435 return;
4436
4437 // A well-formed anonymous tag must always be a TUK_Definition.
4438 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4438, __PRETTY_FUNCTION__))
;
4439
4440 // The type must match the tag exactly; no qualifiers allowed.
4441 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4442 Context.getTagDeclType(TagFromDeclSpec))) {
4443 if (getLangOpts().CPlusPlus)
4444 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4445 return;
4446 }
4447
4448 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4449 // An unnamed class with a typedef name for linkage purposes shall [be
4450 // C-like].
4451 //
4452 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4453 // shouldn't happen, but there are constructs that the language rule doesn't
4454 // disallow for which we can't reasonably avoid computing linkage early.
4455 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4456 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4457 : NonCLikeKind();
4458 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4459 if (NonCLike || ChangesLinkage) {
4460 if (NonCLike.Kind == NonCLikeKind::Invalid)
4461 return;
4462
4463 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4464 if (ChangesLinkage) {
4465 // If the linkage changes, we can't accept this as an extension.
4466 if (NonCLike.Kind == NonCLikeKind::None)
4467 DiagID = diag::err_typedef_changes_linkage;
4468 else
4469 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4470 }
4471
4472 SourceLocation FixitLoc =
4473 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4474 llvm::SmallString<40> TextToInsert;
4475 TextToInsert += ' ';
4476 TextToInsert += NewTD->getIdentifier()->getName();
4477
4478 Diag(FixitLoc, DiagID)
4479 << isa<TypeAliasDecl>(NewTD)
4480 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4481 if (NonCLike.Kind != NonCLikeKind::None) {
4482 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4483 << NonCLike.Kind - 1 << NonCLike.Range;
4484 }
4485 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4486 << NewTD << isa<TypeAliasDecl>(NewTD);
4487
4488 if (ChangesLinkage)
4489 return;
4490 }
4491
4492 // Otherwise, set this as the anon-decl typedef for the tag.
4493 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4494}
4495
4496static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4497 switch (T) {
4498 case DeclSpec::TST_class:
4499 return 0;
4500 case DeclSpec::TST_struct:
4501 return 1;
4502 case DeclSpec::TST_interface:
4503 return 2;
4504 case DeclSpec::TST_union:
4505 return 3;
4506 case DeclSpec::TST_enum:
4507 return 4;
4508 default:
4509 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4509)
;
4510 }
4511}
4512
4513/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4514/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4515/// parameters to cope with template friend declarations.
4516Decl *
4517Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4518 MultiTemplateParamsArg TemplateParams,
4519 bool IsExplicitInstantiation,
4520 RecordDecl *&AnonRecord) {
4521 Decl *TagD = nullptr;
4522 TagDecl *Tag = nullptr;
4523 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4524 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4525 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4526 DS.getTypeSpecType() == DeclSpec::TST_union ||
4527 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4528 TagD = DS.getRepAsDecl();
4529
4530 if (!TagD) // We probably had an error
4531 return nullptr;
4532
4533 // Note that the above type specs guarantee that the
4534 // type rep is a Decl, whereas in many of the others
4535 // it's a Type.
4536 if (isa<TagDecl>(TagD))
4537 Tag = cast<TagDecl>(TagD);
4538 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4539 Tag = CTD->getTemplatedDecl();
4540 }
4541
4542 if (Tag) {
4543 handleTagNumbering(Tag, S);
4544 Tag->setFreeStanding();
4545 if (Tag->isInvalidDecl())
4546 return Tag;
4547 }
4548
4549 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4550 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4551 // or incomplete types shall not be restrict-qualified."
4552 if (TypeQuals & DeclSpec::TQ_restrict)
4553 Diag(DS.getRestrictSpecLoc(),
4554 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4555 << DS.getSourceRange();
4556 }
4557
4558 if (DS.isInlineSpecified())
4559 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4560 << getLangOpts().CPlusPlus17;
4561
4562 if (DS.hasConstexprSpecifier()) {
4563 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4564 // and definitions of functions and variables.
4565 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4566 // the declaration of a function or function template
4567 if (Tag)
4568 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4569 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4570 << DS.getConstexprSpecifier();
4571 else
4572 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4573 << DS.getConstexprSpecifier();
4574 // Don't emit warnings after this error.
4575 return TagD;
4576 }
4577
4578 DiagnoseFunctionSpecifiers(DS);
4579
4580 if (DS.isFriendSpecified()) {
4581 // If we're dealing with a decl but not a TagDecl, assume that
4582 // whatever routines created it handled the friendship aspect.
4583 if (TagD && !Tag)
4584 return nullptr;
4585 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4586 }
4587
4588 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4589 bool IsExplicitSpecialization =
4590 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4591 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4592 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4593 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4594 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4595 // nested-name-specifier unless it is an explicit instantiation
4596 // or an explicit specialization.
4597 //
4598 // FIXME: We allow class template partial specializations here too, per the
4599 // obvious intent of DR1819.
4600 //
4601 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4602 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4603 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4604 return nullptr;
4605 }
4606
4607 // Track whether this decl-specifier declares anything.
4608 bool DeclaresAnything = true;
4609
4610 // Handle anonymous struct definitions.
4611 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4612 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4613 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4614 if (getLangOpts().CPlusPlus ||
4615 Record->getDeclContext()->isRecord()) {
4616 // If CurContext is a DeclContext that can contain statements,
4617 // RecursiveASTVisitor won't visit the decls that
4618 // BuildAnonymousStructOrUnion() will put into CurContext.
4619 // Also store them here so that they can be part of the
4620 // DeclStmt that gets created in this case.
4621 // FIXME: Also return the IndirectFieldDecls created by
4622 // BuildAnonymousStructOr union, for the same reason?
4623 if (CurContext->isFunctionOrMethod())
4624 AnonRecord = Record;
4625 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4626 Context.getPrintingPolicy());
4627 }
4628
4629 DeclaresAnything = false;
4630 }
4631 }
4632
4633 // C11 6.7.2.1p2:
4634 // A struct-declaration that does not declare an anonymous structure or
4635 // anonymous union shall contain a struct-declarator-list.
4636 //
4637 // This rule also existed in C89 and C99; the grammar for struct-declaration
4638 // did not permit a struct-declaration without a struct-declarator-list.
4639 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4640 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4641 // Check for Microsoft C extension: anonymous struct/union member.
4642 // Handle 2 kinds of anonymous struct/union:
4643 // struct STRUCT;
4644 // union UNION;
4645 // and
4646 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4647 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4648 if ((Tag && Tag->getDeclName()) ||
4649 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4650 RecordDecl *Record = nullptr;
4651 if (Tag)
4652 Record = dyn_cast<RecordDecl>(Tag);
4653 else if (const RecordType *RT =
4654 DS.getRepAsType().get()->getAsStructureType())
4655 Record = RT->getDecl();
4656 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4657 Record = UT->getDecl();
4658
4659 if (Record && getLangOpts().MicrosoftExt) {
4660 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4661 << Record->isUnion() << DS.getSourceRange();
4662 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4663 }
4664
4665 DeclaresAnything = false;
4666 }
4667 }
4668
4669 // Skip all the checks below if we have a type error.
4670 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4671 (TagD && TagD->isInvalidDecl()))
4672 return TagD;
4673
4674 if (getLangOpts().CPlusPlus &&
4675 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4676 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4677 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4678 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4679 DeclaresAnything = false;
4680
4681 if (!DS.isMissingDeclaratorOk()) {
4682 // Customize diagnostic for a typedef missing a name.
4683 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4684 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4685 << DS.getSourceRange();
4686 else
4687 DeclaresAnything = false;
4688 }
4689
4690 if (DS.isModulePrivateSpecified() &&
4691 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4692 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4693 << Tag->getTagKind()
4694 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4695
4696 ActOnDocumentableDecl(TagD);
4697
4698 // C 6.7/2:
4699 // A declaration [...] shall declare at least a declarator [...], a tag,
4700 // or the members of an enumeration.
4701 // C++ [dcl.dcl]p3:
4702 // [If there are no declarators], and except for the declaration of an
4703 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4704 // names into the program, or shall redeclare a name introduced by a
4705 // previous declaration.
4706 if (!DeclaresAnything) {
4707 // In C, we allow this as a (popular) extension / bug. Don't bother
4708 // producing further diagnostics for redundant qualifiers after this.
4709 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4710 return TagD;
4711 }
4712
4713 // C++ [dcl.stc]p1:
4714 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4715 // init-declarator-list of the declaration shall not be empty.
4716 // C++ [dcl.fct.spec]p1:
4717 // If a cv-qualifier appears in a decl-specifier-seq, the
4718 // init-declarator-list of the declaration shall not be empty.
4719 //
4720 // Spurious qualifiers here appear to be valid in C.
4721 unsigned DiagID = diag::warn_standalone_specifier;
4722 if (getLangOpts().CPlusPlus)
4723 DiagID = diag::ext_standalone_specifier;
4724
4725 // Note that a linkage-specification sets a storage class, but
4726 // 'extern "C" struct foo;' is actually valid and not theoretically
4727 // useless.
4728 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4729 if (SCS == DeclSpec::SCS_mutable)
4730 // Since mutable is not a viable storage class specifier in C, there is
4731 // no reason to treat it as an extension. Instead, diagnose as an error.
4732 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4733 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4734 Diag(DS.getStorageClassSpecLoc(), DiagID)
4735 << DeclSpec::getSpecifierName(SCS);
4736 }
4737
4738 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4739 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4740 << DeclSpec::getSpecifierName(TSCS);
4741 if (DS.getTypeQualifiers()) {
4742 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4743 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4744 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4745 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4746 // Restrict is covered above.
4747 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4748 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4749 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4750 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4751 }
4752
4753 // Warn about ignored type attributes, for example:
4754 // __attribute__((aligned)) struct A;
4755 // Attributes should be placed after tag to apply to type declaration.
4756 if (!DS.getAttributes().empty()) {
4757 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4758 if (TypeSpecType == DeclSpec::TST_class ||
4759 TypeSpecType == DeclSpec::TST_struct ||
4760 TypeSpecType == DeclSpec::TST_interface ||
4761 TypeSpecType == DeclSpec::TST_union ||
4762 TypeSpecType == DeclSpec::TST_enum) {
4763 for (const ParsedAttr &AL : DS.getAttributes())
4764 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4765 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4766 }
4767 }
4768
4769 return TagD;
4770}
4771
4772/// We are trying to inject an anonymous member into the given scope;
4773/// check if there's an existing declaration that can't be overloaded.
4774///
4775/// \return true if this is a forbidden redeclaration
4776static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4777 Scope *S,
4778 DeclContext *Owner,
4779 DeclarationName Name,
4780 SourceLocation NameLoc,
4781 bool IsUnion) {
4782 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4783 Sema::ForVisibleRedeclaration);
4784 if (!SemaRef.LookupName(R, S)) return false;
4785
4786 // Pick a representative declaration.
4787 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4788 assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast
<void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4788, __PRETTY_FUNCTION__))
;
4789
4790 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4791 return false;
4792
4793 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4794 << IsUnion << Name;
4795 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4796
4797 return true;
4798}
4799
4800/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4801/// anonymous struct or union AnonRecord into the owning context Owner
4802/// and scope S. This routine will be invoked just after we realize
4803/// that an unnamed union or struct is actually an anonymous union or
4804/// struct, e.g.,
4805///
4806/// @code
4807/// union {
4808/// int i;
4809/// float f;
4810/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4811/// // f into the surrounding scope.x
4812/// @endcode
4813///
4814/// This routine is recursive, injecting the names of nested anonymous
4815/// structs/unions into the owning context and scope as well.
4816static bool
4817InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4818 RecordDecl *AnonRecord, AccessSpecifier AS,
4819 SmallVectorImpl<NamedDecl *> &Chaining) {
4820 bool Invalid = false;
4821
4822 // Look every FieldDecl and IndirectFieldDecl with a name.
4823 for (auto *D : AnonRecord->decls()) {
4824 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4825 cast<NamedDecl>(D)->getDeclName()) {
4826 ValueDecl *VD = cast<ValueDecl>(D);
4827 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4828 VD->getLocation(),
4829 AnonRecord->isUnion())) {
4830 // C++ [class.union]p2:
4831 // The names of the members of an anonymous union shall be
4832 // distinct from the names of any other entity in the
4833 // scope in which the anonymous union is declared.
4834 Invalid = true;
4835 } else {
4836 // C++ [class.union]p2:
4837 // For the purpose of name lookup, after the anonymous union
4838 // definition, the members of the anonymous union are
4839 // considered to have been defined in the scope in which the
4840 // anonymous union is declared.
4841 unsigned OldChainingSize = Chaining.size();
4842 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4843 Chaining.append(IF->chain_begin(), IF->chain_end());
4844 else
4845 Chaining.push_back(VD);
4846
4847 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4847, __PRETTY_FUNCTION__))
;
4848 NamedDecl **NamedChain =
4849 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4850 for (unsigned i = 0; i < Chaining.size(); i++)
4851 NamedChain[i] = Chaining[i];
4852
4853 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4854 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4855 VD->getType(), {NamedChain, Chaining.size()});
4856
4857 for (const auto *Attr : VD->attrs())
4858 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4859
4860 IndirectField->setAccess(AS);
4861 IndirectField->setImplicit();
4862 SemaRef.PushOnScopeChains(IndirectField, S);
4863
4864 // That includes picking up the appropriate access specifier.
4865 if (AS != AS_none) IndirectField->setAccess(AS);
4866
4867 Chaining.resize(OldChainingSize);
4868 }
4869 }
4870 }
4871
4872 return Invalid;
4873}
4874
4875/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4876/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4877/// illegal input values are mapped to SC_None.
4878static StorageClass
4879StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4880 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4881 assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4882, __PRETTY_FUNCTION__))
4882 "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4882, __PRETTY_FUNCTION__))
;
4883 switch (StorageClassSpec) {
4884 case DeclSpec::SCS_unspecified: return SC_None;
4885 case DeclSpec::SCS_extern:
4886 if (DS.isExternInLinkageSpec())
4887 return SC_None;
4888 return SC_Extern;
4889 case DeclSpec::SCS_static: return SC_Static;
4890 case DeclSpec::SCS_auto: return SC_Auto;
4891 case DeclSpec::SCS_register: return SC_Register;
4892 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4893 // Illegal SCSs map to None: error reporting is up to the caller.
4894 case DeclSpec::SCS_mutable: // Fall through.
4895 case DeclSpec::SCS_typedef: return SC_None;
4896 }
4897 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4897)
;
4898}
4899
4900static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4901 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4901, __PRETTY_FUNCTION__))
;
4902
4903 for (const auto *I : Record->decls()) {
4904 const auto *FD = dyn_cast<FieldDecl>(I);
4905 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4906 FD = IFD->getAnonField();
4907 if (FD && FD->hasInClassInitializer())
4908 return FD->getLocation();
4909 }
4910
4911 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 4911)
;
4912}
4913
4914static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4915 SourceLocation DefaultInitLoc) {
4916 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4917 return;
4918
4919 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4920 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4921}
4922
4923static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4924 CXXRecordDecl *AnonUnion) {
4925 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4926 return;
4927
4928 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4929}
4930
4931/// BuildAnonymousStructOrUnion - Handle the declaration of an
4932/// anonymous structure or union. Anonymous unions are a C++ feature
4933/// (C++ [class.union]) and a C11 feature; anonymous structures
4934/// are a C11 feature and GNU C++ extension.
4935Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4936 AccessSpecifier AS,
4937 RecordDecl *Record,
4938 const PrintingPolicy &Policy) {
4939 DeclContext *Owner = Record->getDeclContext();
4940
4941 // Diagnose whether this anonymous struct/union is an extension.
4942 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4943 Diag(Record->getLocation(), diag::ext_anonymous_union);
4944 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4945 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4946 else if (!Record->isUnion() && !getLangOpts().C11)
4947 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4948
4949 // C and C++ require different kinds of checks for anonymous
4950 // structs/unions.
4951 bool Invalid = false;
4952 if (getLangOpts().CPlusPlus) {
4953 const char *PrevSpec = nullptr;
4954 if (Record->isUnion()) {
4955 // C++ [class.union]p6:
4956 // C++17 [class.union.anon]p2:
4957 // Anonymous unions declared in a named namespace or in the
4958 // global namespace shall be declared static.
4959 unsigned DiagID;
4960 DeclContext *OwnerScope = Owner->getRedeclContext();
4961 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4962 (OwnerScope->isTranslationUnit() ||
4963 (OwnerScope->isNamespace() &&
4964 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4965 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4966 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4967
4968 // Recover by adding 'static'.
4969 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4970 PrevSpec, DiagID, Policy);
4971 }
4972 // C++ [class.union]p6:
4973 // A storage class is not allowed in a declaration of an
4974 // anonymous union in a class scope.
4975 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4976 isa<RecordDecl>(Owner)) {
4977 Diag(DS.getStorageClassSpecLoc(),
4978 diag::err_anonymous_union_with_storage_spec)
4979 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4980
4981 // Recover by removing the storage specifier.
4982 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4983 SourceLocation(),
4984 PrevSpec, DiagID, Context.getPrintingPolicy());
4985 }
4986 }
4987
4988 // Ignore const/volatile/restrict qualifiers.
4989 if (DS.getTypeQualifiers()) {
4990 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4991 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4992 << Record->isUnion() << "const"
4993 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4994 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4995 Diag(DS.getVolatileSpecLoc(),
4996 diag::ext_anonymous_struct_union_qualified)
4997 << Record->isUnion() << "volatile"
4998 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4999 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5000 Diag(DS.getRestrictSpecLoc(),
5001 diag::ext_anonymous_struct_union_qualified)
5002 << Record->isUnion() << "restrict"
5003 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5004 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5005 Diag(DS.getAtomicSpecLoc(),
5006 diag::ext_anonymous_struct_union_qualified)
5007 << Record->isUnion() << "_Atomic"
5008 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5009 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5010 Diag(DS.getUnalignedSpecLoc(),
5011 diag::ext_anonymous_struct_union_qualified)
5012 << Record->isUnion() << "__unaligned"
5013 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5014
5015 DS.ClearTypeQualifiers();
5016 }
5017
5018 // C++ [class.union]p2:
5019 // The member-specification of an anonymous union shall only
5020 // define non-static data members. [Note: nested types and
5021 // functions cannot be declared within an anonymous union. ]
5022 for (auto *Mem : Record->decls()) {
5023 // Ignore invalid declarations; we already diagnosed them.
5024 if (Mem->isInvalidDecl())
5025 continue;
5026
5027 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5028 // C++ [class.union]p3:
5029 // An anonymous union shall not have private or protected
5030 // members (clause 11).
5031 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 5031, __PRETTY_FUNCTION__))
;
5032 if (FD->getAccess() != AS_public) {
5033 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5034 << Record->isUnion() << (FD->getAccess() == AS_protected);
5035 Invalid = true;
5036 }
5037
5038 // C++ [class.union]p1
5039 // An object of a class with a non-trivial constructor, a non-trivial
5040 // copy constructor, a non-trivial destructor, or a non-trivial copy
5041 // assignment operator cannot be a member of a union, nor can an
5042 // array of such objects.
5043 if (CheckNontrivialField(FD))
5044 Invalid = true;
5045 } else if (Mem->isImplicit()) {
5046 // Any implicit members are fine.
5047 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5048 // This is a type that showed up in an
5049 // elaborated-type-specifier inside the anonymous struct or
5050 // union, but which actually declares a type outside of the
5051 // anonymous struct or union. It's okay.
5052 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5053 if (!MemRecord->isAnonymousStructOrUnion() &&
5054 MemRecord->getDeclName()) {
5055 // Visual C++ allows type definition in anonymous struct or union.
5056 if (getLangOpts().MicrosoftExt)
5057 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5058 << Record->isUnion();
5059 else {
5060 // This is a nested type declaration.
5061 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5062 << Record->isUnion();
5063 Invalid = true;
5064 }
5065 } else {
5066 // This is an anonymous type definition within another anonymous type.
5067 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5068 // not part of standard C++.
5069 Diag(MemRecord->getLocation(),
5070 diag::ext_anonymous_record_with_anonymous_type)
5071 << Record->isUnion();
5072 }
5073 } else if (isa<AccessSpecDecl>(Mem)) {
5074 // Any access specifier is fine.
5075 } else if (isa<StaticAssertDecl>(Mem)) {
5076 // In C++1z, static_assert declarations are also fine.
5077 } else {
5078 // We have something that isn't a non-static data
5079 // member. Complain about it.
5080 unsigned DK = diag::err_anonymous_record_bad_member;
5081 if (isa<TypeDecl>(Mem))
5082 DK = diag::err_anonymous_record_with_type;
5083 else if (isa<FunctionDecl>(Mem))
5084 DK = diag::err_anonymous_record_with_function;
5085 else if (isa<VarDecl>(Mem))
5086 DK = diag::err_anonymous_record_with_static;
5087
5088 // Visual C++ allows type definition in anonymous struct or union.
5089 if (getLangOpts().MicrosoftExt &&
5090 DK == diag::err_anonymous_record_with_type)
5091 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5092 << Record->isUnion();
5093 else {
5094 Diag(Mem->getLocation(), DK) << Record->isUnion();
5095 Invalid = true;
5096 }
5097 }
5098 }
5099
5100 // C++11 [class.union]p8 (DR1460):
5101 // At most one variant member of a union may have a
5102 // brace-or-equal-initializer.
5103 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5104 Owner->isRecord())
5105 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5106 cast<CXXRecordDecl>(Record));
5107 }
5108
5109 if (!Record->isUnion() && !Owner->isRecord()) {
5110 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5111 << getLangOpts().CPlusPlus;
5112 Invalid = true;
5113 }
5114
5115 // C++ [dcl.dcl]p3:
5116 // [If there are no declarators], and except for the declaration of an
5117 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5118 // names into the program
5119 // C++ [class.mem]p2:
5120 // each such member-declaration shall either declare at least one member
5121 // name of the class or declare at least one unnamed bit-field
5122 //
5123 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5124 if (getLangOpts().CPlusPlus && Record->field_empty())
5125 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5126
5127 // Mock up a declarator.
5128 Declarator Dc(DS, DeclaratorContext::MemberContext);
5129 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5130 assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 5130, __PRETTY_FUNCTION__))
;
5131
5132 // Create a declaration for this anonymous struct/union.
5133 NamedDecl *Anon = nullptr;
5134 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5135 Anon = FieldDecl::Create(
5136 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5137 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5138 /*BitWidth=*/nullptr, /*Mutable=*/false,
5139 /*InitStyle=*/ICIS_NoInit);
5140 Anon->setAccess(AS);
5141 ProcessDeclAttributes(S, Anon, Dc);
5142
5143 if (getLangOpts().CPlusPlus)
5144 FieldCollector->Add(cast<FieldDecl>(Anon));
5145 } else {
5146 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5147 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5148 if (SCSpec == DeclSpec::SCS_mutable) {
5149 // mutable can only appear on non-static class members, so it's always
5150 // an error here
5151 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5152 Invalid = true;
5153 SC = SC_None;
5154 }
5155
5156 assert(DS.getAttributes().empty() && "No attribute expected")((DS.getAttributes().empty() && "No attribute expected"
) ? static_cast<void> (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 5156, __PRETTY_FUNCTION__))
;
5157 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5158 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5159 Context.getTypeDeclType(Record), TInfo, SC);
5160
5161 // Default-initialize the implicit variable. This initialization will be
5162 // trivial in almost all cases, except if a union member has an in-class
5163 // initializer:
5164 // union { int n = 0; };
5165 ActOnUninitializedDecl(Anon);
5166 }
5167 Anon->setImplicit();
5168
5169 // Mark this as an anonymous struct/union type.
5170 Record->setAnonymousStructOrUnion(true);
5171
5172 // Add the anonymous struct/union object to the current
5173 // context. We'll be referencing this object when we refer to one of
5174 // its members.
5175 Owner->addDecl(Anon);
5176
5177 // Inject the members of the anonymous struct/union into the owning
5178 // context and into the identifier resolver chain for name lookup
5179 // purposes.
5180 SmallVector<NamedDecl*, 2> Chain;
5181 Chain.push_back(Anon);
5182
5183 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5184 Invalid = true;
5185
5186 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5187 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5188 MangleNumberingContext *MCtx;
5189 Decl *ManglingContextDecl;
5190 std::tie(MCtx, ManglingContextDecl) =
5191 getCurrentMangleNumberContext(NewVD->getDeclContext());
5192 if (MCtx) {
5193 Context.setManglingNumber(
5194 NewVD, MCtx->getManglingNumber(
5195 NewVD, getMSManglingNumber(getLangOpts(), S)));
5196 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5197 }
5198 }
5199 }
5200
5201 if (Invalid)
5202 Anon->setInvalidDecl();
5203
5204 return Anon;
5205}
5206
5207/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5208/// Microsoft C anonymous structure.
5209/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5210/// Example:
5211///
5212/// struct A { int a; };
5213/// struct B { struct A; int b; };
5214///
5215/// void foo() {
5216/// B var;
5217/// var.a = 3;
5218/// }
5219///
5220Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5221 RecordDecl *Record) {
5222 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 5222, __PRETTY_FUNCTION__))
;
5223
5224 // Mock up a declarator.
5225 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5226 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5227 assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 5227, __PRETTY_FUNCTION__))
;
5228
5229 auto *ParentDecl = cast<RecordDecl>(CurContext);
5230 QualType RecTy = Context.getTypeDeclType(Record);
5231
5232 // Create a declaration for this anonymous struct.
5233 NamedDecl *Anon =
5234 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5235 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5236 /*BitWidth=*/nullptr, /*Mutable=*/false,
5237 /*InitStyle=*/ICIS_NoInit);
5238 Anon->setImplicit();
5239
5240 // Add the anonymous struct object to the current context.
5241 CurContext->addDecl(Anon);
5242
5243 // Inject the members of the anonymous struct into the current
5244 // context and into the identifier resolver chain for name lookup
5245 // purposes.
5246 SmallVector<NamedDecl*, 2> Chain;
5247 Chain.push_back(Anon);
5248
5249 RecordDecl *RecordDef = Record->getDefinition();
5250 if (RequireCompleteType(Anon->getLocation(), RecTy,
5251 diag::err_field_incomplete) ||
5252 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5253 AS_none, Chain)) {
5254 Anon->setInvalidDecl();
5255 ParentDecl->setInvalidDecl();
5256 }
5257
5258 return Anon;
5259}
5260
5261/// GetNameForDeclarator - Determine the full declaration name for the
5262/// given Declarator.
5263DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5264 return GetNameFromUnqualifiedId(D.getName());
5265}
5266
5267/// Retrieves the declaration name from a parsed unqualified-id.
5268DeclarationNameInfo
5269Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5270 DeclarationNameInfo NameInfo;
5271 NameInfo.setLoc(Name.StartLocation);
5272
5273 switch (Name.getKind()) {
5274
5275 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5276 case UnqualifiedIdKind::IK_Identifier:
5277 NameInfo.setName(Name.Identifier);
5278 return NameInfo;
5279
5280 case UnqualifiedIdKind::IK_DeductionGuideName: {
5281 // C++ [temp.deduct.guide]p3:
5282 // The simple-template-id shall name a class template specialization.
5283 // The template-name shall be the same identifier as the template-name
5284 // of the simple-template-id.
5285 // These together intend to imply that the template-name shall name a
5286 // class template.
5287 // FIXME: template<typename T> struct X {};
5288 // template<typename T> using Y = X<T>;
5289 // Y(int) -> Y<int>;
5290 // satisfies these rules but does not name a class template.
5291 TemplateName TN = Name.TemplateName.get().get();
5292 auto *Template = TN.getAsTemplateDecl();
5293 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5294 Diag(Name.StartLocation,
5295 diag::err_deduction_guide_name_not_class_template)
5296 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5297 if (Template)
5298 Diag(Template->getLocation(), diag::note_template_decl_here);
5299 return DeclarationNameInfo();
5300 }
5301
5302 NameInfo.setName(
5303 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5304 return NameInfo;
5305 }
5306
5307 case UnqualifiedIdKind::IK_OperatorFunctionId:
5308 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5309 Name.OperatorFunctionId.Operator));
5310 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5311 = Name.OperatorFunctionId.SymbolLocations[0];
5312 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5313 = Name.EndLocation.getRawEncoding();
5314 return NameInfo;
5315
5316 case UnqualifiedIdKind::IK_LiteralOperatorId:
5317 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5318 Name.Identifier));
5319 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5320 return NameInfo;
5321
5322 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5323 TypeSourceInfo *TInfo;
5324 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5325 if (Ty.isNull())
5326 return DeclarationNameInfo();
5327 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5328 Context.getCanonicalType(Ty)));
5329 NameInfo.setNamedTypeInfo(TInfo);
5330 return NameInfo;
5331 }
5332
5333 case UnqualifiedIdKind::IK_ConstructorName: {
5334 TypeSourceInfo *TInfo;
5335 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5336 if (Ty.isNull())
5337 return DeclarationNameInfo();
5338 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5339 Context.getCanonicalType(Ty)));
5340 NameInfo.setNamedTypeInfo(TInfo);
5341 return NameInfo;
5342 }
5343
5344 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5345 // In well-formed code, we can only have a constructor
5346 // template-id that refers to the current context, so go there
5347 // to find the actual type being constructed.
5348 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5349 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5350 return DeclarationNameInfo();
5351
5352 // Determine the type of the class being constructed.
5353 QualType CurClassType = Context.getTypeDeclType(CurClass);
5354
5355 // FIXME: Check two things: that the template-id names the same type as
5356 // CurClassType, and that the template-id does not occur when the name
5357 // was qualified.
5358
5359 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5360 Context.getCanonicalType(CurClassType)));
5361 // FIXME: should we retrieve TypeSourceInfo?
5362 NameInfo.setNamedTypeInfo(nullptr);
5363 return NameInfo;
5364 }
5365
5366 case UnqualifiedIdKind::IK_DestructorName: {
5367 TypeSourceInfo *TInfo;
5368 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5369 if (Ty.isNull())
5370 return DeclarationNameInfo();
5371 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5372 Context.getCanonicalType(Ty)));
5373 NameInfo.setNamedTypeInfo(TInfo);
5374 return NameInfo;
5375 }
5376
5377 case UnqualifiedIdKind::IK_TemplateId: {
5378 TemplateName TName = Name.TemplateId->Template.get();
5379 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5380 return Context.getNameForTemplate(TName, TNameLoc);
5381 }
5382
5383 } // switch (Name.getKind())
5384
5385 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 5385)
;
5386}
5387
5388static QualType getCoreType(QualType Ty) {
5389 do {
5390 if (Ty->isPointerType() || Ty->isReferenceType())
5391 Ty = Ty->getPointeeType();
5392 else if (Ty->isArrayType())
5393 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5394 else
5395 return Ty.withoutLocalFastQualifiers();
5396 } while (true);
5397}
5398
5399/// hasSimilarParameters - Determine whether the C++ functions Declaration
5400/// and Definition have "nearly" matching parameters. This heuristic is
5401/// used to improve diagnostics in the case where an out-of-line function
5402/// definition doesn't match any declaration within the class or namespace.
5403/// Also sets Params to the list of indices to the parameters that differ
5404/// between the declaration and the definition. If hasSimilarParameters
5405/// returns true and Params is empty, then all of the parameters match.
5406static bool hasSimilarParameters(ASTContext &Context,
5407 FunctionDecl *Declaration,
5408 FunctionDecl *Definition,
5409 SmallVectorImpl<unsigned> &Params) {
5410 Params.clear();
5411 if (Declaration->param_size() != Definition->param_size())
5412 return false;
5413 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5414 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5415 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5416
5417 // The parameter types are identical
5418 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5419 continue;
5420
5421 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5422 QualType DefParamBaseTy = getCoreType(DefParamTy);
5423 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5424 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5425
5426 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5427 (DeclTyName && DeclTyName == DefTyName))
5428 Params.push_back(Idx);
5429 else // The two parameters aren't even close
5430 return false;
5431 }
5432
5433 return true;
5434}
5435
5436/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5437/// declarator needs to be rebuilt in the current instantiation.
5438/// Any bits of declarator which appear before the name are valid for
5439/// consideration here. That's specifically the type in the decl spec
5440/// and the base type in any member-pointer chunks.
5441static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5442 DeclarationName Name) {
5443 // The types we specifically need to rebuild are:
5444 // - typenames, typeofs, and decltypes
5445 // - types which will become injected class names
5446 // Of course, we also need to rebuild any type referencing such a
5447 // type. It's safest to just say "dependent", but we call out a
5448 // few cases here.
5449
5450 DeclSpec &DS = D.getMutableDeclSpec();
5451 switch (DS.getTypeSpecType()) {
5452 case DeclSpec::TST_typename:
5453 case DeclSpec::TST_typeofType:
5454 case DeclSpec::TST_underlyingType:
5455 case DeclSpec::TST_atomic: {
5456 // Grab the type from the parser.
5457 TypeSourceInfo *TSI = nullptr;
5458 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5459 if (T.isNull() || !T->isDependentType()) break;
5460
5461 // Make sure there's a type source info. This isn't really much
5462 // of a waste; most dependent types should have type source info
5463 // attached already.
5464 if (!TSI)
5465 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5466
5467 // Rebuild the type in the current instantiation.
5468 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5469 if (!TSI) return true;
5470
5471 // Store the new type back in the decl spec.
5472 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5473 DS.UpdateTypeRep(LocType);
5474 break;
5475 }
5476
5477 case DeclSpec::TST_decltype:
5478 case DeclSpec::TST_typeofExpr: {
5479 Expr *E = DS.getRepAsExpr();
5480 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5481 if (Result.isInvalid()) return true;
5482 DS.UpdateExprRep(Result.get());
5483 break;
5484 }
5485
5486 default:
5487 // Nothing to do for these decl specs.
5488 break;
5489 }
5490
5491 // It doesn't matter what order we do this in.
5492 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5493 DeclaratorChunk &Chunk = D.getTypeObject(I);
5494
5495 // The only type information in the declarator which can come
5496 // before the declaration name is the base type of a member
5497 // pointer.
5498 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5499 continue;
5500
5501 // Rebuild the scope specifier in-place.
5502 CXXScopeSpec &SS = Chunk.Mem.Scope();
5503 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5504 return true;
5505 }
5506
5507 return false;
5508}
5509
5510Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5511 D.setFunctionDefinitionKind(FDK_Declaration);
5512 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5513
5514 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5515 Dcl && Dcl->getDeclContext()->isFileContext())
5516 Dcl->setTopLevelDeclInObjCContainer();
5517
5518 if (getLangOpts().OpenCL)
5519 setCurrentOpenCLExtensionForDecl(Dcl);
5520
5521 return Dcl;
5522}
5523
5524/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5525/// If T is the name of a class, then each of the following shall have a
5526/// name different from T:
5527/// - every static data member of class T;
5528/// - every member function of class T
5529/// - every member of class T that is itself a type;
5530/// \returns true if the declaration name violates these rules.
5531bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5532 DeclarationNameInfo NameInfo) {
5533 DeclarationName Name = NameInfo.getName();
5534
5535 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5536 while (Record && Record->isAnonymousStructOrUnion())
5537 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5538 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5539 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5540 return true;
5541 }
5542
5543 return false;
5544}
5545
5546/// Diagnose a declaration whose declarator-id has the given
5547/// nested-name-specifier.
5548///
5549/// \param SS The nested-name-specifier of the declarator-id.
5550///
5551/// \param DC The declaration context to which the nested-name-specifier
5552/// resolves.
5553///
5554/// \param Name The name of the entity being declared.
5555///
5556/// \param Loc The location of the name of the entity being declared.
5557///
5558/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5559/// we're declaring an explicit / partial specialization / instantiation.
5560///
5561/// \returns true if we cannot safely recover from this error, false otherwise.
5562bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5563 DeclarationName Name,
5564 SourceLocation Loc, bool IsTemplateId) {
5565 DeclContext *Cur = CurContext;
5566 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5567 Cur = Cur->getParent();
5568
5569 // If the user provided a superfluous scope specifier that refers back to the
5570 // class in which the entity is already declared, diagnose and ignore it.
5571 //
5572 // class X {
5573 // void X::f();
5574 // };
5575 //
5576 // Note, it was once ill-formed to give redundant qualification in all
5577 // contexts, but that rule was removed by DR482.
5578 if (Cur->Equals(DC)) {
5579 if (Cur->isRecord()) {
5580 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5581 : diag::err_member_extra_qualification)
5582 << Name << FixItHint::CreateRemoval(SS.getRange());
5583 SS.clear();
5584 } else {
5585 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5586 }
5587 return false;
5588 }
5589
5590 // Check whether the qualifying scope encloses the scope of the original
5591 // declaration. For a template-id, we perform the checks in
5592 // CheckTemplateSpecializationScope.
5593 if (!Cur->Encloses(DC) && !IsTemplateId) {
5594 if (Cur->isRecord())
5595 Diag(Loc, diag::err_member_qualification)
5596 << Name << SS.getRange();
5597 else if (isa<TranslationUnitDecl>(DC))
5598 Diag(Loc, diag::err_invalid_declarator_global_scope)
5599 << Name << SS.getRange();
5600 else if (isa<FunctionDecl>(Cur))
5601 Diag(Loc, diag::err_invalid_declarator_in_function)
5602 << Name << SS.getRange();
5603 else if (isa<BlockDecl>(Cur))
5604 Diag(Loc, diag::err_invalid_declarator_in_block)
5605 << Name << SS.getRange();
5606 else
5607 Diag(Loc, diag::err_invalid_declarator_scope)
5608 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5609
5610 return true;
5611 }
5612
5613 if (Cur->isRecord()) {
5614 // Cannot qualify members within a class.
5615 Diag(Loc, diag::err_member_qualification)
5616 << Name << SS.getRange();
5617 SS.clear();
5618
5619 // C++ constructors and destructors with incorrect scopes can break
5620 // our AST invariants by having the wrong underlying types. If
5621 // that's the case, then drop this declaration entirely.
5622 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5623 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5624 !Context.hasSameType(Name.getCXXNameType(),
5625 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5626 return true;
5627
5628 return false;
5629 }
5630
5631 // C++11 [dcl.meaning]p1:
5632 // [...] "The nested-name-specifier of the qualified declarator-id shall
5633 // not begin with a decltype-specifer"
5634 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5635 while (SpecLoc.getPrefix())
5636 SpecLoc = SpecLoc.getPrefix();
5637 if (dyn_cast_or_null<DecltypeType>(
5638 SpecLoc.getNestedNameSpecifier()->getAsType()))
5639 Diag(Loc, diag::err_decltype_in_declarator)
5640 << SpecLoc.getTypeLoc().getSourceRange();
5641
5642 return false;
5643}
5644
5645NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5646 MultiTemplateParamsArg TemplateParamLists) {
5647 // TODO: consider using NameInfo for diagnostic.
5648 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5649 DeclarationName Name = NameInfo.getName();
5650
5651 // All of these full declarators require an identifier. If it doesn't have
5652 // one, the ParsedFreeStandingDeclSpec action should be used.
5653 if (D.isDecompositionDeclarator()) {
5654 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5655 } else if (!Name) {
5656 if (!D.isInvalidType()) // Reject this if we think it is valid.
5657 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5658 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5659 return nullptr;
5660 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5661 return nullptr;
5662
5663 // The scope passed in may not be a decl scope. Zip up the scope tree until
5664 // we find one that is.
5665 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5666 (S->getFlags() & Scope::TemplateParamScope) != 0)
5667 S = S->getParent();
5668
5669 DeclContext *DC = CurContext;
5670 if (D.getCXXScopeSpec().isInvalid())
5671 D.setInvalidType();
5672 else if (D.getCXXScopeSpec().isSet()) {
5673 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5674 UPPC_DeclarationQualifier))
5675 return nullptr;
5676
5677 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5678 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5679 if (!DC || isa<EnumDecl>(DC)) {
5680 // If we could not compute the declaration context, it's because the
5681 // declaration context is dependent but does not refer to a class,
5682 // class template, or class template partial specialization. Complain
5683 // and return early, to avoid the coming semantic disaster.
5684 Diag(D.getIdentifierLoc(),
5685 diag::err_template_qualified_declarator_no_match)
5686 << D.getCXXScopeSpec().getScopeRep()
5687 << D.getCXXScopeSpec().getRange();
5688 return nullptr;
5689 }
5690 bool IsDependentContext = DC->isDependentContext();
5691
5692 if (!IsDependentContext &&
5693 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5694 return nullptr;
5695
5696 // If a class is incomplete, do not parse entities inside it.
5697 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5698 Diag(D.getIdentifierLoc(),
5699 diag::err_member_def_undefined_record)
5700 << Name << DC << D.getCXXScopeSpec().getRange();
5701 return nullptr;
5702 }
5703 if (!D.getDeclSpec().isFriendSpecified()) {
5704 if (diagnoseQualifiedDeclaration(
5705 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5706 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5707 if (DC->isRecord())
5708 return nullptr;
5709
5710 D.setInvalidType();
5711 }
5712 }
5713
5714 // Check whether we need to rebuild the type of the given
5715 // declaration in the current instantiation.
5716 if (EnteringContext && IsDependentContext &&
5717 TemplateParamLists.size() != 0) {
5718 ContextRAII SavedContext(*this, DC);
5719 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5720 D.setInvalidType();
5721 }
5722 }
5723
5724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5725 QualType R = TInfo->getType();
5726
5727 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5728 UPPC_DeclarationType))
5729 D.setInvalidType();
5730
5731 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5732 forRedeclarationInCurContext());
5733
5734 // See if this is a redefinition of a variable in the same scope.
5735 if (!D.getCXXScopeSpec().isSet()) {
5736 bool IsLinkageLookup = false;
5737 bool CreateBuiltins = false;
5738
5739 // If the declaration we're planning to build will be a function
5740 // or object with linkage, then look for another declaration with
5741 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5742 //
5743 // If the declaration we're planning to build will be declared with
5744 // external linkage in the translation unit, create any builtin with
5745 // the same name.
5746 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5747 /* Do nothing*/;
5748 else if (CurContext->isFunctionOrMethod() &&
5749 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5750 R->isFunctionType())) {
5751 IsLinkageLookup = true;
5752 CreateBuiltins =
5753 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5754 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5755 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5756 CreateBuiltins = true;
5757
5758 if (IsLinkageLookup) {
5759 Previous.clear(LookupRedeclarationWithLinkage);
5760 Previous.setRedeclarationKind(ForExternalRedeclaration);
5761 }
5762
5763 LookupName(Previous, S, CreateBuiltins);
5764 } else { // Something like "int foo::x;"
5765 LookupQualifiedName(Previous, DC);
5766
5767 // C++ [dcl.meaning]p1:
5768 // When the declarator-id is qualified, the declaration shall refer to a
5769 // previously declared member of the class or namespace to which the
5770 // qualifier refers (or, in the case of a namespace, of an element of the
5771 // inline namespace set of that namespace (7.3.1)) or to a specialization
5772 // thereof; [...]
5773 //
5774 // Note that we already checked the context above, and that we do not have
5775 // enough information to make sure that Previous contains the declaration
5776 // we want to match. For example, given:
5777 //
5778 // class X {
5779 // void f();
5780 // void f(float);
5781 // };
5782 //
5783 // void X::f(int) { } // ill-formed
5784 //
5785 // In this case, Previous will point to the overload set
5786 // containing the two f's declared in X, but neither of them
5787 // matches.
5788
5789 // C++ [dcl.meaning]p1:
5790 // [...] the member shall not merely have been introduced by a
5791 // using-declaration in the scope of the class or namespace nominated by
5792 // the nested-name-specifier of the declarator-id.
5793 RemoveUsingDecls(Previous);
5794 }
5795
5796 if (Previous.isSingleResult() &&
5797 Previous.getFoundDecl()->isTemplateParameter()) {
5798 // Maybe we will complain about the shadowed template parameter.
5799 if (!D.isInvalidType())
5800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5801 Previous.getFoundDecl());
5802
5803 // Just pretend that we didn't see the previous declaration.
5804 Previous.clear();
5805 }
5806
5807 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5808 // Forget that the previous declaration is the injected-class-name.
5809 Previous.clear();
5810
5811 // In C++, the previous declaration we find might be a tag type
5812 // (class or enum). In this case, the new declaration will hide the
5813 // tag type. Note that this applies to functions, function templates, and
5814 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5815 if (Previous.isSingleTagDecl() &&
5816 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5817 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5818 Previous.clear();
5819
5820 // Check that there are no default arguments other than in the parameters
5821 // of a function declaration (C++ only).
5822 if (getLangOpts().CPlusPlus)
5823 CheckExtraCXXDefaultArguments(D);
5824
5825 NamedDecl *New;
5826
5827 bool AddToScope = true;
5828 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5829 if (TemplateParamLists.size()) {
5830 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5831 return nullptr;
5832 }
5833
5834 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5835 } else if (R->isFunctionType()) {
5836 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5837 TemplateParamLists,
5838 AddToScope);
5839 } else {
5840 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5841 AddToScope);
5842 }
5843
5844 if (!New)
5845 return nullptr;
5846
5847 // If this has an identifier and is not a function template specialization,
5848 // add it to the scope stack.
5849 if (New->getDeclName() && AddToScope)
5850 PushOnScopeChains(New, S);
5851
5852 if (isInOpenMPDeclareTargetContext())
5853 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5854
5855 return New;
5856}
5857
5858/// Helper method to turn variable array types into constant array
5859/// types in certain situations which would otherwise be errors (for
5860/// GCC compatibility).
5861static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5862 ASTContext &Context,
5863 bool &SizeIsNegative,
5864 llvm::APSInt &Oversized) {
5865 // This method tries to turn a variable array into a constant
5866 // array even when the size isn't an ICE. This is necessary
5867 // for compatibility with code that depends on gcc's buggy
5868 // constant expression folding, like struct {char x[(int)(char*)2];}
5869 SizeIsNegative = false;
5870 Oversized = 0;
5871
5872 if (T->isDependentType())
5873 return QualType();
5874
5875 QualifierCollector Qs;
5876 const Type *Ty = Qs.strip(T);
5877
5878 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5879 QualType Pointee = PTy->getPointeeType();
5880 QualType FixedType =
5881 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5882 Oversized);
5883 if (FixedType.isNull()) return FixedType;
5884 FixedType = Context.getPointerType(FixedType);
5885 return Qs.apply(Context, FixedType);
5886 }
5887 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5888 QualType Inner = PTy->getInnerType();
5889 QualType FixedType =
5890 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5891 Oversized);
5892 if (FixedType.isNull()) return FixedType;
5893 FixedType = Context.getParenType(FixedType);
5894 return Qs.apply(Context, FixedType);
5895 }
5896
5897 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5898 if (!VLATy)
5899 return QualType();
5900 // FIXME: We should probably handle this case
5901 if (VLATy->getElementType()->isVariablyModifiedType())
5902 return QualType();
5903
5904 Expr::EvalResult Result;
5905 if (!VLATy->getSizeExpr() ||
5906 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5907 return QualType();
5908
5909 llvm::APSInt Res = Result.Val.getInt();
5910
5911 // Check whether the array size is negative.
5912 if (Res.isSigned() && Res.isNegative()) {
5913 SizeIsNegative = true;
5914 return QualType();
5915 }
5916
5917 // Check whether the array is too large to be addressed.
5918 unsigned ActiveSizeBits
5919 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5920 Res);
5921 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5922 Oversized = Res;
5923 return QualType();
5924 }
5925
5926 return Context.getConstantArrayType(
5927 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5928}
5929
5930static void
5931FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5932 SrcTL = SrcTL.getUnqualifiedLoc();
5933 DstTL = DstTL.getUnqualifiedLoc();
5934 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5935 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5936 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5937 DstPTL.getPointeeLoc());
5938 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5939 return;
5940 }
5941 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5942 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5943 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5944 DstPTL.getInnerLoc());
5945 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5946 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5947 return;
5948 }
5949 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5950 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5951 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5952 TypeLoc DstElemTL = DstATL.getElementLoc();
5953 DstElemTL.initializeFullCopy(SrcElemTL);
5954 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5955 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5956 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5957}
5958
5959/// Helper method to turn variable array types into constant array
5960/// types in certain situations which would otherwise be errors (for
5961/// GCC compatibility).
5962static TypeSourceInfo*
5963TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5964 ASTContext &Context,
5965 bool &SizeIsNegative,
5966 llvm::APSInt &Oversized) {
5967 QualType FixedTy
5968 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5969 SizeIsNegative, Oversized);
5970 if (FixedTy.isNull())
5971 return nullptr;
5972 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5973 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5974 FixedTInfo->getTypeLoc());
5975 return FixedTInfo;
5976}
5977
5978/// Register the given locally-scoped extern "C" declaration so
5979/// that it can be found later for redeclarations. We include any extern "C"
5980/// declaration that is not visible in the translation unit here, not just
5981/// function-scope declarations.
5982void
5983Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5984 if (!getLangOpts().CPlusPlus &&
5985 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5986 // Don't need to track declarations in the TU in C.
5987 return;
5988
5989 // Note that we have a locally-scoped external with this name.
5990 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5991}
5992
5993NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5994 // FIXME: We can have multiple results via __attribute__((overloadable)).
5995 auto Result = Context.getExternCContextDecl()->lookup(Name);
5996 return Result.empty() ? nullptr : *Result.begin();
5997}
5998
5999/// Diagnose function specifiers on a declaration of an identifier that
6000/// does not identify a function.
6001void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6002 // FIXME: We should probably indicate the identifier in question to avoid
6003 // confusion for constructs like "virtual int a(), b;"
6004 if (DS.isVirtualSpecified())
6005 Diag(DS.getVirtualSpecLoc(),
6006 diag::err_virtual_non_function);
6007
6008 if (DS.hasExplicitSpecifier())
6009 Diag(DS.getExplicitSpecLoc(),
6010 diag::err_explicit_non_function);
6011
6012 if (DS.isNoreturnSpecified())
6013 Diag(DS.getNoreturnSpecLoc(),
6014 diag::err_noreturn_non_function);
6015}
6016
6017NamedDecl*
6018Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6019 TypeSourceInfo *TInfo, LookupResult &Previous) {
6020 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6021 if (D.getCXXScopeSpec().isSet()) {
6022 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6023 << D.getCXXScopeSpec().getRange();
6024 D.setInvalidType();
6025 // Pretend we didn't see the scope specifier.
6026 DC = CurContext;
6027 Previous.clear();
6028 }
6029
6030 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6031
6032 if (D.getDeclSpec().isInlineSpecified())
6033 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6034 << getLangOpts().CPlusPlus17;
6035 if (D.getDeclSpec().hasConstexprSpecifier())
6036 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6037 << 1 << D.getDeclSpec().getConstexprSpecifier();
6038
6039 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6040 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6041 Diag(D.getName().StartLocation,
6042 diag::err_deduction_guide_invalid_specifier)
6043 << "typedef";
6044 else
6045 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6046 << D.getName().getSourceRange();
6047 return nullptr;
6048 }
6049
6050 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6051 if (!NewTD) return nullptr;
6052
6053 // Handle attributes prior to checking for duplicates in MergeVarDecl
6054 ProcessDeclAttributes(S, NewTD, D);
6055
6056 CheckTypedefForVariablyModifiedType(S, NewTD);
6057
6058 bool Redeclaration = D.isRedeclaration();
6059 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6060 D.setRedeclaration(Redeclaration);
6061 return ND;
6062}
6063
6064void
6065Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6066 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6067 // then it shall have block scope.
6068 // Note that variably modified types must be fixed before merging the decl so
6069 // that redeclarations will match.
6070 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6071 QualType T = TInfo->getType();
6072 if (T->isVariablyModifiedType()) {
6073 setFunctionHasBranchProtectedScope();
6074
6075 if (S->getFnParent() == nullptr) {
6076 bool SizeIsNegative;
6077 llvm::APSInt Oversized;
6078 TypeSourceInfo *FixedTInfo =
6079 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6080 SizeIsNegative,
6081 Oversized);
6082 if (FixedTInfo) {
6083 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6084 NewTD->setTypeSourceInfo(FixedTInfo);
6085 } else {
6086 if (SizeIsNegative)
6087 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6088 else if (T->isVariableArrayType())
6089 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6090 else if (Oversized.getBoolValue())
6091 Diag(NewTD->getLocation(), diag::err_array_too_large)
6092 << Oversized.toString(10);
6093 else
6094 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6095 NewTD->setInvalidDecl();
6096 }
6097 }
6098 }
6099}
6100
6101/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6102/// declares a typedef-name, either using the 'typedef' type specifier or via
6103/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6104NamedDecl*
6105Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6106 LookupResult &Previous, bool &Redeclaration) {
6107
6108 // Find the shadowed declaration before filtering for scope.
6109 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6110
6111 // Merge the decl with the existing one if appropriate. If the decl is
6112 // in an outer scope, it isn't the same thing.
6113 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6114 /*AllowInlineNamespace*/false);
6115 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6116 if (!Previous.empty()) {
6117 Redeclaration = true;
6118 MergeTypedefNameDecl(S, NewTD, Previous);
6119 } else {
6120 inferGslPointerAttribute(NewTD);
6121 }
6122
6123 if (ShadowedDecl && !Redeclaration)
6124 CheckShadow(NewTD, ShadowedDecl, Previous);
6125
6126 // If this is the C FILE type, notify the AST context.
6127 if (IdentifierInfo *II = NewTD->getIdentifier())
6128 if (!NewTD->isInvalidDecl() &&
6129 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6130 if (II->isStr("FILE"))
6131 Context.setFILEDecl(NewTD);
6132 else if (II->isStr("jmp_buf"))
6133 Context.setjmp_bufDecl(NewTD);
6134 else if (II->isStr("sigjmp_buf"))
6135 Context.setsigjmp_bufDecl(NewTD);
6136 else if (II->isStr("ucontext_t"))
6137 Context.setucontext_tDecl(NewTD);
6138 }
6139
6140 return NewTD;
6141}
6142
6143/// Determines whether the given declaration is an out-of-scope
6144/// previous declaration.
6145///
6146/// This routine should be invoked when name lookup has found a
6147/// previous declaration (PrevDecl) that is not in the scope where a
6148/// new declaration by the same name is being introduced. If the new
6149/// declaration occurs in a local scope, previous declarations with
6150/// linkage may still be considered previous declarations (C99
6151/// 6.2.2p4-5, C++ [basic.link]p6).
6152///
6153/// \param PrevDecl the previous declaration found by name
6154/// lookup
6155///
6156/// \param DC the context in which the new declaration is being
6157/// declared.
6158///
6159/// \returns true if PrevDecl is an out-of-scope previous declaration
6160/// for a new delcaration with the same name.
6161static bool
6162isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6163 ASTContext &Context) {
6164 if (!PrevDecl)
6165 return false;
6166
6167 if (!PrevDecl->hasLinkage())
6168 return false;
6169
6170 if (Context.getLangOpts().CPlusPlus) {
6171 // C++ [basic.link]p6:
6172 // If there is a visible declaration of an entity with linkage
6173 // having the same name and type, ignoring entities declared
6174 // outside the innermost enclosing namespace scope, the block
6175 // scope declaration declares that same entity and receives the
6176 // linkage of the previous declaration.
6177 DeclContext *OuterContext = DC->getRedeclContext();
6178 if (!OuterContext->isFunctionOrMethod())
6179 // This rule only applies to block-scope declarations.
6180 return false;
6181
6182 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6183 if (PrevOuterContext->isRecord())
6184 // We found a member function: ignore it.
6185 return false;
6186
6187 // Find the innermost enclosing namespace for the new and
6188 // previous declarations.
6189 OuterContext = OuterContext->getEnclosingNamespaceContext();
6190 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6191
6192 // The previous declaration is in a different namespace, so it
6193 // isn't the same function.
6194 if (!OuterContext->Equals(PrevOuterContext))
6195 return false;
6196 }
6197
6198 return true;
6199}
6200
6201static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6202 CXXScopeSpec &SS = D.getCXXScopeSpec();
6203 if (!SS.isSet()) return;
6204 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6205}
6206
6207bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6208 QualType type = decl->getType();
6209 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6210 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6211 // Various kinds of declaration aren't allowed to be __autoreleasing.
6212 unsigned kind = -1U;
6213 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6214 if (var->hasAttr<BlocksAttr>())
6215 kind = 0; // __block
6216 else if (!var->hasLocalStorage())
6217 kind = 1; // global
6218 } else if (isa<ObjCIvarDecl>(decl)) {
6219 kind = 3; // ivar
6220 } else if (isa<FieldDecl>(decl)) {
6221 kind = 2; // field
6222 }
6223
6224 if (kind != -1U) {
6225 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6226 << kind;
6227 }
6228 } else if (lifetime == Qualifiers::OCL_None) {
6229 // Try to infer lifetime.
6230 if (!type->isObjCLifetimeType())
6231 return false;
6232
6233 lifetime = type->getObjCARCImplicitLifetime();
6234 type = Context.getLifetimeQualifiedType(type, lifetime);
6235 decl->setType(type);
6236 }
6237
6238 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6239 // Thread-local variables cannot have lifetime.
6240 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6241 var->getTLSKind()) {
6242 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6243 << var->getType();
6244 return true;
6245 }
6246 }
6247
6248 return false;
6249}
6250
6251void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6252 if (Decl->getType().hasAddressSpace())
6253 return;
6254 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6255 QualType Type = Var->getType();
6256 if (Type->isSamplerT() || Type->isVoidType())
6257 return;
6258 LangAS ImplAS = LangAS::opencl_private;
6259 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6260 Var->hasGlobalStorage())
6261 ImplAS = LangAS::opencl_global;
6262 // If the original type from a decayed type is an array type and that array
6263 // type has no address space yet, deduce it now.
6264 if (auto DT = dyn_cast<DecayedType>(Type)) {
6265 auto OrigTy = DT->getOriginalType();
6266 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6267 // Add the address space to the original array type and then propagate
6268 // that to the element type through `getAsArrayType`.
6269 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6270 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6271 // Re-generate the decayed type.
6272 Type = Context.getDecayedType(OrigTy);
6273 }
6274 }
6275 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6276 // Apply any qualifiers (including address space) from the array type to
6277 // the element type. This implements C99 6.7.3p8: "If the specification of
6278 // an array type includes any type qualifiers, the element type is so
6279 // qualified, not the array type."
6280 if (Type->isArrayType())
6281 Type = QualType(Context.getAsArrayType(Type), 0);
6282 Decl->setType(Type);
6283 }
6284}
6285
6286static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6287 // Ensure that an auto decl is deduced otherwise the checks below might cache
6288 // the wrong linkage.
6289 assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast
<void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6289, __PRETTY_FUNCTION__))
;
6290
6291 // 'weak' only applies to declarations with external linkage.
6292 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6293 if (!ND.isExternallyVisible()) {
6294 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6295 ND.dropAttr<WeakAttr>();
6296 }
6297 }
6298 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6299 if (ND.isExternallyVisible()) {
6300 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6301 ND.dropAttr<WeakRefAttr>();
6302 ND.dropAttr<AliasAttr>();
6303 }
6304 }
6305
6306 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6307 if (VD->hasInit()) {
6308 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6309 assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6310, __PRETTY_FUNCTION__))
6310 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6310, __PRETTY_FUNCTION__))
;
6311 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6312 VD->dropAttr<AliasAttr>();
6313 }
6314 }
6315 }
6316
6317 // 'selectany' only applies to externally visible variable declarations.
6318 // It does not apply to functions.
6319 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6320 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6321 S.Diag(Attr->getLocation(),
6322 diag::err_attribute_selectany_non_extern_data);
6323 ND.dropAttr<SelectAnyAttr>();
6324 }
6325 }
6326
6327 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6328 auto *VD = dyn_cast<VarDecl>(&ND);
6329 bool IsAnonymousNS = false;
6330 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6331 if (VD) {
6332 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6333 while (NS && !IsAnonymousNS) {
6334 IsAnonymousNS = NS->isAnonymousNamespace();
6335 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6336 }
6337 }
6338 // dll attributes require external linkage. Static locals may have external
6339 // linkage but still cannot be explicitly imported or exported.
6340 // In Microsoft mode, a variable defined in anonymous namespace must have
6341 // external linkage in order to be exported.
6342 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6343 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6344 (!AnonNSInMicrosoftMode &&
6345 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6346 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6347 << &ND << Attr;
6348 ND.setInvalidDecl();
6349 }
6350 }
6351
6352 // Virtual functions cannot be marked as 'notail'.
6353 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6354 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6355 if (MD->isVirtual()) {
6356 S.Diag(ND.getLocation(),
6357 diag::err_invalid_attribute_on_virtual_function)
6358 << Attr;
6359 ND.dropAttr<NotTailCalledAttr>();
6360 }
6361
6362 // Check the attributes on the function type, if any.
6363 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6364 // Don't declare this variable in the second operand of the for-statement;
6365 // GCC miscompiles that by ending its lifetime before evaluating the
6366 // third operand. See gcc.gnu.org/PR86769.
6367 AttributedTypeLoc ATL;
6368 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6369 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6370 TL = ATL.getModifiedLoc()) {
6371 // The [[lifetimebound]] attribute can be applied to the implicit object
6372 // parameter of a non-static member function (other than a ctor or dtor)
6373 // by applying it to the function type.
6374 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6375 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6376 if (!MD || MD->isStatic()) {
6377 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6378 << !MD << A->getRange();
6379 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6380 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6381 << isa<CXXDestructorDecl>(MD) << A->getRange();
6382 }
6383 }
6384 }
6385 }
6386}
6387
6388static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6389 NamedDecl *NewDecl,
6390 bool IsSpecialization,
6391 bool IsDefinition) {
6392 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6393 return;
6394
6395 bool IsTemplate = false;
6396 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6397 OldDecl = OldTD->getTemplatedDecl();
6398 IsTemplate = true;
6399 if (!IsSpecialization)
6400 IsDefinition = false;
6401 }
6402 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6403 NewDecl = NewTD->getTemplatedDecl();
6404 IsTemplate = true;
6405 }
6406
6407 if (!OldDecl || !NewDecl)
6408 return;
6409
6410 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6411 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6412 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6413 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6414
6415 // dllimport and dllexport are inheritable attributes so we have to exclude
6416 // inherited attribute instances.
6417 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6418 (NewExportAttr && !NewExportAttr->isInherited());
6419
6420 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6421 // the only exception being explicit specializations.
6422 // Implicitly generated declarations are also excluded for now because there
6423 // is no other way to switch these to use dllimport or dllexport.
6424 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6425
6426 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6427 // Allow with a warning for free functions and global variables.
6428 bool JustWarn = false;
6429 if (!OldDecl->isCXXClassMember()) {
6430 auto *VD = dyn_cast<VarDecl>(OldDecl);
6431 if (VD && !VD->getDescribedVarTemplate())
6432 JustWarn = true;
6433 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6434 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6435 JustWarn = true;
6436 }
6437
6438 // We cannot change a declaration that's been used because IR has already
6439 // been emitted. Dllimported functions will still work though (modulo
6440 // address equality) as they can use the thunk.
6441 if (OldDecl->isUsed())
6442 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6443 JustWarn = false;
6444
6445 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6446 : diag::err_attribute_dll_redeclaration;
6447 S.Diag(NewDecl->getLocation(), DiagID)
6448 << NewDecl
6449 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6450 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6451 if (!JustWarn) {
6452 NewDecl->setInvalidDecl();
6453 return;
6454 }
6455 }
6456
6457 // A redeclaration is not allowed to drop a dllimport attribute, the only
6458 // exceptions being inline function definitions (except for function
6459 // templates), local extern declarations, qualified friend declarations or
6460 // special MSVC extension: in the last case, the declaration is treated as if
6461 // it were marked dllexport.
6462 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6463 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6464 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6465 // Ignore static data because out-of-line definitions are diagnosed
6466 // separately.
6467 IsStaticDataMember = VD->isStaticDataMember();
6468 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6469 VarDecl::DeclarationOnly;
6470 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6471 IsInline = FD->isInlined();
6472 IsQualifiedFriend = FD->getQualifier() &&
6473 FD->getFriendObjectKind() == Decl::FOK_Declared;
6474 }
6475
6476 if (OldImportAttr && !HasNewAttr &&
6477 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6478 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6479 if (IsMicrosoft && IsDefinition) {
6480 S.Diag(NewDecl->getLocation(),
6481 diag::warn_redeclaration_without_import_attribute)
6482 << NewDecl;
6483 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6484 NewDecl->dropAttr<DLLImportAttr>();
6485 NewDecl->addAttr(
6486 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6487 } else {
6488 S.Diag(NewDecl->getLocation(),
6489 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6490 << NewDecl << OldImportAttr;
6491 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6492 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6493 OldDecl->dropAttr<DLLImportAttr>();
6494 NewDecl->dropAttr<DLLImportAttr>();
6495 }
6496 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6497 // In MinGW, seeing a function declared inline drops the dllimport
6498 // attribute.
6499 OldDecl->dropAttr<DLLImportAttr>();
6500 NewDecl->dropAttr<DLLImportAttr>();
6501 S.Diag(NewDecl->getLocation(),
6502 diag::warn_dllimport_dropped_from_inline_function)
6503 << NewDecl << OldImportAttr;
6504 }
6505
6506 // A specialization of a class template member function is processed here
6507 // since it's a redeclaration. If the parent class is dllexport, the
6508 // specialization inherits that attribute. This doesn't happen automatically
6509 // since the parent class isn't instantiated until later.
6510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6511 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6512 !NewImportAttr && !NewExportAttr) {
6513 if (const DLLExportAttr *ParentExportAttr =
6514 MD->getParent()->getAttr<DLLExportAttr>()) {
6515 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6516 NewAttr->setInherited(true);
6517 NewDecl->addAttr(NewAttr);
6518 }
6519 }
6520 }
6521}
6522
6523/// Given that we are within the definition of the given function,
6524/// will that definition behave like C99's 'inline', where the
6525/// definition is discarded except for optimization purposes?
6526static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6527 // Try to avoid calling GetGVALinkageForFunction.
6528
6529 // All cases of this require the 'inline' keyword.
6530 if (!FD->isInlined()) return false;
6531
6532 // This is only possible in C++ with the gnu_inline attribute.
6533 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6534 return false;
6535
6536 // Okay, go ahead and call the relatively-more-expensive function.
6537 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6538}
6539
6540/// Determine whether a variable is extern "C" prior to attaching
6541/// an initializer. We can't just call isExternC() here, because that
6542/// will also compute and cache whether the declaration is externally
6543/// visible, which might change when we attach the initializer.
6544///
6545/// This can only be used if the declaration is known to not be a
6546/// redeclaration of an internal linkage declaration.
6547///
6548/// For instance:
6549///
6550/// auto x = []{};
6551///
6552/// Attaching the initializer here makes this declaration not externally
6553/// visible, because its type has internal linkage.
6554///
6555/// FIXME: This is a hack.
6556template<typename T>
6557static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6558 if (S.getLangOpts().CPlusPlus) {
6559 // In C++, the overloadable attribute negates the effects of extern "C".
6560 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6561 return false;
6562
6563 // So do CUDA's host/device attributes.
6564 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6565 D->template hasAttr<CUDAHostAttr>()))
6566 return false;
6567 }
6568 return D->isExternC();
6569}
6570
6571static bool shouldConsiderLinkage(const VarDecl *VD) {
6572 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6573 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6574 isa<OMPDeclareMapperDecl>(DC))
6575 return VD->hasExternalStorage();
6576 if (DC->isFileContext())
6577 return true;
6578 if (DC->isRecord())
6579 return false;
6580 if (isa<RequiresExprBodyDecl>(DC))
6581 return false;
6582 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6582)
;
6583}
6584
6585static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6586 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6587 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6588 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6589 return true;
6590 if (DC->isRecord())
6591 return false;
6592 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6592)
;
6593}
6594
6595static bool hasParsedAttr(Scope *S, const Declarator &PD,
6596 ParsedAttr::Kind Kind) {
6597 // Check decl attributes on the DeclSpec.
6598 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6599 return true;
6600
6601 // Walk the declarator structure, checking decl attributes that were in a type
6602 // position to the decl itself.
6603 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6604 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6605 return true;
6606 }
6607
6608 // Finally, check attributes on the decl itself.
6609 return PD.getAttributes().hasAttribute(Kind);
6610}
6611
6612/// Adjust the \c DeclContext for a function or variable that might be a
6613/// function-local external declaration.
6614bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6615 if (!DC->isFunctionOrMethod())
6616 return false;
6617
6618 // If this is a local extern function or variable declared within a function
6619 // template, don't add it into the enclosing namespace scope until it is
6620 // instantiated; it might have a dependent type right now.
6621 if (DC->isDependentContext())
6622 return true;
6623
6624 // C++11 [basic.link]p7:
6625 // When a block scope declaration of an entity with linkage is not found to
6626 // refer to some other declaration, then that entity is a member of the
6627 // innermost enclosing namespace.
6628 //
6629 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6630 // semantically-enclosing namespace, not a lexically-enclosing one.
6631 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6632 DC = DC->getParent();
6633 return true;
6634}
6635
6636/// Returns true if given declaration has external C language linkage.
6637static bool isDeclExternC(const Decl *D) {
6638 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6639 return FD->isExternC();
6640 if (const auto *VD = dyn_cast<VarDecl>(D))
6641 return VD->isExternC();
6642
6643 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6643)
;
6644}
6645/// Returns true if there hasn't been any invalid type diagnosed.
6646static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6647 DeclContext *DC, QualType R) {
6648 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6649 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6650 // argument.
6651 if (R->isImageType() || R->isPipeType()) {
6652 Se.Diag(D.getIdentifierLoc(),
6653 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6654 << R;
6655 D.setInvalidType();
6656 return false;
6657 }
6658
6659 // OpenCL v1.2 s6.9.r:
6660 // The event type cannot be used to declare a program scope variable.
6661 // OpenCL v2.0 s6.9.q:
6662 // The clk_event_t and reserve_id_t types cannot be declared in program
6663 // scope.
6664 if (NULL__null == S->getParent()) {
6665 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6666 Se.Diag(D.getIdentifierLoc(),
6667 diag::err_invalid_type_for_program_scope_var)
6668 << R;
6669 D.setInvalidType();
6670 return false;
6671 }
6672 }
6673
6674 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6675 QualType NR = R;
6676 while (NR->isPointerType()) {
6677 if (NR->isFunctionPointerType()) {
6678 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6679 D.setInvalidType();
6680 return false;
6681 }
6682 NR = NR->getPointeeType();
6683 }
6684
6685 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6686 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6687 // half array type (unless the cl_khr_fp16 extension is enabled).
6688 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6689 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6690 D.setInvalidType();
6691 return false;
6692 }
6693 }
6694
6695 // OpenCL v1.2 s6.9.r:
6696 // The event type cannot be used with the __local, __constant and __global
6697 // address space qualifiers.
6698 if (R->isEventT()) {
6699 if (R.getAddressSpace() != LangAS::opencl_private) {
6700 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6701 D.setInvalidType();
6702 return false;
6703 }
6704 }
6705
6706 // C++ for OpenCL does not allow the thread_local storage qualifier.
6707 // OpenCL C does not support thread_local either, and
6708 // also reject all other thread storage class specifiers.
6709 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6710 if (TSC != TSCS_unspecified) {
6711 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6712 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6713 diag::err_opencl_unknown_type_specifier)
6714 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6715 << DeclSpec::getSpecifierName(TSC) << 1;
6716 D.setInvalidType();
6717 return false;
6718 }
6719
6720 if (R->isSamplerT()) {
6721 // OpenCL v1.2 s6.9.b p4:
6722 // The sampler type cannot be used with the __local and __global address
6723 // space qualifiers.
6724 if (R.getAddressSpace() == LangAS::opencl_local ||
6725 R.getAddressSpace() == LangAS::opencl_global) {
6726 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6727 D.setInvalidType();
6728 }
6729
6730 // OpenCL v1.2 s6.12.14.1:
6731 // A global sampler must be declared with either the constant address
6732 // space qualifier or with the const qualifier.
6733 if (DC->isTranslationUnit() &&
6734 !(R.getAddressSpace() == LangAS::opencl_constant ||
6735 R.isConstQualified())) {
6736 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6737 D.setInvalidType();
6738 }
6739 if (D.isInvalidType())
6740 return false;
6741 }
6742 return true;
6743}
6744
6745NamedDecl *Sema::ActOnVariableDeclarator(
6746 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6747 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6748 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6749 QualType R = TInfo->getType();
6750 DeclarationName Name = GetNameForDeclarator(D).getName();
6751
6752 IdentifierInfo *II = Name.getAsIdentifierInfo();
6753
6754 if (D.isDecompositionDeclarator()) {
6755 // Take the name of the first declarator as our name for diagnostic
6756 // purposes.
6757 auto &Decomp = D.getDecompositionDeclarator();
6758 if (!Decomp.bindings().empty()) {
6759 II = Decomp.bindings()[0].Name;
6760 Name = II;
6761 }
6762 } else if (!II) {
6763 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6764 return nullptr;
6765 }
6766
6767
6768 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6769 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6770
6771 // dllimport globals without explicit storage class are treated as extern. We
6772 // have to change the storage class this early to get the right DeclContext.
6773 if (SC == SC_None && !DC->isRecord() &&
6774 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6775 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6776 SC = SC_Extern;
6777
6778 DeclContext *OriginalDC = DC;
6779 bool IsLocalExternDecl = SC == SC_Extern &&
6780 adjustContextForLocalExternDecl(DC);
6781
6782 if (SCSpec == DeclSpec::SCS_mutable) {
6783 // mutable can only appear on non-static class members, so it's always
6784 // an error here
6785 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6786 D.setInvalidType();
6787 SC = SC_None;
6788 }
6789
6790 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6791 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6792 D.getDeclSpec().getStorageClassSpecLoc())) {
6793 // In C++11, the 'register' storage class specifier is deprecated.
6794 // Suppress the warning in system macros, it's used in macros in some
6795 // popular C system headers, such as in glibc's htonl() macro.
6796 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6797 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6798 : diag::warn_deprecated_register)
6799 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6800 }
6801
6802 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6803
6804 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6805 // C99 6.9p2: The storage-class specifiers auto and register shall not
6806 // appear in the declaration specifiers in an external declaration.
6807 // Global Register+Asm is a GNU extension we support.
6808 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6809 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6810 D.setInvalidType();
6811 }
6812 }
6813
6814 bool IsMemberSpecialization = false;
6815 bool IsVariableTemplateSpecialization = false;
6816 bool IsPartialSpecialization = false;
6817 bool IsVariableTemplate = false;
6818 VarDecl *NewVD = nullptr;
6819 VarTemplateDecl *NewTemplate = nullptr;
6820 TemplateParameterList *TemplateParams = nullptr;
6821 if (!getLangOpts().CPlusPlus) {
6822 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6823 II, R, TInfo, SC);
6824
6825 if (R->getContainedDeducedType())
6826 ParsingInitForAutoVars.insert(NewVD);
6827
6828 if (D.isInvalidType())
6829 NewVD->setInvalidDecl();
6830
6831 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6832 NewVD->hasLocalStorage())
6833 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6834 NTCUC_AutoVar, NTCUK_Destruct);
6835 } else {
6836 bool Invalid = false;
6837
6838 if (DC->isRecord() && !CurContext->isRecord()) {
6839 // This is an out-of-line definition of a static data member.
6840 switch (SC) {
6841 case SC_None:
6842 break;
6843 case SC_Static:
6844 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6845 diag::err_static_out_of_line)
6846 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6847 break;
6848 case SC_Auto:
6849 case SC_Register:
6850 case SC_Extern:
6851 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6852 // to names of variables declared in a block or to function parameters.
6853 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6854 // of class members
6855
6856 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6857 diag::err_storage_class_for_static_member)
6858 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6859 break;
6860 case SC_PrivateExtern:
6861 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6861)
;
6862 }
6863 }
6864
6865 if (SC == SC_Static && CurContext->isRecord()) {
6866 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6867 // C++ [class.static.data]p2:
6868 // A static data member shall not be a direct member of an unnamed
6869 // or local class
6870 // FIXME: or of a (possibly indirectly) nested class thereof.
6871 if (RD->isLocalClass()) {
6872 Diag(D.getIdentifierLoc(),
6873 diag::err_static_data_member_not_allowed_in_local_class)
6874 << Name << RD->getDeclName() << RD->getTagKind();
6875 } else if (!RD->getDeclName()) {
6876 Diag(D.getIdentifierLoc(),
6877 diag::err_static_data_member_not_allowed_in_anon_struct)
6878 << Name << RD->getTagKind();
6879 Invalid = true;
6880 } else if (RD->isUnion()) {
6881 // C++98 [class.union]p1: If a union contains a static data member,
6882 // the program is ill-formed. C++11 drops this restriction.
6883 Diag(D.getIdentifierLoc(),
6884 getLangOpts().CPlusPlus11
6885 ? diag::warn_cxx98_compat_static_data_member_in_union
6886 : diag::ext_static_data_member_in_union) << Name;
6887 }
6888 }
6889 }
6890
6891 // Match up the template parameter lists with the scope specifier, then
6892 // determine whether we have a template or a template specialization.
6893 bool InvalidScope = false;
6894 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6895 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6896 D.getCXXScopeSpec(),
6897 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6898 ? D.getName().TemplateId
6899 : nullptr,
6900 TemplateParamLists,
6901 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6902 Invalid |= InvalidScope;
6903
6904 if (TemplateParams) {
6905 if (!TemplateParams->size() &&
6906 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6907 // There is an extraneous 'template<>' for this variable. Complain
6908 // about it, but allow the declaration of the variable.
6909 Diag(TemplateParams->getTemplateLoc(),
6910 diag::err_template_variable_noparams)
6911 << II
6912 << SourceRange(TemplateParams->getTemplateLoc(),
6913 TemplateParams->getRAngleLoc());
6914 TemplateParams = nullptr;
6915 } else {
6916 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6917 // This is an explicit specialization or a partial specialization.
6918 // FIXME: Check that we can declare a specialization here.
6919 IsVariableTemplateSpecialization = true;
6920 IsPartialSpecialization = TemplateParams->size() > 0;
6921 } else { // if (TemplateParams->size() > 0)
6922 // This is a template declaration.
6923 IsVariableTemplate = true;
6924
6925 // Check that we can declare a template here.
6926 if (CheckTemplateDeclScope(S, TemplateParams))
6927 return nullptr;
6928
6929 // Only C++1y supports variable templates (N3651).
6930 Diag(D.getIdentifierLoc(),
6931 getLangOpts().CPlusPlus14
6932 ? diag::warn_cxx11_compat_variable_template
6933 : diag::ext_variable_template);
6934 }
6935 }
6936 } else {
6937 assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6939, __PRETTY_FUNCTION__))
6938 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6939, __PRETTY_FUNCTION__))
6939 "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 6939, __PRETTY_FUNCTION__))
;
6940 }
6941
6942 if (IsVariableTemplateSpecialization) {
6943 SourceLocation TemplateKWLoc =
6944 TemplateParamLists.size() > 0
6945 ? TemplateParamLists[0]->getTemplateLoc()
6946 : SourceLocation();
6947 DeclResult Res = ActOnVarTemplateSpecialization(
6948 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6949 IsPartialSpecialization);
6950 if (Res.isInvalid())
6951 return nullptr;
6952 NewVD = cast<VarDecl>(Res.get());
6953 AddToScope = false;
6954 } else if (D.isDecompositionDeclarator()) {
6955 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6956 D.getIdentifierLoc(), R, TInfo, SC,
6957 Bindings);
6958 } else
6959 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6960 D.getIdentifierLoc(), II, R, TInfo, SC);
6961
6962 // If this is supposed to be a variable template, create it as such.
6963 if (IsVariableTemplate) {
6964 NewTemplate =
6965 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6966 TemplateParams, NewVD);
6967 NewVD->setDescribedVarTemplate(NewTemplate);
6968 }
6969
6970 // If this decl has an auto type in need of deduction, make a note of the
6971 // Decl so we can diagnose uses of it in its own initializer.
6972 if (R->getContainedDeducedType())
6973 ParsingInitForAutoVars.insert(NewVD);
6974
6975 if (D.isInvalidType() || Invalid) {
6976 NewVD->setInvalidDecl();
6977 if (NewTemplate)
6978 NewTemplate->setInvalidDecl();
6979 }
6980
6981 SetNestedNameSpecifier(*this, NewVD, D);
6982
6983 // If we have any template parameter lists that don't directly belong to
6984 // the variable (matching the scope specifier), store them.
6985 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6986 if (TemplateParamLists.size() > VDTemplateParamLists)
6987 NewVD->setTemplateParameterListsInfo(
6988 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6989 }
6990
6991 if (D.getDeclSpec().isInlineSpecified()) {
6992 if (!getLangOpts().CPlusPlus) {
6993 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6994 << 0;
6995 } else if (CurContext->isFunctionOrMethod()) {
6996 // 'inline' is not allowed on block scope variable declaration.
6997 Diag(D.getDeclSpec().getInlineSpecLoc(),
6998 diag::err_inline_declaration_block_scope) << Name
6999 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7000 } else {
7001 Diag(D.getDeclSpec().getInlineSpecLoc(),
7002 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7003 : diag::ext_inline_variable);
7004 NewVD->setInlineSpecified();
7005 }
7006 }
7007
7008 // Set the lexical context. If the declarator has a C++ scope specifier, the
7009 // lexical context will be different from the semantic context.
7010 NewVD->setLexicalDeclContext(CurContext);
7011 if (NewTemplate)
7012 NewTemplate->setLexicalDeclContext(CurContext);
7013
7014 if (IsLocalExternDecl) {
7015 if (D.isDecompositionDeclarator())
7016 for (auto *B : Bindings)
7017 B->setLocalExternDecl();
7018 else
7019 NewVD->setLocalExternDecl();
7020 }
7021
7022 bool EmitTLSUnsupportedError = false;
7023 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7024 // C++11 [dcl.stc]p4:
7025 // When thread_local is applied to a variable of block scope the
7026 // storage-class-specifier static is implied if it does not appear
7027 // explicitly.
7028 // Core issue: 'static' is not implied if the variable is declared
7029 // 'extern'.
7030 if (NewVD->hasLocalStorage() &&
7031 (SCSpec != DeclSpec::SCS_unspecified ||
7032 TSCS != DeclSpec::TSCS_thread_local ||
7033 !DC->isFunctionOrMethod()))
7034 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7035 diag::err_thread_non_global)
7036 << DeclSpec::getSpecifierName(TSCS);
7037 else if (!Context.getTargetInfo().isTLSSupported()) {
7038 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7039 // Postpone error emission until we've collected attributes required to
7040 // figure out whether it's a host or device variable and whether the
7041 // error should be ignored.
7042 EmitTLSUnsupportedError = true;
7043 // We still need to mark the variable as TLS so it shows up in AST with
7044 // proper storage class for other tools to use even if we're not going
7045 // to emit any code for it.
7046 NewVD->setTSCSpec(TSCS);
7047 } else
7048 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7049 diag::err_thread_unsupported);
7050 } else
7051 NewVD->setTSCSpec(TSCS);
7052 }
7053
7054 switch (D.getDeclSpec().getConstexprSpecifier()) {
7055 case CSK_unspecified:
7056 break;
7057
7058 case CSK_consteval:
7059 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7060 diag::err_constexpr_wrong_decl_kind)
7061 << D.getDeclSpec().getConstexprSpecifier();
7062 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7063
7064 case CSK_constexpr:
7065 NewVD->setConstexpr(true);
7066 // C++1z [dcl.spec.constexpr]p1:
7067 // A static data member declared with the constexpr specifier is
7068 // implicitly an inline variable.
7069 if (NewVD->isStaticDataMember() &&
7070 (getLangOpts().CPlusPlus17 ||
7071 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7072 NewVD->setImplicitlyInline();
7073 break;
7074
7075 case CSK_constinit:
7076 if (!NewVD->hasGlobalStorage())
7077 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7078 diag::err_constinit_local_variable);
7079 else
7080 NewVD->addAttr(ConstInitAttr::Create(
7081 Context, D.getDeclSpec().getConstexprSpecLoc(),
7082 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7083 break;
7084 }
7085
7086 // C99 6.7.4p3
7087 // An inline definition of a function with external linkage shall
7088 // not contain a definition of a modifiable object with static or
7089 // thread storage duration...
7090 // We only apply this when the function is required to be defined
7091 // elsewhere, i.e. when the function is not 'extern inline'. Note
7092 // that a local variable with thread storage duration still has to
7093 // be marked 'static'. Also note that it's possible to get these
7094 // semantics in C++ using __attribute__((gnu_inline)).
7095 if (SC == SC_Static && S->getFnParent() != nullptr &&
7096 !NewVD->getType().isConstQualified()) {
7097 FunctionDecl *CurFD = getCurFunctionDecl();
7098 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7099 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7100 diag::warn_static_local_in_extern_inline);
7101 MaybeSuggestAddingStaticToDecl(CurFD);
7102 }
7103 }
7104
7105 if (D.getDeclSpec().isModulePrivateSpecified()) {
7106 if (IsVariableTemplateSpecialization)
7107 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7108 << (IsPartialSpecialization ? 1 : 0)
7109 << FixItHint::CreateRemoval(
7110 D.getDeclSpec().getModulePrivateSpecLoc());
7111 else if (IsMemberSpecialization)
7112 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7113 << 2
7114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7115 else if (NewVD->hasLocalStorage())
7116 Diag(NewVD->getLocation(), diag::err_module_private_local)
7117 << 0 << NewVD->getDeclName()
7118 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7119 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7120 else {
7121 NewVD->setModulePrivate();
7122 if (NewTemplate)
7123 NewTemplate->setModulePrivate();
7124 for (auto *B : Bindings)
7125 B->setModulePrivate();
7126 }
7127 }
7128
7129 if (getLangOpts().OpenCL) {
7130
7131 deduceOpenCLAddressSpace(NewVD);
7132
7133 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7134 }
7135
7136 // Handle attributes prior to checking for duplicates in MergeVarDecl
7137 ProcessDeclAttributes(S, NewVD, D);
7138
7139 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7140 if (EmitTLSUnsupportedError &&
7141 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7142 (getLangOpts().OpenMPIsDevice &&
7143 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7144 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7145 diag::err_thread_unsupported);
7146 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7147 // storage [duration]."
7148 if (SC == SC_None && S->getFnParent() != nullptr &&
7149 (NewVD->hasAttr<CUDASharedAttr>() ||
7150 NewVD->hasAttr<CUDAConstantAttr>())) {
7151 NewVD->setStorageClass(SC_Static);
7152 }
7153 }
7154
7155 // Ensure that dllimport globals without explicit storage class are treated as
7156 // extern. The storage class is set above using parsed attributes. Now we can
7157 // check the VarDecl itself.
7158 assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 7160, __PRETTY_FUNCTION__))
7159 NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 7160, __PRETTY_FUNCTION__))
7160 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 7160, __PRETTY_FUNCTION__))
;
7161
7162 // In auto-retain/release, infer strong retension for variables of
7163 // retainable type.
7164 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7165 NewVD->setInvalidDecl();
7166
7167 // Handle GNU asm-label extension (encoded as an attribute).
7168 if (Expr *E = (Expr*)D.getAsmLabel()) {
7169 // The parser guarantees this is a string.
7170 StringLiteral *SE = cast<StringLiteral>(E);
7171 StringRef Label = SE->getString();
7172 if (S->getFnParent() != nullptr) {
7173 switch (SC) {
7174 case SC_None:
7175 case SC_Auto:
7176 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7177 break;
7178 case SC_Register:
7179 // Local Named register
7180 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7181 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7182 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7183 break;
7184 case SC_Static:
7185 case SC_Extern:
7186 case SC_PrivateExtern:
7187 break;
7188 }
7189 } else if (SC == SC_Register) {
7190 // Global Named register
7191 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7192 const auto &TI = Context.getTargetInfo();
7193 bool HasSizeMismatch;
7194
7195 if (!TI.isValidGCCRegisterName(Label))
7196 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7197 else if (!TI.validateGlobalRegisterVariable(Label,
7198 Context.getTypeSize(R),
7199 HasSizeMismatch))
7200 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7201 else if (HasSizeMismatch)
7202 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7203 }
7204
7205 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7206 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7207 NewVD->setInvalidDecl(true);
7208 }
7209 }
7210
7211 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7212 /*IsLiteralLabel=*/true,
7213 SE->getStrTokenLoc(0)));
7214 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7215 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7216 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7217 if (I != ExtnameUndeclaredIdentifiers.end()) {
7218 if (isDeclExternC(NewVD)) {
7219 NewVD->addAttr(I->second);
7220 ExtnameUndeclaredIdentifiers.erase(I);
7221 } else
7222 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7223 << /*Variable*/1 << NewVD;
7224 }
7225 }
7226
7227 // Find the shadowed declaration before filtering for scope.
7228 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7229 ? getShadowedDeclaration(NewVD, Previous)
7230 : nullptr;
7231
7232 // Don't consider existing declarations that are in a different
7233 // scope and are out-of-semantic-context declarations (if the new
7234 // declaration has linkage).
7235 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7236 D.getCXXScopeSpec().isNotEmpty() ||
7237 IsMemberSpecialization ||
7238 IsVariableTemplateSpecialization);
7239
7240 // Check whether the previous declaration is in the same block scope. This
7241 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7242 if (getLangOpts().CPlusPlus &&
7243 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7244 NewVD->setPreviousDeclInSameBlockScope(
7245 Previous.isSingleResult() && !Previous.isShadowed() &&
7246 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7247
7248 if (!getLangOpts().CPlusPlus) {
7249 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7250 } else {
7251 // If this is an explicit specialization of a static data member, check it.
7252 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7253 CheckMemberSpecialization(NewVD, Previous))
7254 NewVD->setInvalidDecl();
7255
7256 // Merge the decl with the existing one if appropriate.
7257 if (!Previous.empty()) {
7258 if (Previous.isSingleResult() &&
7259 isa<FieldDecl>(Previous.getFoundDecl()) &&
7260 D.getCXXScopeSpec().isSet()) {
7261 // The user tried to define a non-static data member
7262 // out-of-line (C++ [dcl.meaning]p1).
7263 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7264 << D.getCXXScopeSpec().getRange();
7265 Previous.clear();
7266 NewVD->setInvalidDecl();
7267 }
7268 } else if (D.getCXXScopeSpec().isSet()) {
7269 // No previous declaration in the qualifying scope.
7270 Diag(D.getIdentifierLoc(), diag::err_no_member)
7271 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7272 << D.getCXXScopeSpec().getRange();
7273 NewVD->setInvalidDecl();
7274 }
7275
7276 if (!IsVariableTemplateSpecialization)
7277 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7278
7279 if (NewTemplate) {
7280 VarTemplateDecl *PrevVarTemplate =
7281 NewVD->getPreviousDecl()
7282 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7283 : nullptr;
7284
7285 // Check the template parameter list of this declaration, possibly
7286 // merging in the template parameter list from the previous variable
7287 // template declaration.
7288 if (CheckTemplateParameterList(
7289 TemplateParams,
7290 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7291 : nullptr,
7292 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7293 DC->isDependentContext())
7294 ? TPC_ClassTemplateMember
7295 : TPC_VarTemplate))
7296 NewVD->setInvalidDecl();
7297
7298 // If we are providing an explicit specialization of a static variable
7299 // template, make a note of that.
7300 if (PrevVarTemplate &&
7301 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7302 PrevVarTemplate->setMemberSpecialization();
7303 }
7304 }
7305
7306 // Diagnose shadowed variables iff this isn't a redeclaration.
7307 if (ShadowedDecl && !D.isRedeclaration())
7308 CheckShadow(NewVD, ShadowedDecl, Previous);
7309
7310 ProcessPragmaWeak(S, NewVD);
7311
7312 // If this is the first declaration of an extern C variable, update
7313 // the map of such variables.
7314 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7315 isIncompleteDeclExternC(*this, NewVD))
7316 RegisterLocallyScopedExternCDecl(NewVD, S);
7317
7318 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7319 MangleNumberingContext *MCtx;
7320 Decl *ManglingContextDecl;
7321 std::tie(MCtx, ManglingContextDecl) =
7322 getCurrentMangleNumberContext(NewVD->getDeclContext());
7323 if (MCtx) {
7324 Context.setManglingNumber(
7325 NewVD, MCtx->getManglingNumber(
7326 NewVD, getMSManglingNumber(getLangOpts(), S)));
7327 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7328 }
7329 }
7330
7331 // Special handling of variable named 'main'.
7332 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7333 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7334 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7335
7336 // C++ [basic.start.main]p3
7337 // A program that declares a variable main at global scope is ill-formed.
7338 if (getLangOpts().CPlusPlus)
7339 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7340
7341 // In C, and external-linkage variable named main results in undefined
7342 // behavior.
7343 else if (NewVD->hasExternalFormalLinkage())
7344 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7345 }
7346
7347 if (D.isRedeclaration() && !Previous.empty()) {
7348 NamedDecl *Prev = Previous.getRepresentativeDecl();
7349 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7350 D.isFunctionDefinition());
7351 }
7352
7353 if (NewTemplate) {
7354 if (NewVD->isInvalidDecl())
7355 NewTemplate->setInvalidDecl();
7356 ActOnDocumentableDecl(NewTemplate);
7357 return NewTemplate;
7358 }
7359
7360 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7361 CompleteMemberSpecialization(NewVD, Previous);
7362
7363 return NewVD;
7364}
7365
7366/// Enum describing the %select options in diag::warn_decl_shadow.
7367enum ShadowedDeclKind {
7368 SDK_Local,
7369 SDK_Global,
7370 SDK_StaticMember,
7371 SDK_Field,
7372 SDK_Typedef,
7373 SDK_Using
7374};
7375
7376/// Determine what kind of declaration we're shadowing.
7377static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7378 const DeclContext *OldDC) {
7379 if (isa<TypeAliasDecl>(ShadowedDecl))
7380 return SDK_Using;
7381 else if (isa<TypedefDecl>(ShadowedDecl))
7382 return SDK_Typedef;
7383 else if (isa<RecordDecl>(OldDC))
7384 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7385
7386 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7387}
7388
7389/// Return the location of the capture if the given lambda captures the given
7390/// variable \p VD, or an invalid source location otherwise.
7391static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7392 const VarDecl *VD) {
7393 for (const Capture &Capture : LSI->Captures) {
7394 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7395 return Capture.getLocation();
7396 }
7397 return SourceLocation();
7398}
7399
7400static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7401 const LookupResult &R) {
7402 // Only diagnose if we're shadowing an unambiguous field or variable.
7403 if (R.getResultKind() != LookupResult::Found)
7404 return false;
7405
7406 // Return false if warning is ignored.
7407 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7408}
7409
7410/// Return the declaration shadowed by the given variable \p D, or null
7411/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7412NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7413 const LookupResult &R) {
7414 if (!shouldWarnIfShadowedDecl(Diags, R))
7415 return nullptr;
7416
7417 // Don't diagnose declarations at file scope.
7418 if (D->hasGlobalStorage())
7419 return nullptr;
7420
7421 NamedDecl *ShadowedDecl = R.getFoundDecl();
7422 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7423 ? ShadowedDecl
7424 : nullptr;
7425}
7426
7427/// Return the declaration shadowed by the given typedef \p D, or null
7428/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7429NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7430 const LookupResult &R) {
7431 // Don't warn if typedef declaration is part of a class
7432 if (D->getDeclContext()->isRecord())
7433 return nullptr;
7434
7435 if (!shouldWarnIfShadowedDecl(Diags, R))
7436 return nullptr;
7437
7438 NamedDecl *ShadowedDecl = R.getFoundDecl();
7439 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7440}
7441
7442/// Diagnose variable or built-in function shadowing. Implements
7443/// -Wshadow.
7444///
7445/// This method is called whenever a VarDecl is added to a "useful"
7446/// scope.
7447///
7448/// \param ShadowedDecl the declaration that is shadowed by the given variable
7449/// \param R the lookup of the name
7450///
7451void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7452 const LookupResult &R) {
7453 DeclContext *NewDC = D->getDeclContext();
7454
7455 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7456 // Fields are not shadowed by variables in C++ static methods.
7457 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7458 if (MD->isStatic())
7459 return;
7460
7461 // Fields shadowed by constructor parameters are a special case. Usually
7462 // the constructor initializes the field with the parameter.
7463 if (isa<CXXConstructorDecl>(NewDC))
7464 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7465 // Remember that this was shadowed so we can either warn about its
7466 // modification or its existence depending on warning settings.
7467 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7468 return;
7469 }
7470 }
7471
7472 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7473 if (shadowedVar->isExternC()) {
7474 // For shadowing external vars, make sure that we point to the global
7475 // declaration, not a locally scoped extern declaration.
7476 for (auto I : shadowedVar->redecls())
7477 if (I->isFileVarDecl()) {
7478 ShadowedDecl = I;
7479 break;
7480 }
7481 }
7482
7483 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7484
7485 unsigned WarningDiag = diag::warn_decl_shadow;
7486 SourceLocation CaptureLoc;
7487 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7488 isa<CXXMethodDecl>(NewDC)) {
7489 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7490 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7491 if (RD->getLambdaCaptureDefault() == LCD_None) {
7492 // Try to avoid warnings for lambdas with an explicit capture list.
7493 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7494 // Warn only when the lambda captures the shadowed decl explicitly.
7495 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7496 if (CaptureLoc.isInvalid())
7497 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7498 } else {
7499 // Remember that this was shadowed so we can avoid the warning if the
7500 // shadowed decl isn't captured and the warning settings allow it.
7501 cast<LambdaScopeInfo>(getCurFunction())
7502 ->ShadowingDecls.push_back(
7503 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7504 return;
7505 }
7506 }
7507
7508 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7509 // A variable can't shadow a local variable in an enclosing scope, if
7510 // they are separated by a non-capturing declaration context.
7511 for (DeclContext *ParentDC = NewDC;
7512 ParentDC && !ParentDC->Equals(OldDC);
7513 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7514 // Only block literals, captured statements, and lambda expressions
7515 // can capture; other scopes don't.
7516 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7517 !isLambdaCallOperator(ParentDC)) {
7518 return;
7519 }
7520 }
7521 }
7522 }
7523 }
7524
7525 // Only warn about certain kinds of shadowing for class members.
7526 if (NewDC && NewDC->isRecord()) {
7527 // In particular, don't warn about shadowing non-class members.
7528 if (!OldDC->isRecord())
7529 return;
7530
7531 // TODO: should we warn about static data members shadowing
7532 // static data members from base classes?
7533
7534 // TODO: don't diagnose for inaccessible shadowed members.
7535 // This is hard to do perfectly because we might friend the
7536 // shadowing context, but that's just a false negative.
7537 }
7538
7539
7540 DeclarationName Name = R.getLookupName();
7541
7542 // Emit warning and note.
7543 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7544 return;
7545 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7546 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7547 if (!CaptureLoc.isInvalid())
7548 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7549 << Name << /*explicitly*/ 1;
7550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7551}
7552
7553/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7554/// when these variables are captured by the lambda.
7555void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7556 for (const auto &Shadow : LSI->ShadowingDecls) {
7557 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7558 // Try to avoid the warning when the shadowed decl isn't captured.
7559 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7560 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7561 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7562 ? diag::warn_decl_shadow_uncaptured_local
7563 : diag::warn_decl_shadow)
7564 << Shadow.VD->getDeclName()
7565 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7566 if (!CaptureLoc.isInvalid())
7567 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7568 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7569 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7570 }
7571}
7572
7573/// Check -Wshadow without the advantage of a previous lookup.
7574void Sema::CheckShadow(Scope *S, VarDecl *D) {
7575 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7576 return;
7577
7578 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7579 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7580 LookupName(R, S);
7581 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7582 CheckShadow(D, ShadowedDecl, R);
7583}
7584
7585/// Check if 'E', which is an expression that is about to be modified, refers
7586/// to a constructor parameter that shadows a field.
7587void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7588 // Quickly ignore expressions that can't be shadowing ctor parameters.
7589 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7590 return;
7591 E = E->IgnoreParenImpCasts();
7592 auto *DRE = dyn_cast<DeclRefExpr>(E);
7593 if (!DRE)
7594 return;
7595 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7596 auto I = ShadowingDecls.find(D);
7597 if (I == ShadowingDecls.end())
7598 return;
7599 const NamedDecl *ShadowedDecl = I->second;
7600 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7601 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7602 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7603 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7604
7605 // Avoid issuing multiple warnings about the same decl.
7606 ShadowingDecls.erase(I);
7607}
7608
7609/// Check for conflict between this global or extern "C" declaration and
7610/// previous global or extern "C" declarations. This is only used in C++.
7611template<typename T>
7612static bool checkGlobalOrExternCConflict(
7613 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7614 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 7614, __PRETTY_FUNCTION__))
;
7615 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7616
7617 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7618 // The common case: this global doesn't conflict with any extern "C"
7619 // declaration.
7620 return false;
7621 }
7622
7623 if (Prev) {
7624 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7625 // Both the old and new declarations have C language linkage. This is a
7626 // redeclaration.
7627 Previous.clear();
7628 Previous.addDecl(Prev);
7629 return true;
7630 }
7631
7632 // This is a global, non-extern "C" declaration, and there is a previous
7633 // non-global extern "C" declaration. Diagnose if this is a variable
7634 // declaration.
7635 if (!isa<VarDecl>(ND))
7636 return false;
7637 } else {
7638 // The declaration is extern "C". Check for any declaration in the
7639 // translation unit which might conflict.
7640 if (IsGlobal) {
7641 // We have already performed the lookup into the translation unit.
7642 IsGlobal = false;
7643 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7644 I != E; ++I) {
7645 if (isa<VarDecl>(*I)) {
7646 Prev = *I;
7647 break;
7648 }
7649 }
7650 } else {
7651 DeclContext::lookup_result R =
7652 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7653 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7654 I != E; ++I) {
7655 if (isa<VarDecl>(*I)) {
7656 Prev = *I;
7657 break;
7658 }
7659 // FIXME: If we have any other entity with this name in global scope,
7660 // the declaration is ill-formed, but that is a defect: it breaks the
7661 // 'stat' hack, for instance. Only variables can have mangled name
7662 // clashes with extern "C" declarations, so only they deserve a
7663 // diagnostic.
7664 }
7665 }
7666
7667 if (!Prev)
7668 return false;
7669 }
7670
7671 // Use the first declaration's location to ensure we point at something which
7672 // is lexically inside an extern "C" linkage-spec.
7673 assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose"
) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 7673, __PRETTY_FUNCTION__))
;
7674 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7675 Prev = FD->getFirstDecl();
7676 else
7677 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7678
7679 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7680 << IsGlobal << ND;
7681 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7682 << IsGlobal;
7683 return false;
7684}
7685
7686/// Apply special rules for handling extern "C" declarations. Returns \c true
7687/// if we have found that this is a redeclaration of some prior entity.
7688///
7689/// Per C++ [dcl.link]p6:
7690/// Two declarations [for a function or variable] with C language linkage
7691/// with the same name that appear in different scopes refer to the same
7692/// [entity]. An entity with C language linkage shall not be declared with
7693/// the same name as an entity in global scope.
7694template<typename T>
7695static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7696 LookupResult &Previous) {
7697 if (!S.getLangOpts().CPlusPlus) {
7698 // In C, when declaring a global variable, look for a corresponding 'extern'
7699 // variable declared in function scope. We don't need this in C++, because
7700 // we find local extern decls in the surrounding file-scope DeclContext.
7701 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7702 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7703 Previous.clear();
7704 Previous.addDecl(Prev);
7705 return true;
7706 }
7707 }
7708 return false;
7709 }
7710
7711 // A declaration in the translation unit can conflict with an extern "C"
7712 // declaration.
7713 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7714 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7715
7716 // An extern "C" declaration can conflict with a declaration in the
7717 // translation unit or can be a redeclaration of an extern "C" declaration
7718 // in another scope.
7719 if (isIncompleteDeclExternC(S,ND))
7720 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7721
7722 // Neither global nor extern "C": nothing to do.
7723 return false;
7724}
7725
7726void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7727 // If the decl is already known invalid, don't check it.
7728 if (NewVD->isInvalidDecl())
7729 return;
7730
7731 QualType T = NewVD->getType();
7732
7733 // Defer checking an 'auto' type until its initializer is attached.
7734 if (T->isUndeducedType())
7735 return;
7736
7737 if (NewVD->hasAttrs())
7738 CheckAlignasUnderalignment(NewVD);
7739
7740 if (T->isObjCObjectType()) {
7741 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7742 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7743 T = Context.getObjCObjectPointerType(T);
7744 NewVD->setType(T);
7745 }
7746
7747 // Emit an error if an address space was applied to decl with local storage.
7748 // This includes arrays of objects with address space qualifiers, but not
7749 // automatic variables that point to other address spaces.
7750 // ISO/IEC TR 18037 S5.1.2
7751 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7752 T.getAddressSpace() != LangAS::Default) {
7753 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7754 NewVD->setInvalidDecl();
7755 return;
7756 }
7757
7758 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7759 // scope.
7760 if (getLangOpts().OpenCLVersion == 120 &&
7761 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7762 NewVD->isStaticLocal()) {
7763 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7764 NewVD->setInvalidDecl();
7765 return;
7766 }
7767
7768 if (getLangOpts().OpenCL) {
7769 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7770 if (NewVD->hasAttr<BlocksAttr>()) {
7771 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7772 return;
7773 }
7774
7775 if (T->isBlockPointerType()) {
7776 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7777 // can't use 'extern' storage class.
7778 if (!T.isConstQualified()) {
7779 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7780 << 0 /*const*/;
7781 NewVD->setInvalidDecl();
7782 return;
7783 }
7784 if (NewVD->hasExternalStorage()) {
7785 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7786 NewVD->setInvalidDecl();
7787 return;
7788 }
7789 }
7790 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7791 // __constant address space.
7792 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7793 // variables inside a function can also be declared in the global
7794 // address space.
7795 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7796 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7797 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7798 NewVD->hasExternalStorage()) {
7799 if (!T->isSamplerT() &&
7800 !(T.getAddressSpace() == LangAS::opencl_constant ||
7801 (T.getAddressSpace() == LangAS::opencl_global &&
7802 (getLangOpts().OpenCLVersion == 200 ||
7803 getLangOpts().OpenCLCPlusPlus)))) {
7804 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7805 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7806 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7807 << Scope << "global or constant";
7808 else
7809 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7810 << Scope << "constant";
7811 NewVD->setInvalidDecl();
7812 return;
7813 }
7814 } else {
7815 if (T.getAddressSpace() == LangAS::opencl_global) {
7816 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7817 << 1 /*is any function*/ << "global";
7818 NewVD->setInvalidDecl();
7819 return;
7820 }
7821 if (T.getAddressSpace() == LangAS::opencl_constant ||
7822 T.getAddressSpace() == LangAS::opencl_local) {
7823 FunctionDecl *FD = getCurFunctionDecl();
7824 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7825 // in functions.
7826 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7827 if (T.getAddressSpace() == LangAS::opencl_constant)
7828 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7829 << 0 /*non-kernel only*/ << "constant";
7830 else
7831 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7832 << 0 /*non-kernel only*/ << "local";
7833 NewVD->setInvalidDecl();
7834 return;
7835 }
7836 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7837 // in the outermost scope of a kernel function.
7838 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7839 if (!getCurScope()->isFunctionScope()) {
7840 if (T.getAddressSpace() == LangAS::opencl_constant)
7841 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7842 << "constant";
7843 else
7844 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7845 << "local";
7846 NewVD->setInvalidDecl();
7847 return;
7848 }
7849 }
7850 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7851 // If we are parsing a template we didn't deduce an addr
7852 // space yet.
7853 T.getAddressSpace() != LangAS::Default) {
7854 // Do not allow other address spaces on automatic variable.
7855 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7856 NewVD->setInvalidDecl();
7857 return;
7858 }
7859 }
7860 }
7861
7862 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7863 && !NewVD->hasAttr<BlocksAttr>()) {
7864 if (getLangOpts().getGC() != LangOptions::NonGC)
7865 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7866 else {
7867 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 7867, __PRETTY_FUNCTION__))
;
7868 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7869 }
7870 }
7871
7872 bool isVM = T->isVariablyModifiedType();
7873 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7874 NewVD->hasAttr<BlocksAttr>())
7875 setFunctionHasBranchProtectedScope();
7876
7877 if ((isVM && NewVD->hasLinkage()) ||
7878 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7879 bool SizeIsNegative;
7880 llvm::APSInt Oversized;
7881 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7882 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7883 QualType FixedT;
7884 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7885 FixedT = FixedTInfo->getType();
7886 else if (FixedTInfo) {
7887 // Type and type-as-written are canonically different. We need to fix up
7888 // both types separately.
7889 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7890 Oversized);
7891 }
7892 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7893 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7894 // FIXME: This won't give the correct result for
7895 // int a[10][n];
7896 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7897
7898 if (NewVD->isFileVarDecl())
7899 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7900 << SizeRange;
7901 else if (NewVD->isStaticLocal())
7902 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7903 << SizeRange;
7904 else
7905 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7906 << SizeRange;
7907 NewVD->setInvalidDecl();
7908 return;
7909 }
7910
7911 if (!FixedTInfo) {
7912 if (NewVD->isFileVarDecl())
7913 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7914 else
7915 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7916 NewVD->setInvalidDecl();
7917 return;
7918 }
7919
7920 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7921 NewVD->setType(FixedT);
7922 NewVD->setTypeSourceInfo(FixedTInfo);
7923 }
7924
7925 if (T->isVoidType()) {
7926 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7927 // of objects and functions.
7928 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7929 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7930 << T;
7931 NewVD->setInvalidDecl();
7932 return;
7933 }
7934 }
7935
7936 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7937 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7938 NewVD->setInvalidDecl();
7939 return;
7940 }
7941
7942 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7943 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7944 NewVD->setInvalidDecl();
7945 return;
7946 }
7947
7948 if (NewVD->isConstexpr() && !T->isDependentType() &&
7949 RequireLiteralType(NewVD->getLocation(), T,
7950 diag::err_constexpr_var_non_literal)) {
7951 NewVD->setInvalidDecl();
7952 return;
7953 }
7954}
7955
7956/// Perform semantic checking on a newly-created variable
7957/// declaration.
7958///
7959/// This routine performs all of the type-checking required for a
7960/// variable declaration once it has been built. It is used both to
7961/// check variables after they have been parsed and their declarators
7962/// have been translated into a declaration, and to check variables
7963/// that have been instantiated from a template.
7964///
7965/// Sets NewVD->isInvalidDecl() if an error was encountered.
7966///
7967/// Returns true if the variable declaration is a redeclaration.
7968bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7969 CheckVariableDeclarationType(NewVD);
7970
7971 // If the decl is already known invalid, don't check it.
7972 if (NewVD->isInvalidDecl())
7973 return false;
7974
7975 // If we did not find anything by this name, look for a non-visible
7976 // extern "C" declaration with the same name.
7977 if (Previous.empty() &&
7978 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7979 Previous.setShadowed();
7980
7981 if (!Previous.empty()) {
7982 MergeVarDecl(NewVD, Previous);
7983 return true;
7984 }
7985 return false;
7986}
7987
7988namespace {
7989struct FindOverriddenMethod {
7990 Sema *S;
7991 CXXMethodDecl *Method;
7992
7993 /// Member lookup function that determines whether a given C++
7994 /// method overrides a method in a base class, to be used with
7995 /// CXXRecordDecl::lookupInBases().
7996 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7997 RecordDecl *BaseRecord =
7998 Specifier->getType()->castAs<RecordType>()->getDecl();
7999
8000 DeclarationName Name = Method->getDeclName();
8001
8002 // FIXME: Do we care about other names here too?
8003 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8004 // We really want to find the base class destructor here.
8005 QualType T = S->Context.getTypeDeclType(BaseRecord);
8006 CanQualType CT = S->Context.getCanonicalType(T);
8007
8008 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8009 }
8010
8011 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8012 Path.Decls = Path.Decls.slice(1)) {
8013 NamedDecl *D = Path.Decls.front();
8014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8015 if (MD->isVirtual() &&
8016 !S->IsOverload(
8017 Method, MD, /*UseMemberUsingDeclRules=*/false,
8018 /*ConsiderCudaAttrs=*/true,
8019 // C++2a [class.virtual]p2 does not consider requires clauses
8020 // when overriding.
8021 /*ConsiderRequiresClauses=*/false))
8022 return true;
8023 }
8024 }
8025
8026 return false;
8027 }
8028};
8029
8030enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
8031} // end anonymous namespace
8032
8033/// Report an error regarding overriding, along with any relevant
8034/// overridden methods.
8035///
8036/// \param DiagID the primary error to report.
8037/// \param MD the overriding method.
8038/// \param OEK which overrides to include as notes.
8039static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
8040 OverrideErrorKind OEK = OEK_All) {
8041 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
8042 for (const CXXMethodDecl *O : MD->overridden_methods()) {
8043 // This check (& the OEK parameter) could be replaced by a predicate, but
8044 // without lambdas that would be overkill. This is still nicer than writing
8045 // out the diag loop 3 times.
8046 if ((OEK == OEK_All) ||
8047 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
8048 (OEK == OEK_Deleted && O->isDeleted()))
8049 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
8050 }
8051}
8052
8053/// AddOverriddenMethods - See if a method overrides any in the base classes,
8054/// and if so, check that it's a valid override and remember it.
8055bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8056 // Look for methods in base classes that this method might override.
8057 CXXBasePaths Paths;
8058 FindOverriddenMethod FOM;
8059 FOM.Method = MD;
8060 FOM.S = this;
8061 bool hasDeletedOverridenMethods = false;
8062 bool hasNonDeletedOverridenMethods = false;
8063 bool AddedAny = false;
8064 if (DC->lookupInBases(FOM, Paths)) {
8065 for (auto *I : Paths.found_decls()) {
8066 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8067 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8068 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8069 !CheckOverridingFunctionAttributes(MD, OldMD) &&
8070 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8071 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8072 hasDeletedOverridenMethods |= OldMD->isDeleted();
8073 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
8074 AddedAny = true;
8075 }
8076 }
8077 }
8078 }
8079
8080 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
8081 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
8082 }
8083 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
8084 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
8085 }
8086
8087 return AddedAny;
8088}
8089
8090namespace {
8091 // Struct for holding all of the extra arguments needed by
8092 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8093 struct ActOnFDArgs {
8094 Scope *S;
8095 Declarator &D;
8096 MultiTemplateParamsArg TemplateParamLists;
8097 bool AddToScope;
8098 };
8099} // end anonymous namespace
8100
8101namespace {
8102
8103// Callback to only accept typo corrections that have a non-zero edit distance.
8104// Also only accept corrections that have the same parent decl.
8105class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8106 public:
8107 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8108 CXXRecordDecl *Parent)
8109 : Context(Context), OriginalFD(TypoFD),
8110 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8111
8112 bool ValidateCandidate(const TypoCorrection &candidate) override {
8113 if (candidate.getEditDistance() == 0)
8114 return false;
8115
8116 SmallVector<unsigned, 1> MismatchedParams;
8117 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8118 CDeclEnd = candidate.end();
8119 CDecl != CDeclEnd; ++CDecl) {
8120 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8121
8122 if (FD && !FD->hasBody() &&
8123 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8124 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8125 CXXRecordDecl *Parent = MD->getParent();
8126 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8127 return true;
8128 } else if (!ExpectedParent) {
8129 return true;
8130 }
8131 }
8132 }
8133
8134 return false;
8135 }
8136
8137 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8138 return std::make_unique<DifferentNameValidatorCCC>(*this);
8139 }
8140
8141 private:
8142 ASTContext &Context;
8143 FunctionDecl *OriginalFD;
8144 CXXRecordDecl *ExpectedParent;
8145};
8146
8147} // end anonymous namespace
8148
8149void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8150 TypoCorrectedFunctionDefinitions.insert(F);
8151}
8152
8153/// Generate diagnostics for an invalid function redeclaration.
8154///
8155/// This routine handles generating the diagnostic messages for an invalid
8156/// function redeclaration, including finding possible similar declarations
8157/// or performing typo correction if there are no previous declarations with
8158/// the same name.
8159///
8160/// Returns a NamedDecl iff typo correction was performed and substituting in
8161/// the new declaration name does not cause new errors.
8162static NamedDecl *DiagnoseInvalidRedeclaration(
8163 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8164 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8165 DeclarationName Name = NewFD->getDeclName();
8166 DeclContext *NewDC = NewFD->getDeclContext();
8167 SmallVector<unsigned, 1> MismatchedParams;
8168 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8169 TypoCorrection Correction;
8170 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8171 unsigned DiagMsg =
8172 IsLocalFriend ? diag::err_no_matching_local_friend :
8173 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8174 diag::err_member_decl_does_not_match;
8175 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8176 IsLocalFriend ? Sema::LookupLocalFriendName
8177 : Sema::LookupOrdinaryName,
8178 Sema::ForVisibleRedeclaration);
8179
8180 NewFD->setInvalidDecl();
8181 if (IsLocalFriend)
8182 SemaRef.LookupName(Prev, S);
8183 else
8184 SemaRef.LookupQualifiedName(Prev, NewDC);
8185 assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8186, __PRETTY_FUNCTION__))
8186 "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8186, __PRETTY_FUNCTION__))
;
8187 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8188 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8189 MD ? MD->getParent() : nullptr);
8190 if (!Prev.empty()) {
8191 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8192 Func != FuncEnd; ++Func) {
8193 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8194 if (FD &&
8195 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8196 // Add 1 to the index so that 0 can mean the mismatch didn't
8197 // involve a parameter
8198 unsigned ParamNum =
8199 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8200 NearMatches.push_back(std::make_pair(FD, ParamNum));
8201 }
8202 }
8203 // If the qualified name lookup yielded nothing, try typo correction
8204 } else if ((Correction = SemaRef.CorrectTypo(
8205 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8206 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8207 IsLocalFriend ? nullptr : NewDC))) {
8208 // Set up everything for the call to ActOnFunctionDeclarator
8209 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8210 ExtraArgs.D.getIdentifierLoc());
8211 Previous.clear();
8212 Previous.setLookupName(Correction.getCorrection());
8213 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8214 CDeclEnd = Correction.end();
8215 CDecl != CDeclEnd; ++CDecl) {
8216 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8217 if (FD && !FD->hasBody() &&
8218 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8219 Previous.addDecl(FD);
8220 }
8221 }
8222 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8223
8224 NamedDecl *Result;
8225 // Retry building the function declaration with the new previous
8226 // declarations, and with errors suppressed.
8227 {
8228 // Trap errors.
8229 Sema::SFINAETrap Trap(SemaRef);
8230
8231 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8232 // pieces need to verify the typo-corrected C++ declaration and hopefully
8233 // eliminate the need for the parameter pack ExtraArgs.
8234 Result = SemaRef.ActOnFunctionDeclarator(
8235 ExtraArgs.S, ExtraArgs.D,
8236 Correction.getCorrectionDecl()->getDeclContext(),
8237 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8238 ExtraArgs.AddToScope);
8239
8240 if (Trap.hasErrorOccurred())
8241 Result = nullptr;
8242 }
8243
8244 if (Result) {
8245 // Determine which correction we picked.
8246 Decl *Canonical = Result->getCanonicalDecl();
8247 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8248 I != E; ++I)
8249 if ((*I)->getCanonicalDecl() == Canonical)
8250 Correction.setCorrectionDecl(*I);
8251
8252 // Let Sema know about the correction.
8253 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8254 SemaRef.diagnoseTypo(
8255 Correction,
8256 SemaRef.PDiag(IsLocalFriend
8257 ? diag::err_no_matching_local_friend_suggest
8258 : diag::err_member_decl_does_not_match_suggest)
8259 << Name << NewDC << IsDefinition);
8260 return Result;
8261 }
8262
8263 // Pretend the typo correction never occurred
8264 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8265 ExtraArgs.D.getIdentifierLoc());
8266 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8267 Previous.clear();
8268 Previous.setLookupName(Name);
8269 }
8270
8271 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8272 << Name << NewDC << IsDefinition << NewFD->getLocation();
8273
8274 bool NewFDisConst = false;
8275 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8276 NewFDisConst = NewMD->isConst();
8277
8278 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8279 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8280 NearMatch != NearMatchEnd; ++NearMatch) {
8281 FunctionDecl *FD = NearMatch->first;
8282 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8283 bool FDisConst = MD && MD->isConst();
8284 bool IsMember = MD || !IsLocalFriend;
8285
8286 // FIXME: These notes are poorly worded for the local friend case.
8287 if (unsigned Idx = NearMatch->second) {
8288 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8289 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8290 if (Loc.isInvalid()) Loc = FD->getLocation();
8291 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8292 : diag::note_local_decl_close_param_match)
8293 << Idx << FDParam->getType()
8294 << NewFD->getParamDecl(Idx - 1)->getType();
8295 } else if (FDisConst != NewFDisConst) {
8296 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8297 << NewFDisConst << FD->getSourceRange().getEnd();
8298 } else
8299 SemaRef.Diag(FD->getLocation(),
8300 IsMember ? diag::note_member_def_close_match
8301 : diag::note_local_decl_close_match);
8302 }
8303 return nullptr;
8304}
8305
8306static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8307 switch (D.getDeclSpec().getStorageClassSpec()) {
8308 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8308)
;
8309 case DeclSpec::SCS_auto:
8310 case DeclSpec::SCS_register:
8311 case DeclSpec::SCS_mutable:
8312 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8313 diag::err_typecheck_sclass_func);
8314 D.getMutableDeclSpec().ClearStorageClassSpecs();
8315 D.setInvalidType();
8316 break;
8317 case DeclSpec::SCS_unspecified: break;
8318 case DeclSpec::SCS_extern:
8319 if (D.getDeclSpec().isExternInLinkageSpec())
8320 return SC_None;
8321 return SC_Extern;
8322 case DeclSpec::SCS_static: {
8323 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8324 // C99 6.7.1p5:
8325 // The declaration of an identifier for a function that has
8326 // block scope shall have no explicit storage-class specifier
8327 // other than extern
8328 // See also (C++ [dcl.stc]p4).
8329 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8330 diag::err_static_block_func);
8331 break;
8332 } else
8333 return SC_Static;
8334 }
8335 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8336 }
8337
8338 // No explicit storage class has already been returned
8339 return SC_None;
8340}
8341
8342static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8343 DeclContext *DC, QualType &R,
8344 TypeSourceInfo *TInfo,
8345 StorageClass SC,
8346 bool &IsVirtualOkay) {
8347 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8348 DeclarationName Name = NameInfo.getName();
8349
8350 FunctionDecl *NewFD = nullptr;
8351 bool isInline = D.getDeclSpec().isInlineSpecified();
8352
8353 if (!SemaRef.getLangOpts().CPlusPlus) {
8354 // Determine whether the function was written with a
8355 // prototype. This true when:
8356 // - there is a prototype in the declarator, or
8357 // - the type R of the function is some kind of typedef or other non-
8358 // attributed reference to a type name (which eventually refers to a
8359 // function type).
8360 bool HasPrototype =
8361 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8362 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8363
8364 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8365 R, TInfo, SC, isInline, HasPrototype,
8366 CSK_unspecified,
8367 /*TrailingRequiresClause=*/nullptr);
8368 if (D.isInvalidType())
8369 NewFD->setInvalidDecl();
8370
8371 return NewFD;
8372 }
8373
8374 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8375
8376 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8377 if (ConstexprKind == CSK_constinit) {
8378 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8379 diag::err_constexpr_wrong_decl_kind)
8380 << ConstexprKind;
8381 ConstexprKind = CSK_unspecified;
8382 D.getMutableDeclSpec().ClearConstexprSpec();
8383 }
8384 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8385
8386 // Check that the return type is not an abstract class type.
8387 // For record types, this is done by the AbstractClassUsageDiagnoser once
8388 // the class has been completely parsed.
8389 if (!DC->isRecord() &&
8390 SemaRef.RequireNonAbstractType(
8391 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8392 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8393 D.setInvalidType();
8394
8395 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8396 // This is a C++ constructor declaration.
8397 assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8398, __PRETTY_FUNCTION__))
8398 "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8398, __PRETTY_FUNCTION__))
;
8399
8400 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8401 return CXXConstructorDecl::Create(
8402 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8403 TInfo, ExplicitSpecifier, isInline,
8404 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8405 TrailingRequiresClause);
8406
8407 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8408 // This is a C++ destructor declaration.
8409 if (DC->isRecord()) {
8410 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8411 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8412 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8413 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8414 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8415 TrailingRequiresClause);
8416
8417 // If the destructor needs an implicit exception specification, set it
8418 // now. FIXME: It'd be nice to be able to create the right type to start
8419 // with, but the type needs to reference the destructor declaration.
8420 if (SemaRef.getLangOpts().CPlusPlus11)
8421 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8422
8423 IsVirtualOkay = true;
8424 return NewDD;
8425
8426 } else {
8427 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8428 D.setInvalidType();
8429
8430 // Create a FunctionDecl to satisfy the function definition parsing
8431 // code path.
8432 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8433 D.getIdentifierLoc(), Name, R, TInfo, SC,
8434 isInline,
8435 /*hasPrototype=*/true, ConstexprKind,
8436 TrailingRequiresClause);
8437 }
8438
8439 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8440 if (!DC->isRecord()) {
8441 SemaRef.Diag(D.getIdentifierLoc(),
8442 diag::err_conv_function_not_member);
8443 return nullptr;
8444 }
8445
8446 SemaRef.CheckConversionDeclarator(D, R, SC);
8447 if (D.isInvalidType())
8448 return nullptr;
8449
8450 IsVirtualOkay = true;
8451 return CXXConversionDecl::Create(
8452 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8453 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8454 TrailingRequiresClause);
8455
8456 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8457 if (TrailingRequiresClause)
8458 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8459 diag::err_trailing_requires_clause_on_deduction_guide)
8460 << TrailingRequiresClause->getSourceRange();
8461 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8462
8463 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8464 ExplicitSpecifier, NameInfo, R, TInfo,
8465 D.getEndLoc());
8466 } else if (DC->isRecord()) {
8467 // If the name of the function is the same as the name of the record,
8468 // then this must be an invalid constructor that has a return type.
8469 // (The parser checks for a return type and makes the declarator a
8470 // constructor if it has no return type).
8471 if (Name.getAsIdentifierInfo() &&
8472 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8473 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8474 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8475 << SourceRange(D.getIdentifierLoc());
8476 return nullptr;
8477 }
8478
8479 // This is a C++ method declaration.
8480 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8481 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8482 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8483 TrailingRequiresClause);
8484 IsVirtualOkay = !Ret->isStatic();
8485 return Ret;
8486 } else {
8487 bool isFriend =
8488 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8489 if (!isFriend && SemaRef.CurContext->isRecord())
8490 return nullptr;
8491
8492 // Determine whether the function was written with a
8493 // prototype. This true when:
8494 // - we're in C++ (where every function has a prototype),
8495 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8496 R, TInfo, SC, isInline, true /*HasPrototype*/,
8497 ConstexprKind, TrailingRequiresClause);
8498 }
8499}
8500
8501enum OpenCLParamType {
8502 ValidKernelParam,
8503 PtrPtrKernelParam,
8504 PtrKernelParam,
8505 InvalidAddrSpacePtrKernelParam,
8506 InvalidKernelParam,
8507 RecordKernelParam
8508};
8509
8510static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8511 // Size dependent types are just typedefs to normal integer types
8512 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8513 // integers other than by their names.
8514 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8515
8516 // Remove typedefs one by one until we reach a typedef
8517 // for a size dependent type.
8518 QualType DesugaredTy = Ty;
8519 do {
8520 ArrayRef<StringRef> Names(SizeTypeNames);
8521 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8522 if (Names.end() != Match)
8523 return true;
8524
8525 Ty = DesugaredTy;
8526 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8527 } while (DesugaredTy != Ty);
8528
8529 return false;
8530}
8531
8532static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8533 if (PT->isPointerType()) {
8534 QualType PointeeType = PT->getPointeeType();
8535 if (PointeeType->isPointerType())
8536 return PtrPtrKernelParam;
8537 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8538 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8539 PointeeType.getAddressSpace() == LangAS::Default)
8540 return InvalidAddrSpacePtrKernelParam;
8541 return PtrKernelParam;
8542 }
8543
8544 // OpenCL v1.2 s6.9.k:
8545 // Arguments to kernel functions in a program cannot be declared with the
8546 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8547 // uintptr_t or a struct and/or union that contain fields declared to be one
8548 // of these built-in scalar types.
8549 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8550 return InvalidKernelParam;
8551
8552 if (PT->isImageType())
8553 return PtrKernelParam;
8554
8555 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8556 return InvalidKernelParam;
8557
8558 // OpenCL extension spec v1.2 s9.5:
8559 // This extension adds support for half scalar and vector types as built-in
8560 // types that can be used for arithmetic operations, conversions etc.
8561 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8562 return InvalidKernelParam;
8563
8564 if (PT->isRecordType())
8565 return RecordKernelParam;
8566
8567 // Look into an array argument to check if it has a forbidden type.
8568 if (PT->isArrayType()) {
8569 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8570 // Call ourself to check an underlying type of an array. Since the
8571 // getPointeeOrArrayElementType returns an innermost type which is not an
8572 // array, this recursive call only happens once.
8573 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8574 }
8575
8576 return ValidKernelParam;
8577}
8578
8579static void checkIsValidOpenCLKernelParameter(
8580 Sema &S,
8581 Declarator &D,
8582 ParmVarDecl *Param,
8583 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8584 QualType PT = Param->getType();
8585
8586 // Cache the valid types we encounter to avoid rechecking structs that are
8587 // used again
8588 if (ValidTypes.count(PT.getTypePtr()))
8589 return;
8590
8591 switch (getOpenCLKernelParameterType(S, PT)) {
8592 case PtrPtrKernelParam:
8593 // OpenCL v1.2 s6.9.a:
8594 // A kernel function argument cannot be declared as a
8595 // pointer to a pointer type.
8596 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8597 D.setInvalidType();
8598 return;
8599
8600 case InvalidAddrSpacePtrKernelParam:
8601 // OpenCL v1.0 s6.5:
8602 // __kernel function arguments declared to be a pointer of a type can point
8603 // to one of the following address spaces only : __global, __local or
8604 // __constant.
8605 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8606 D.setInvalidType();
8607 return;
8608
8609 // OpenCL v1.2 s6.9.k:
8610 // Arguments to kernel functions in a program cannot be declared with the
8611 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8612 // uintptr_t or a struct and/or union that contain fields declared to be
8613 // one of these built-in scalar types.
8614
8615 case InvalidKernelParam:
8616 // OpenCL v1.2 s6.8 n:
8617 // A kernel function argument cannot be declared
8618 // of event_t type.
8619 // Do not diagnose half type since it is diagnosed as invalid argument
8620 // type for any function elsewhere.
8621 if (!PT->isHalfType()) {
8622 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8623
8624 // Explain what typedefs are involved.
8625 const TypedefType *Typedef = nullptr;
8626 while ((Typedef = PT->getAs<TypedefType>())) {
8627 SourceLocation Loc = Typedef->getDecl()->getLocation();
8628 // SourceLocation may be invalid for a built-in type.
8629 if (Loc.isValid())
8630 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8631 PT = Typedef->desugar();
8632 }
8633 }
8634
8635 D.setInvalidType();
8636 return;
8637
8638 case PtrKernelParam:
8639 case ValidKernelParam:
8640 ValidTypes.insert(PT.getTypePtr());
8641 return;
8642
8643 case RecordKernelParam:
8644 break;
8645 }
8646
8647 // Track nested structs we will inspect
8648 SmallVector<const Decl *, 4> VisitStack;
8649
8650 // Track where we are in the nested structs. Items will migrate from
8651 // VisitStack to HistoryStack as we do the DFS for bad field.
8652 SmallVector<const FieldDecl *, 4> HistoryStack;
8653 HistoryStack.push_back(nullptr);
8654
8655 // At this point we already handled everything except of a RecordType or
8656 // an ArrayType of a RecordType.
8657 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."
) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8657, __PRETTY_FUNCTION__))
;
8658 const RecordType *RecTy =
8659 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8660 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8661
8662 VisitStack.push_back(RecTy->getDecl());
8663 assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast
<void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8663, __PRETTY_FUNCTION__))
;
8664
8665 do {
8666 const Decl *Next = VisitStack.pop_back_val();
8667 if (!Next) {
8668 assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail
("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8668, __PRETTY_FUNCTION__))
;
8669 // Found a marker, we have gone up a level
8670 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8671 ValidTypes.insert(Hist->getType().getTypePtr());
8672
8673 continue;
8674 }
8675
8676 // Adds everything except the original parameter declaration (which is not a
8677 // field itself) to the history stack.
8678 const RecordDecl *RD;
8679 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8680 HistoryStack.push_back(Field);
8681
8682 QualType FieldTy = Field->getType();
8683 // Other field types (known to be valid or invalid) are handled while we
8684 // walk around RecordDecl::fields().
8685 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8686, __PRETTY_FUNCTION__))
8686 "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8686, __PRETTY_FUNCTION__))
;
8687 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8688
8689 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8690 } else {
8691 RD = cast<RecordDecl>(Next);
8692 }
8693
8694 // Add a null marker so we know when we've gone back up a level
8695 VisitStack.push_back(nullptr);
8696
8697 for (const auto *FD : RD->fields()) {
8698 QualType QT = FD->getType();
8699
8700 if (ValidTypes.count(QT.getTypePtr()))
8701 continue;
8702
8703 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8704 if (ParamType == ValidKernelParam)
8705 continue;
8706
8707 if (ParamType == RecordKernelParam) {
8708 VisitStack.push_back(FD);
8709 continue;
8710 }
8711
8712 // OpenCL v1.2 s6.9.p:
8713 // Arguments to kernel functions that are declared to be a struct or union
8714 // do not allow OpenCL objects to be passed as elements of the struct or
8715 // union.
8716 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8717 ParamType == InvalidAddrSpacePtrKernelParam) {
8718 S.Diag(Param->getLocation(),
8719 diag::err_record_with_pointers_kernel_param)
8720 << PT->isUnionType()
8721 << PT;
8722 } else {
8723 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8724 }
8725
8726 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8727 << OrigRecDecl->getDeclName();
8728
8729 // We have an error, now let's go back up through history and show where
8730 // the offending field came from
8731 for (ArrayRef<const FieldDecl *>::const_iterator
8732 I = HistoryStack.begin() + 1,
8733 E = HistoryStack.end();
8734 I != E; ++I) {
8735 const FieldDecl *OuterField = *I;
8736 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8737 << OuterField->getType();
8738 }
8739
8740 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8741 << QT->isPointerType()
8742 << QT;
8743 D.setInvalidType();
8744 return;
8745 }
8746 } while (!VisitStack.empty());
8747}
8748
8749/// Find the DeclContext in which a tag is implicitly declared if we see an
8750/// elaborated type specifier in the specified context, and lookup finds
8751/// nothing.
8752static DeclContext *getTagInjectionContext(DeclContext *DC) {
8753 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8754 DC = DC->getParent();
8755 return DC;
8756}
8757
8758/// Find the Scope in which a tag is implicitly declared if we see an
8759/// elaborated type specifier in the specified context, and lookup finds
8760/// nothing.
8761static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8762 while (S->isClassScope() ||
8763 (LangOpts.CPlusPlus &&
8764 S->isFunctionPrototypeScope()) ||
8765 ((S->getFlags() & Scope::DeclScope) == 0) ||
8766 (S->getEntity() && S->getEntity()->isTransparentContext()))
8767 S = S->getParent();
8768 return S;
8769}
8770
8771NamedDecl*
8772Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8773 TypeSourceInfo *TInfo, LookupResult &Previous,
8774 MultiTemplateParamsArg TemplateParamListsRef,
8775 bool &AddToScope) {
8776 QualType R = TInfo->getType();
8777
8778 assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("R->isFunctionType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 8778, __PRETTY_FUNCTION__))
;
8779 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8780 for (TemplateParameterList *TPL : TemplateParamListsRef)
8781 TemplateParamLists.push_back(TPL);
8782 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8783 if (!TemplateParamLists.empty() &&
8784 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8785 TemplateParamLists.back() = Invented;
8786 else
8787 TemplateParamLists.push_back(Invented);
8788 }
8789
8790 // TODO: consider using NameInfo for diagnostic.
8791 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8792 DeclarationName Name = NameInfo.getName();
8793 StorageClass SC = getFunctionStorageClass(*this, D);
8794
8795 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8796 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8797 diag::err_invalid_thread)
8798 << DeclSpec::getSpecifierName(TSCS);
8799
8800 if (D.isFirstDeclarationOfMember())
8801 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8802 D.getIdentifierLoc());
8803
8804 bool isFriend = false;
8805 FunctionTemplateDecl *FunctionTemplate = nullptr;
8806 bool isMemberSpecialization = false;
8807 bool isFunctionTemplateSpecialization = false;
8808
8809 bool isDependentClassScopeExplicitSpecialization = false;
8810 bool HasExplicitTemplateArgs = false;
8811 TemplateArgumentListInfo TemplateArgs;
8812
8813 bool isVirtualOkay = false;
8814
8815 DeclContext *OriginalDC = DC;
8816 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8817
8818 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8819 isVirtualOkay);
8820 if (!NewFD) return nullptr;
8821
8822 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8823 NewFD->setTopLevelDeclInObjCContainer();
8824
8825 // Set the lexical context. If this is a function-scope declaration, or has a
8826 // C++ scope specifier, or is the object of a friend declaration, the lexical
8827 // context will be different from the semantic context.
8828 NewFD->setLexicalDeclContext(CurContext);
8829
8830 if (IsLocalExternDecl)
8831 NewFD->setLocalExternDecl();
8832
8833 if (getLangOpts().CPlusPlus) {
8834 bool isInline = D.getDeclSpec().isInlineSpecified();
8835 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8836 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8837 isFriend = D.getDeclSpec().isFriendSpecified();
8838 if (isFriend && !isInline && D.isFunctionDefinition()) {
8839 // C++ [class.friend]p5
8840 // A function can be defined in a friend declaration of a
8841 // class . . . . Such a function is implicitly inline.
8842 NewFD->setImplicitlyInline();
8843 }
8844
8845 // If this is a method defined in an __interface, and is not a constructor
8846 // or an overloaded operator, then set the pure flag (isVirtual will already
8847 // return true).
8848 if (const CXXRecordDecl *Parent =
8849 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8850 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8851 NewFD->setPure(true);
8852
8853 // C++ [class.union]p2
8854 // A union can have member functions, but not virtual functions.
8855 if (isVirtual && Parent->isUnion())
8856 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8857 }
8858
8859 SetNestedNameSpecifier(*this, NewFD, D);
8860 isMemberSpecialization = false;
8861 isFunctionTemplateSpecialization = false;
8862 if (D.isInvalidType())
8863 NewFD->setInvalidDecl();
8864
8865 // Match up the template parameter lists with the scope specifier, then
8866 // determine whether we have a template or a template specialization.
8867 bool Invalid = false;
8868 TemplateParameterList *TemplateParams =
8869 MatchTemplateParametersToScopeSpecifier(
8870 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8871 D.getCXXScopeSpec(),
8872 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8873 ? D.getName().TemplateId
8874 : nullptr,
8875 TemplateParamLists, isFriend, isMemberSpecialization,
8876 Invalid);
8877 if (TemplateParams) {
8878 if (TemplateParams->size() > 0) {
8879 // This is a function template
8880
8881 // Check that we can declare a template here.
8882 if (CheckTemplateDeclScope(S, TemplateParams))
8883 NewFD->setInvalidDecl();
8884
8885 // A destructor cannot be a template.
8886 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8887 Diag(NewFD->getLocation(), diag::err_destructor_template);
8888 NewFD->setInvalidDecl();
8889 }
8890
8891 // If we're adding a template to a dependent context, we may need to
8892 // rebuilding some of the types used within the template parameter list,
8893 // now that we know what the current instantiation is.
8894 if (DC->isDependentContext()) {
8895 ContextRAII SavedContext(*this, DC);
8896 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8897 Invalid = true;
8898 }
8899
8900 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8901 NewFD->getLocation(),
8902 Name, TemplateParams,
8903 NewFD);
8904 FunctionTemplate->setLexicalDeclContext(CurContext);
8905 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8906
8907 // For source fidelity, store the other template param lists.
8908 if (TemplateParamLists.size() > 1) {
8909 NewFD->setTemplateParameterListsInfo(Context,
8910 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8911 .drop_back(1));
8912 }
8913 } else {
8914 // This is a function template specialization.
8915 isFunctionTemplateSpecialization = true;
8916 // For source fidelity, store all the template param lists.
8917 if (TemplateParamLists.size() > 0)
8918 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8919
8920 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8921 if (isFriend) {
8922 // We want to remove the "template<>", found here.
8923 SourceRange RemoveRange = TemplateParams->getSourceRange();
8924
8925 // If we remove the template<> and the name is not a
8926 // template-id, we're actually silently creating a problem:
8927 // the friend declaration will refer to an untemplated decl,
8928 // and clearly the user wants a template specialization. So
8929 // we need to insert '<>' after the name.
8930 SourceLocation InsertLoc;
8931 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8932 InsertLoc = D.getName().getSourceRange().getEnd();
8933 InsertLoc = getLocForEndOfToken(InsertLoc);
8934 }
8935
8936 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8937 << Name << RemoveRange
8938 << FixItHint::CreateRemoval(RemoveRange)
8939 << FixItHint::CreateInsertion(InsertLoc, "<>");
8940 }
8941 }
8942 } else {
8943 // All template param lists were matched against the scope specifier:
8944 // this is NOT (an explicit specialization of) a template.
8945 if (TemplateParamLists.size() > 0)
8946 // For source fidelity, store all the template param lists.
8947 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8948 }
8949
8950 if (Invalid) {
8951 NewFD->setInvalidDecl();
8952 if (FunctionTemplate)
8953 FunctionTemplate->setInvalidDecl();
8954 }
8955
8956 // C++ [dcl.fct.spec]p5:
8957 // The virtual specifier shall only be used in declarations of
8958 // nonstatic class member functions that appear within a
8959 // member-specification of a class declaration; see 10.3.
8960 //
8961 if (isVirtual && !NewFD->isInvalidDecl()) {
8962 if (!isVirtualOkay) {
8963 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8964 diag::err_virtual_non_function);
8965 } else if (!CurContext->isRecord()) {
8966 // 'virtual' was specified outside of the class.
8967 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8968 diag::err_virtual_out_of_class)
8969 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8970 } else if (NewFD->getDescribedFunctionTemplate()) {
8971 // C++ [temp.mem]p3:
8972 // A member function template shall not be virtual.
8973 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8974 diag::err_virtual_member_function_template)
8975 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8976 } else {
8977 // Okay: Add virtual to the method.
8978 NewFD->setVirtualAsWritten(true);
8979 }
8980
8981 if (getLangOpts().CPlusPlus14 &&
8982 NewFD->getReturnType()->isUndeducedType())
8983 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8984 }
8985
8986 if (getLangOpts().CPlusPlus14 &&
8987 (NewFD->isDependentContext() ||
8988 (isFriend && CurContext->isDependentContext())) &&
8989 NewFD->getReturnType()->isUndeducedType()) {
8990 // If the function template is referenced directly (for instance, as a
8991 // member of the current instantiation), pretend it has a dependent type.
8992 // This is not really justified by the standard, but is the only sane
8993 // thing to do.
8994 // FIXME: For a friend function, we have not marked the function as being
8995 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8996 const FunctionProtoType *FPT =
8997 NewFD->getType()->castAs<FunctionProtoType>();
8998 QualType Result =
8999 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9000 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9001 FPT->getExtProtoInfo()));
9002 }
9003
9004 // C++ [dcl.fct.spec]p3:
9005 // The inline specifier shall not appear on a block scope function
9006 // declaration.
9007 if (isInline && !NewFD->isInvalidDecl()) {
9008 if (CurContext->isFunctionOrMethod()) {
9009 // 'inline' is not allowed on block scope function declaration.
9010 Diag(D.getDeclSpec().getInlineSpecLoc(),
9011 diag::err_inline_declaration_block_scope) << Name
9012 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9013 }
9014 }
9015
9016 // C++ [dcl.fct.spec]p6:
9017 // The explicit specifier shall be used only in the declaration of a
9018 // constructor or conversion function within its class definition;
9019 // see 12.3.1 and 12.3.2.
9020 if (hasExplicit && !NewFD->isInvalidDecl() &&
9021 !isa<CXXDeductionGuideDecl>(NewFD)) {
9022 if (!CurContext->isRecord()) {
9023 // 'explicit' was specified outside of the class.
9024 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9025 diag::err_explicit_out_of_class)
9026 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9027 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9028 !isa<CXXConversionDecl>(NewFD)) {
9029 // 'explicit' was specified on a function that wasn't a constructor
9030 // or conversion function.
9031 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9032 diag::err_explicit_non_ctor_or_conv_function)
9033 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9034 }
9035 }
9036
9037 if (ConstexprSpecKind ConstexprKind =
9038 D.getDeclSpec().getConstexprSpecifier()) {
9039 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9040 // are implicitly inline.
9041 NewFD->setImplicitlyInline();
9042
9043 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9044 // be either constructors or to return a literal type. Therefore,
9045 // destructors cannot be declared constexpr.
9046 if (isa<CXXDestructorDecl>(NewFD) &&
9047 (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) {
9048 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9049 << ConstexprKind;
9050 NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr);
9051 }
9052 // C++20 [dcl.constexpr]p2: An allocation function, or a
9053 // deallocation function shall not be declared with the consteval
9054 // specifier.
9055 if (ConstexprKind == CSK_consteval &&
9056 (NewFD->getOverloadedOperator() == OO_New ||
9057 NewFD->getOverloadedOperator() == OO_Array_New ||
9058 NewFD->getOverloadedOperator() == OO_Delete ||
9059 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9060 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9061 diag::err_invalid_consteval_decl_kind)
9062 << NewFD;
9063 NewFD->setConstexprKind(CSK_constexpr);
9064 }
9065 }
9066
9067 // If __module_private__ was specified, mark the function accordingly.
9068 if (D.getDeclSpec().isModulePrivateSpecified()) {
9069 if (isFunctionTemplateSpecialization) {
9070 SourceLocation ModulePrivateLoc
9071 = D.getDeclSpec().getModulePrivateSpecLoc();
9072 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9073 << 0
9074 << FixItHint::CreateRemoval(ModulePrivateLoc);
9075 } else {
9076 NewFD->setModulePrivate();
9077 if (FunctionTemplate)
9078 FunctionTemplate->setModulePrivate();
9079 }
9080 }
9081
9082 if (isFriend) {
9083 if (FunctionTemplate) {
9084 FunctionTemplate->setObjectOfFriendDecl();
9085 FunctionTemplate->setAccess(AS_public);
9086 }
9087 NewFD->setObjectOfFriendDecl();
9088 NewFD->setAccess(AS_public);
9089 }
9090
9091 // If a function is defined as defaulted or deleted, mark it as such now.
9092 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
9093 // definition kind to FDK_Definition.
9094 switch (D.getFunctionDefinitionKind()) {
9095 case FDK_Declaration:
9096 case FDK_Definition:
9097 break;
9098
9099 case FDK_Defaulted:
9100 NewFD->setDefaulted();
9101 break;
9102
9103 case FDK_Deleted:
9104 NewFD->setDeletedAsWritten();
9105 break;
9106 }
9107
9108 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9109 D.isFunctionDefinition()) {
9110 // C++ [class.mfct]p2:
9111 // A member function may be defined (8.4) in its class definition, in
9112 // which case it is an inline member function (7.1.2)
9113 NewFD->setImplicitlyInline();
9114 }
9115
9116 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9117 !CurContext->isRecord()) {
9118 // C++ [class.static]p1:
9119 // A data or function member of a class may be declared static
9120 // in a class definition, in which case it is a static member of
9121 // the class.
9122
9123 // Complain about the 'static' specifier if it's on an out-of-line
9124 // member function definition.
9125
9126 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9127 // member function template declaration and class member template
9128 // declaration (MSVC versions before 2015), warn about this.
9129 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9130 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9131 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9132 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9133 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9134 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9135 }
9136
9137 // C++11 [except.spec]p15:
9138 // A deallocation function with no exception-specification is treated
9139 // as if it were specified with noexcept(true).
9140 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9141 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9142 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9143 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9144 NewFD->setType(Context.getFunctionType(
9145 FPT->getReturnType(), FPT->getParamTypes(),
9146 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9147 }
9148
9149 // Filter out previous declarations that don't match the scope.
9150 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9151 D.getCXXScopeSpec().isNotEmpty() ||
9152 isMemberSpecialization ||
9153 isFunctionTemplateSpecialization);
9154
9155 // Handle GNU asm-label extension (encoded as an attribute).
9156 if (Expr *E = (Expr*) D.getAsmLabel()) {
9157 // The parser guarantees this is a string.
9158 StringLiteral *SE = cast<StringLiteral>(E);
9159 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9160 /*IsLiteralLabel=*/true,
9161 SE->getStrTokenLoc(0)));
9162 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9163 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9164 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9165 if (I != ExtnameUndeclaredIdentifiers.end()) {
9166 if (isDeclExternC(NewFD)) {
9167 NewFD->addAttr(I->second);
9168 ExtnameUndeclaredIdentifiers.erase(I);
9169 } else
9170 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9171 << /*Variable*/0 << NewFD;
9172 }
9173 }
9174
9175 // Copy the parameter declarations from the declarator D to the function
9176 // declaration NewFD, if they are available. First scavenge them into Params.
9177 SmallVector<ParmVarDecl*, 16> Params;
9178 unsigned FTIIdx;
9179 if (D.isFunctionDeclarator(FTIIdx)) {
9180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9181
9182 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9183 // function that takes no arguments, not a function that takes a
9184 // single void argument.
9185 // We let through "const void" here because Sema::GetTypeForDeclarator
9186 // already checks for that case.
9187 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9188 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9189 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9190 assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?"
) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9190, __PRETTY_FUNCTION__))
;
9191 Param->setDeclContext(NewFD);
9192 Params.push_back(Param);
9193
9194 if (Param->isInvalidDecl())
9195 NewFD->setInvalidDecl();
9196 }
9197 }
9198
9199 if (!getLangOpts().CPlusPlus) {
9200 // In C, find all the tag declarations from the prototype and move them
9201 // into the function DeclContext. Remove them from the surrounding tag
9202 // injection context of the function, which is typically but not always
9203 // the TU.
9204 DeclContext *PrototypeTagContext =
9205 getTagInjectionContext(NewFD->getLexicalDeclContext());
9206 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9207 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9208
9209 // We don't want to reparent enumerators. Look at their parent enum
9210 // instead.
9211 if (!TD) {
9212 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9213 TD = cast<EnumDecl>(ECD->getDeclContext());
9214 }
9215 if (!TD)
9216 continue;
9217 DeclContext *TagDC = TD->getLexicalDeclContext();
9218 if (!TagDC->containsDecl(TD))
9219 continue;
9220 TagDC->removeDecl(TD);
9221 TD->setDeclContext(NewFD);
9222 NewFD->addDecl(TD);
9223
9224 // Preserve the lexical DeclContext if it is not the surrounding tag
9225 // injection context of the FD. In this example, the semantic context of
9226 // E will be f and the lexical context will be S, while both the
9227 // semantic and lexical contexts of S will be f:
9228 // void f(struct S { enum E { a } f; } s);
9229 if (TagDC != PrototypeTagContext)
9230 TD->setLexicalDeclContext(TagDC);
9231 }
9232 }
9233 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9234 // When we're declaring a function with a typedef, typeof, etc as in the
9235 // following example, we'll need to synthesize (unnamed)
9236 // parameters for use in the declaration.
9237 //
9238 // @code
9239 // typedef void fn(int);
9240 // fn f;
9241 // @endcode
9242
9243 // Synthesize a parameter for each argument type.
9244 for (const auto &AI : FT->param_types()) {
9245 ParmVarDecl *Param =
9246 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9247 Param->setScopeInfo(0, Params.size());
9248 Params.push_back(Param);
9249 }
9250 } else {
9251 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9252, __PRETTY_FUNCTION__))
9252 "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9252, __PRETTY_FUNCTION__))
;
9253 }
9254
9255 // Finally, we know we have the right number of parameters, install them.
9256 NewFD->setParams(Params);
9257
9258 if (D.getDeclSpec().isNoreturnSpecified())
9259 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9260 D.getDeclSpec().getNoreturnSpecLoc(),
9261 AttributeCommonInfo::AS_Keyword));
9262
9263 // Functions returning a variably modified type violate C99 6.7.5.2p2
9264 // because all functions have linkage.
9265 if (!NewFD->isInvalidDecl() &&
9266 NewFD->getReturnType()->isVariablyModifiedType()) {
9267 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9268 NewFD->setInvalidDecl();
9269 }
9270
9271 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9272 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9273 !NewFD->hasAttr<SectionAttr>())
9274 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9275 Context, PragmaClangTextSection.SectionName,
9276 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9277
9278 // Apply an implicit SectionAttr if #pragma code_seg is active.
9279 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9280 !NewFD->hasAttr<SectionAttr>()) {
9281 NewFD->addAttr(SectionAttr::CreateImplicit(
9282 Context, CodeSegStack.CurrentValue->getString(),
9283 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9284 SectionAttr::Declspec_allocate));
9285 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9286 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9287 ASTContext::PSF_Read,
9288 NewFD))
9289 NewFD->dropAttr<SectionAttr>();
9290 }
9291
9292 // Apply an implicit CodeSegAttr from class declspec or
9293 // apply an implicit SectionAttr from #pragma code_seg if active.
9294 if (!NewFD->hasAttr<CodeSegAttr>()) {
9295 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9296 D.isFunctionDefinition())) {
9297 NewFD->addAttr(SAttr);
9298 }
9299 }
9300
9301 // Handle attributes.
9302 ProcessDeclAttributes(S, NewFD, D);
9303
9304 if (getLangOpts().OpenCL) {
9305 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9306 // type declaration will generate a compilation error.
9307 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9308 if (AddressSpace != LangAS::Default) {
9309 Diag(NewFD->getLocation(),
9310 diag::err_opencl_return_value_with_address_space);
9311 NewFD->setInvalidDecl();
9312 }
9313 }
9314
9315 if (!getLangOpts().CPlusPlus) {
9316 // Perform semantic checking on the function declaration.
9317 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9318 CheckMain(NewFD, D.getDeclSpec());
9319
9320 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9321 CheckMSVCRTEntryPoint(NewFD);
9322
9323 if (!NewFD->isInvalidDecl())
9324 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9325 isMemberSpecialization));
9326 else if (!Previous.empty())
9327 // Recover gracefully from an invalid redeclaration.
9328 D.setRedeclaration(true);
9329 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9331, __PRETTY_FUNCTION__))
9330 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9331, __PRETTY_FUNCTION__))
9331 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9331, __PRETTY_FUNCTION__))
;
9332
9333 // Diagnose no-prototype function declarations with calling conventions that
9334 // don't support variadic calls. Only do this in C and do it after merging
9335 // possibly prototyped redeclarations.
9336 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9337 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9338 CallingConv CC = FT->getExtInfo().getCC();
9339 if (!supportsVariadicCall(CC)) {
9340 // Windows system headers sometimes accidentally use stdcall without
9341 // (void) parameters, so we relax this to a warning.
9342 int DiagID =
9343 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9344 Diag(NewFD->getLocation(), DiagID)
9345 << FunctionType::getNameForCallConv(CC);
9346 }
9347 }
9348
9349 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9350 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9351 checkNonTrivialCUnion(NewFD->getReturnType(),
9352 NewFD->getReturnTypeSourceRange().getBegin(),
9353 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9354 } else {
9355 // C++11 [replacement.functions]p3:
9356 // The program's definitions shall not be specified as inline.
9357 //
9358 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9359 //
9360 // Suppress the diagnostic if the function is __attribute__((used)), since
9361 // that forces an external definition to be emitted.
9362 if (D.getDeclSpec().isInlineSpecified() &&
9363 NewFD->isReplaceableGlobalAllocationFunction() &&
9364 !NewFD->hasAttr<UsedAttr>())
9365 Diag(D.getDeclSpec().getInlineSpecLoc(),
9366 diag::ext_operator_new_delete_declared_inline)
9367 << NewFD->getDeclName();
9368
9369 // If the declarator is a template-id, translate the parser's template
9370 // argument list into our AST format.
9371 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9372 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9373 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9374 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9375 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9376 TemplateId->NumArgs);
9377 translateTemplateArguments(TemplateArgsPtr,
9378 TemplateArgs);
9379
9380 HasExplicitTemplateArgs = true;
9381
9382 if (NewFD->isInvalidDecl()) {
9383 HasExplicitTemplateArgs = false;
9384 } else if (FunctionTemplate) {
9385 // Function template with explicit template arguments.
9386 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9387 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9388
9389 HasExplicitTemplateArgs = false;
9390 } else {
9391 assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9393, __PRETTY_FUNCTION__))
9392 D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9393, __PRETTY_FUNCTION__))
9393 "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9393, __PRETTY_FUNCTION__))
;
9394 // "friend void foo<>(int);" is an implicit specialization decl.
9395 isFunctionTemplateSpecialization = true;
9396 }
9397 } else if (isFriend && isFunctionTemplateSpecialization) {
9398 // This combination is only possible in a recovery case; the user
9399 // wrote something like:
9400 // template <> friend void foo(int);
9401 // which we're recovering from as if the user had written:
9402 // friend void foo<>(int);
9403 // Go ahead and fake up a template id.
9404 HasExplicitTemplateArgs = true;
9405 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9406 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9407 }
9408
9409 // We do not add HD attributes to specializations here because
9410 // they may have different constexpr-ness compared to their
9411 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9412 // may end up with different effective targets. Instead, a
9413 // specialization inherits its target attributes from its template
9414 // in the CheckFunctionTemplateSpecialization() call below.
9415 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9416 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9417
9418 // If it's a friend (and only if it's a friend), it's possible
9419 // that either the specialized function type or the specialized
9420 // template is dependent, and therefore matching will fail. In
9421 // this case, don't check the specialization yet.
9422 bool InstantiationDependent = false;
9423 if (isFunctionTemplateSpecialization && isFriend &&
9424 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9425 TemplateSpecializationType::anyDependentTemplateArguments(
9426 TemplateArgs,
9427 InstantiationDependent))) {
9428 assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9429, __PRETTY_FUNCTION__))
9429 "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9429, __PRETTY_FUNCTION__))
;
9430 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9431 Previous))
9432 NewFD->setInvalidDecl();
9433 } else if (isFunctionTemplateSpecialization) {
9434 if (CurContext->isDependentContext() && CurContext->isRecord()
9435 && !isFriend) {
9436 isDependentClassScopeExplicitSpecialization = true;
9437 } else if (!NewFD->isInvalidDecl() &&
9438 CheckFunctionTemplateSpecialization(
9439 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9440 Previous))
9441 NewFD->setInvalidDecl();
9442
9443 // C++ [dcl.stc]p1:
9444 // A storage-class-specifier shall not be specified in an explicit
9445 // specialization (14.7.3)
9446 FunctionTemplateSpecializationInfo *Info =
9447 NewFD->getTemplateSpecializationInfo();
9448 if (Info && SC != SC_None) {
9449 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9450 Diag(NewFD->getLocation(),
9451 diag::err_explicit_specialization_inconsistent_storage_class)
9452 << SC
9453 << FixItHint::CreateRemoval(
9454 D.getDeclSpec().getStorageClassSpecLoc());
9455
9456 else
9457 Diag(NewFD->getLocation(),
9458 diag::ext_explicit_specialization_storage_class)
9459 << FixItHint::CreateRemoval(
9460 D.getDeclSpec().getStorageClassSpecLoc());
9461 }
9462 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9463 if (CheckMemberSpecialization(NewFD, Previous))
9464 NewFD->setInvalidDecl();
9465 }
9466
9467 // Perform semantic checking on the function declaration.
9468 if (!isDependentClassScopeExplicitSpecialization) {
9469 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9470 CheckMain(NewFD, D.getDeclSpec());
9471
9472 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9473 CheckMSVCRTEntryPoint(NewFD);
9474
9475 if (!NewFD->isInvalidDecl())
9476 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9477 isMemberSpecialization));
9478 else if (!Previous.empty())
9479 // Recover gracefully from an invalid redeclaration.
9480 D.setRedeclaration(true);
9481 }
9482
9483 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9485, __PRETTY_FUNCTION__))
9484 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9485, __PRETTY_FUNCTION__))
9485 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9485, __PRETTY_FUNCTION__))
;
9486
9487 NamedDecl *PrincipalDecl = (FunctionTemplate
9488 ? cast<NamedDecl>(FunctionTemplate)
9489 : NewFD);
9490
9491 if (isFriend && NewFD->getPreviousDecl()) {
9492 AccessSpecifier Access = AS_public;
9493 if (!NewFD->isInvalidDecl())
9494 Access = NewFD->getPreviousDecl()->getAccess();
9495
9496 NewFD->setAccess(Access);
9497 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9498 }
9499
9500 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9501 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9502 PrincipalDecl->setNonMemberOperator();
9503
9504 // If we have a function template, check the template parameter
9505 // list. This will check and merge default template arguments.
9506 if (FunctionTemplate) {
9507 FunctionTemplateDecl *PrevTemplate =
9508 FunctionTemplate->getPreviousDecl();
9509 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9510 PrevTemplate ? PrevTemplate->getTemplateParameters()
9511 : nullptr,
9512 D.getDeclSpec().isFriendSpecified()
9513 ? (D.isFunctionDefinition()
9514 ? TPC_FriendFunctionTemplateDefinition
9515 : TPC_FriendFunctionTemplate)
9516 : (D.getCXXScopeSpec().isSet() &&
9517 DC && DC->isRecord() &&
9518 DC->isDependentContext())
9519 ? TPC_ClassTemplateMember
9520 : TPC_FunctionTemplate);
9521 }
9522
9523 if (NewFD->isInvalidDecl()) {
9524 // Ignore all the rest of this.
9525 } else if (!D.isRedeclaration()) {
9526 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9527 AddToScope };
9528 // Fake up an access specifier if it's supposed to be a class member.
9529 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9530 NewFD->setAccess(AS_public);
9531
9532 // Qualified decls generally require a previous declaration.
9533 if (D.getCXXScopeSpec().isSet()) {
9534 // ...with the major exception of templated-scope or
9535 // dependent-scope friend declarations.
9536
9537 // TODO: we currently also suppress this check in dependent
9538 // contexts because (1) the parameter depth will be off when
9539 // matching friend templates and (2) we might actually be
9540 // selecting a friend based on a dependent factor. But there
9541 // are situations where these conditions don't apply and we
9542 // can actually do this check immediately.
9543 //
9544 // Unless the scope is dependent, it's always an error if qualified
9545 // redeclaration lookup found nothing at all. Diagnose that now;
9546 // nothing will diagnose that error later.
9547 if (isFriend &&
9548 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9549 (!Previous.empty() && CurContext->isDependentContext()))) {
9550 // ignore these
9551 } else {
9552 // The user tried to provide an out-of-line definition for a
9553 // function that is a member of a class or namespace, but there
9554 // was no such member function declared (C++ [class.mfct]p2,
9555 // C++ [namespace.memdef]p2). For example:
9556 //
9557 // class X {
9558 // void f() const;
9559 // };
9560 //
9561 // void X::f() { } // ill-formed
9562 //
9563 // Complain about this problem, and attempt to suggest close
9564 // matches (e.g., those that differ only in cv-qualifiers and
9565 // whether the parameter types are references).
9566
9567 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9568 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9569 AddToScope = ExtraArgs.AddToScope;
9570 return Result;
9571 }
9572 }
9573
9574 // Unqualified local friend declarations are required to resolve
9575 // to something.
9576 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9577 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9578 *this, Previous, NewFD, ExtraArgs, true, S)) {
9579 AddToScope = ExtraArgs.AddToScope;
9580 return Result;
9581 }
9582 }
9583 } else if (!D.isFunctionDefinition() &&
9584 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9585 !isFriend && !isFunctionTemplateSpecialization &&
9586 !isMemberSpecialization) {
9587 // An out-of-line member function declaration must also be a
9588 // definition (C++ [class.mfct]p2).
9589 // Note that this is not the case for explicit specializations of
9590 // function templates or member functions of class templates, per
9591 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9592 // extension for compatibility with old SWIG code which likes to
9593 // generate them.
9594 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9595 << D.getCXXScopeSpec().getRange();
9596 }
9597 }
9598
9599 ProcessPragmaWeak(S, NewFD);
9600 checkAttributesAfterMerging(*this, *NewFD);
9601
9602 AddKnownFunctionAttributes(NewFD);
9603
9604 if (NewFD->hasAttr<OverloadableAttr>() &&
9605 !NewFD->getType()->getAs<FunctionProtoType>()) {
9606 Diag(NewFD->getLocation(),
9607 diag::err_attribute_overloadable_no_prototype)
9608 << NewFD;
9609
9610 // Turn this into a variadic function with no parameters.
9611 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9612 FunctionProtoType::ExtProtoInfo EPI(
9613 Context.getDefaultCallingConvention(true, false));
9614 EPI.Variadic = true;
9615 EPI.ExtInfo = FT->getExtInfo();
9616
9617 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9618 NewFD->setType(R);
9619 }
9620
9621 // If there's a #pragma GCC visibility in scope, and this isn't a class
9622 // member, set the visibility of this function.
9623 if (!DC->isRecord() && NewFD->isExternallyVisible())
9624 AddPushedVisibilityAttribute(NewFD);
9625
9626 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9627 // marking the function.
9628 AddCFAuditedAttribute(NewFD);
9629
9630 // If this is a function definition, check if we have to apply optnone due to
9631 // a pragma.
9632 if(D.isFunctionDefinition())
9633 AddRangeBasedOptnone(NewFD);
9634
9635 // If this is the first declaration of an extern C variable, update
9636 // the map of such variables.
9637 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9638 isIncompleteDeclExternC(*this, NewFD))
9639 RegisterLocallyScopedExternCDecl(NewFD, S);
9640
9641 // Set this FunctionDecl's range up to the right paren.
9642 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9643
9644 if (D.isRedeclaration() && !Previous.empty()) {
9645 NamedDecl *Prev = Previous.getRepresentativeDecl();
9646 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9647 isMemberSpecialization ||
9648 isFunctionTemplateSpecialization,
9649 D.isFunctionDefinition());
9650 }
9651
9652 if (getLangOpts().CUDA) {
9653 IdentifierInfo *II = NewFD->getIdentifier();
9654 if (II && II->isStr(getCudaConfigureFuncName()) &&
9655 !NewFD->isInvalidDecl() &&
9656 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9657 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9658 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9659 << getCudaConfigureFuncName();
9660 Context.setcudaConfigureCallDecl(NewFD);
9661 }
9662
9663 // Variadic functions, other than a *declaration* of printf, are not allowed
9664 // in device-side CUDA code, unless someone passed
9665 // -fcuda-allow-variadic-functions.
9666 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9667 (NewFD->hasAttr<CUDADeviceAttr>() ||
9668 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9669 !(II && II->isStr("printf") && NewFD->isExternC() &&
9670 !D.isFunctionDefinition())) {
9671 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9672 }
9673 }
9674
9675 MarkUnusedFileScopedDecl(NewFD);
9676
9677
9678
9679 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9680 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9681 if ((getLangOpts().OpenCLVersion >= 120)
9682 && (SC == SC_Static)) {
9683 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9684 D.setInvalidType();
9685 }
9686
9687 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9688 if (!NewFD->getReturnType()->isVoidType()) {
9689 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9690 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9691 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9692 : FixItHint());
9693 D.setInvalidType();
9694 }
9695
9696 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9697 for (auto Param : NewFD->parameters())
9698 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9699
9700 if (getLangOpts().OpenCLCPlusPlus) {
9701 if (DC->isRecord()) {
9702 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9703 D.setInvalidType();
9704 }
9705 if (FunctionTemplate) {
9706 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9707 D.setInvalidType();
9708 }
9709 }
9710 }
9711
9712 if (getLangOpts().CPlusPlus) {
9713 if (FunctionTemplate) {
9714 if (NewFD->isInvalidDecl())
9715 FunctionTemplate->setInvalidDecl();
9716 return FunctionTemplate;
9717 }
9718
9719 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9720 CompleteMemberSpecialization(NewFD, Previous);
9721 }
9722
9723 for (const ParmVarDecl *Param : NewFD->parameters()) {
9724 QualType PT = Param->getType();
9725
9726 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9727 // types.
9728 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9729 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9730 QualType ElemTy = PipeTy->getElementType();
9731 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9732 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9733 D.setInvalidType();
9734 }
9735 }
9736 }
9737 }
9738
9739 // Here we have an function template explicit specialization at class scope.
9740 // The actual specialization will be postponed to template instatiation
9741 // time via the ClassScopeFunctionSpecializationDecl node.
9742 if (isDependentClassScopeExplicitSpecialization) {
9743 ClassScopeFunctionSpecializationDecl *NewSpec =
9744 ClassScopeFunctionSpecializationDecl::Create(
9745 Context, CurContext, NewFD->getLocation(),
9746 cast<CXXMethodDecl>(NewFD),
9747 HasExplicitTemplateArgs, TemplateArgs);
9748 CurContext->addDecl(NewSpec);
9749 AddToScope = false;
9750 }
9751
9752 // Diagnose availability attributes. Availability cannot be used on functions
9753 // that are run during load/unload.
9754 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9755 if (NewFD->hasAttr<ConstructorAttr>()) {
9756 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9757 << 1;
9758 NewFD->dropAttr<AvailabilityAttr>();
9759 }
9760 if (NewFD->hasAttr<DestructorAttr>()) {
9761 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9762 << 2;
9763 NewFD->dropAttr<AvailabilityAttr>();
9764 }
9765 }
9766
9767 // Diagnose no_builtin attribute on function declaration that are not a
9768 // definition.
9769 // FIXME: We should really be doing this in
9770 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9771 // the FunctionDecl and at this point of the code
9772 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9773 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9774 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9775 switch (D.getFunctionDefinitionKind()) {
9776 case FDK_Defaulted:
9777 case FDK_Deleted:
9778 Diag(NBA->getLocation(),
9779 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9780 << NBA->getSpelling();
9781 break;
9782 case FDK_Declaration:
9783 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9784 << NBA->getSpelling();
9785 break;
9786 case FDK_Definition:
9787 break;
9788 }
9789
9790 return NewFD;
9791}
9792
9793/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9794/// when __declspec(code_seg) "is applied to a class, all member functions of
9795/// the class and nested classes -- this includes compiler-generated special
9796/// member functions -- are put in the specified segment."
9797/// The actual behavior is a little more complicated. The Microsoft compiler
9798/// won't check outer classes if there is an active value from #pragma code_seg.
9799/// The CodeSeg is always applied from the direct parent but only from outer
9800/// classes when the #pragma code_seg stack is empty. See:
9801/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9802/// available since MS has removed the page.
9803static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9804 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9805 if (!Method)
9806 return nullptr;
9807 const CXXRecordDecl *Parent = Method->getParent();
9808 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9809 Attr *NewAttr = SAttr->clone(S.getASTContext());
9810 NewAttr->setImplicit(true);
9811 return NewAttr;
9812 }
9813
9814 // The Microsoft compiler won't check outer classes for the CodeSeg
9815 // when the #pragma code_seg stack is active.
9816 if (S.CodeSegStack.CurrentValue)
9817 return nullptr;
9818
9819 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9820 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9821 Attr *NewAttr = SAttr->clone(S.getASTContext());
9822 NewAttr->setImplicit(true);
9823 return NewAttr;
9824 }
9825 }
9826 return nullptr;
9827}
9828
9829/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9830/// containing class. Otherwise it will return implicit SectionAttr if the
9831/// function is a definition and there is an active value on CodeSegStack
9832/// (from the current #pragma code-seg value).
9833///
9834/// \param FD Function being declared.
9835/// \param IsDefinition Whether it is a definition or just a declarartion.
9836/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9837/// nullptr if no attribute should be added.
9838Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9839 bool IsDefinition) {
9840 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9841 return A;
9842 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9843 CodeSegStack.CurrentValue)
9844 return SectionAttr::CreateImplicit(
9845 getASTContext(), CodeSegStack.CurrentValue->getString(),
9846 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9847 SectionAttr::Declspec_allocate);
9848 return nullptr;
9849}
9850
9851/// Determines if we can perform a correct type check for \p D as a
9852/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9853/// best-effort check.
9854///
9855/// \param NewD The new declaration.
9856/// \param OldD The old declaration.
9857/// \param NewT The portion of the type of the new declaration to check.
9858/// \param OldT The portion of the type of the old declaration to check.
9859bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9860 QualType NewT, QualType OldT) {
9861 if (!NewD->getLexicalDeclContext()->isDependentContext())
9862 return true;
9863
9864 // For dependently-typed local extern declarations and friends, we can't
9865 // perform a correct type check in general until instantiation:
9866 //
9867 // int f();
9868 // template<typename T> void g() { T f(); }
9869 //
9870 // (valid if g() is only instantiated with T = int).
9871 if (NewT->isDependentType() &&
9872 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9873 return false;
9874
9875 // Similarly, if the previous declaration was a dependent local extern
9876 // declaration, we don't really know its type yet.
9877 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9878 return false;
9879
9880 return true;
9881}
9882
9883/// Checks if the new declaration declared in dependent context must be
9884/// put in the same redeclaration chain as the specified declaration.
9885///
9886/// \param D Declaration that is checked.
9887/// \param PrevDecl Previous declaration found with proper lookup method for the
9888/// same declaration name.
9889/// \returns True if D must be added to the redeclaration chain which PrevDecl
9890/// belongs to.
9891///
9892bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9893 if (!D->getLexicalDeclContext()->isDependentContext())
9894 return true;
9895
9896 // Don't chain dependent friend function definitions until instantiation, to
9897 // permit cases like
9898 //
9899 // void func();
9900 // template<typename T> class C1 { friend void func() {} };
9901 // template<typename T> class C2 { friend void func() {} };
9902 //
9903 // ... which is valid if only one of C1 and C2 is ever instantiated.
9904 //
9905 // FIXME: This need only apply to function definitions. For now, we proxy
9906 // this by checking for a file-scope function. We do not want this to apply
9907 // to friend declarations nominating member functions, because that gets in
9908 // the way of access checks.
9909 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9910 return false;
9911
9912 auto *VD = dyn_cast<ValueDecl>(D);
9913 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9914 return !VD || !PrevVD ||
9915 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9916 PrevVD->getType());
9917}
9918
9919/// Check the target attribute of the function for MultiVersion
9920/// validity.
9921///
9922/// Returns true if there was an error, false otherwise.
9923static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9924 const auto *TA = FD->getAttr<TargetAttr>();
9925 assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute"
) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 9925, __PRETTY_FUNCTION__))
;
9926 ParsedTargetAttr ParseInfo = TA->parse();
9927 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9928 enum ErrType { Feature = 0, Architecture = 1 };
9929
9930 if (!ParseInfo.Architecture.empty() &&
9931 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9932 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9933 << Architecture << ParseInfo.Architecture;
9934 return true;
9935 }
9936
9937 for (const auto &Feat : ParseInfo.Features) {
9938 auto BareFeat = StringRef{Feat}.substr(1);
9939 if (Feat[0] == '-') {
9940 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9941 << Feature << ("no-" + BareFeat).str();
9942 return true;
9943 }
9944
9945 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9946 !TargetInfo.isValidFeatureName(BareFeat)) {
9947 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9948 << Feature << BareFeat;
9949 return true;
9950 }
9951 }
9952 return false;
9953}
9954
9955static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9956 MultiVersionKind MVType) {
9957 for (const Attr *A : FD->attrs()) {
9958 switch (A->getKind()) {
9959 case attr::CPUDispatch:
9960 case attr::CPUSpecific:
9961 if (MVType != MultiVersionKind::CPUDispatch &&
9962 MVType != MultiVersionKind::CPUSpecific)
9963 return true;
9964 break;
9965 case attr::Target:
9966 if (MVType != MultiVersionKind::Target)
9967 return true;
9968 break;
9969 default:
9970 return true;
9971 }
9972 }
9973 return false;
9974}
9975
9976bool Sema::areMultiversionVariantFunctionsCompatible(
9977 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9978 const PartialDiagnostic &NoProtoDiagID,
9979 const PartialDiagnosticAt &NoteCausedDiagIDAt,
9980 const PartialDiagnosticAt &NoSupportDiagIDAt,
9981 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9982 bool ConstexprSupported, bool CLinkageMayDiffer) {
9983 enum DoesntSupport {
9984 FuncTemplates = 0,
9985 VirtFuncs = 1,
9986 DeducedReturn = 2,
9987 Constructors = 3,
9988 Destructors = 4,
9989 DeletedFuncs = 5,
9990 DefaultedFuncs = 6,
9991 ConstexprFuncs = 7,
9992 ConstevalFuncs = 8,
9993 };
9994 enum Different {
9995 CallingConv = 0,
9996 ReturnType = 1,
9997 ConstexprSpec = 2,
9998 InlineSpec = 3,
9999 StorageClass = 4,
10000 Linkage = 5,
10001 };
10002
10003 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10004 !OldFD->getType()->getAs<FunctionProtoType>()) {
10005 Diag(OldFD->getLocation(), NoProtoDiagID);
10006 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10007 return true;
10008 }
10009
10010 if (NoProtoDiagID.getDiagID() != 0 &&
10011 !NewFD->getType()->getAs<FunctionProtoType>())
10012 return Diag(NewFD->getLocation(), NoProtoDiagID);
10013
10014 if (!TemplatesSupported &&
10015 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10016 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10017 << FuncTemplates;
10018
10019 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10020 if (NewCXXFD->isVirtual())
10021 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10022 << VirtFuncs;
10023
10024 if (isa<CXXConstructorDecl>(NewCXXFD))
10025 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10026 << Constructors;
10027
10028 if (isa<CXXDestructorDecl>(NewCXXFD))
10029 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10030 << Destructors;
10031 }
10032
10033 if (NewFD->isDeleted())
10034 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10035 << DeletedFuncs;
10036
10037 if (NewFD->isDefaulted())
10038 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10039 << DefaultedFuncs;
10040
10041 if (!ConstexprSupported && NewFD->isConstexpr())
10042 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10043 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10044
10045 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10046 const auto *NewType = cast<FunctionType>(NewQType);
10047 QualType NewReturnType = NewType->getReturnType();
10048
10049 if (NewReturnType->isUndeducedType())
10050 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10051 << DeducedReturn;
10052
10053 // Ensure the return type is identical.
10054 if (OldFD) {
10055 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10056 const auto *OldType = cast<FunctionType>(OldQType);
10057 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10058 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10059
10060 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10061 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10062
10063 QualType OldReturnType = OldType->getReturnType();
10064
10065 if (OldReturnType != NewReturnType)
10066 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10067
10068 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10069 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10070
10071 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10072 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10073
10074 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10075 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10076
10077 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10078 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10079
10080 if (CheckEquivalentExceptionSpec(
10081 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10082 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10083 return true;
10084 }
10085 return false;
10086}
10087
10088static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10089 const FunctionDecl *NewFD,
10090 bool CausesMV,
10091 MultiVersionKind MVType) {
10092 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10093 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10094 if (OldFD)
10095 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10096 return true;
10097 }
10098
10099 bool IsCPUSpecificCPUDispatchMVType =
10100 MVType == MultiVersionKind::CPUDispatch ||
10101 MVType == MultiVersionKind::CPUSpecific;
10102
10103 // For now, disallow all other attributes. These should be opt-in, but
10104 // an analysis of all of them is a future FIXME.
10105 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
10106 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
10107 << IsCPUSpecificCPUDispatchMVType;
10108 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10109 return true;
10110 }
10111
10112 if (HasNonMultiVersionAttributes(NewFD, MVType))
10113 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10114 << IsCPUSpecificCPUDispatchMVType;
10115
10116 // Only allow transition to MultiVersion if it hasn't been used.
10117 if (OldFD && CausesMV && OldFD->isUsed(false))
10118 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10119
10120 return S.areMultiversionVariantFunctionsCompatible(
10121 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10122 PartialDiagnosticAt(NewFD->getLocation(),
10123 S.PDiag(diag::note_multiversioning_caused_here)),
10124 PartialDiagnosticAt(NewFD->getLocation(),
10125 S.PDiag(diag::err_multiversion_doesnt_support)
10126 << IsCPUSpecificCPUDispatchMVType),
10127 PartialDiagnosticAt(NewFD->getLocation(),
10128 S.PDiag(diag::err_multiversion_diff)),
10129 /*TemplatesSupported=*/false,
10130 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10131 /*CLinkageMayDiffer=*/false);
10132}
10133
10134/// Check the validity of a multiversion function declaration that is the
10135/// first of its kind. Also sets the multiversion'ness' of the function itself.
10136///
10137/// This sets NewFD->isInvalidDecl() to true if there was an error.
10138///
10139/// Returns true if there was an error, false otherwise.
10140static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10141 MultiVersionKind MVType,
10142 const TargetAttr *TA) {
10143 assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10144, __PRETTY_FUNCTION__))
10144 "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10144, __PRETTY_FUNCTION__))
;
10145
10146 // Target only causes MV if it is default, otherwise this is a normal
10147 // function.
10148 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10149 return false;
10150
10151 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10152 FD->setInvalidDecl();
10153 return true;
10154 }
10155
10156 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10157 FD->setInvalidDecl();
10158 return true;
10159 }
10160
10161 FD->setIsMultiVersion();
10162 return false;
10163}
10164
10165static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10166 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10167 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10168 return true;
10169 }
10170
10171 return false;
10172}
10173
10174static bool CheckTargetCausesMultiVersioning(
10175 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10176 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10177 LookupResult &Previous) {
10178 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10179 ParsedTargetAttr NewParsed = NewTA->parse();
10180 // Sort order doesn't matter, it just needs to be consistent.
10181 llvm::sort(NewParsed.Features);
10182
10183 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10184 // to change, this is a simple redeclaration.
10185 if (!NewTA->isDefaultVersion() &&
10186 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10187 return false;
10188
10189 // Otherwise, this decl causes MultiVersioning.
10190 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10191 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10192 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10193 NewFD->setInvalidDecl();
10194 return true;
10195 }
10196
10197 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10198 MultiVersionKind::Target)) {
10199 NewFD->setInvalidDecl();
10200 return true;
10201 }
10202
10203 if (CheckMultiVersionValue(S, NewFD)) {
10204 NewFD->setInvalidDecl();
10205 return true;
10206 }
10207
10208 // If this is 'default', permit the forward declaration.
10209 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10210 Redeclaration = true;
10211 OldDecl = OldFD;
10212 OldFD->setIsMultiVersion();
10213 NewFD->setIsMultiVersion();
10214 return false;
10215 }
10216
10217 if (CheckMultiVersionValue(S, OldFD)) {
10218 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10219 NewFD->setInvalidDecl();
10220 return true;
10221 }
10222
10223 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10224
10225 if (OldParsed == NewParsed) {
10226 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10227 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10228 NewFD->setInvalidDecl();
10229 return true;
10230 }
10231
10232 for (const auto *FD : OldFD->redecls()) {
10233 const auto *CurTA = FD->getAttr<TargetAttr>();
10234 // We allow forward declarations before ANY multiversioning attributes, but
10235 // nothing after the fact.
10236 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10237 (!CurTA || CurTA->isInherited())) {
10238 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10239 << 0;
10240 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10241 NewFD->setInvalidDecl();
10242 return true;
10243 }
10244 }
10245
10246 OldFD->setIsMultiVersion();
10247 NewFD->setIsMultiVersion();
10248 Redeclaration = false;
10249 MergeTypeWithPrevious = false;
10250 OldDecl = nullptr;
10251 Previous.clear();
10252 return false;
10253}
10254
10255/// Check the validity of a new function declaration being added to an existing
10256/// multiversioned declaration collection.
10257static bool CheckMultiVersionAdditionalDecl(
10258 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10259 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10260 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10261 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10262 LookupResult &Previous) {
10263
10264 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10265 // Disallow mixing of multiversioning types.
10266 if ((OldMVType == MultiVersionKind::Target &&
10267 NewMVType != MultiVersionKind::Target) ||
10268 (NewMVType == MultiVersionKind::Target &&
10269 OldMVType != MultiVersionKind::Target)) {
10270 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10271 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10272 NewFD->setInvalidDecl();
10273 return true;
10274 }
10275
10276 ParsedTargetAttr NewParsed;
10277 if (NewTA) {
10278 NewParsed = NewTA->parse();
10279 llvm::sort(NewParsed.Features);
10280 }
10281
10282 bool UseMemberUsingDeclRules =
10283 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10284
10285 // Next, check ALL non-overloads to see if this is a redeclaration of a
10286 // previous member of the MultiVersion set.
10287 for (NamedDecl *ND : Previous) {
10288 FunctionDecl *CurFD = ND->getAsFunction();
10289 if (!CurFD)
10290 continue;
10291 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10292 continue;
10293
10294 if (NewMVType == MultiVersionKind::Target) {
10295 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10296 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10297 NewFD->setIsMultiVersion();
10298 Redeclaration = true;
10299 OldDecl = ND;
10300 return false;
10301 }
10302
10303 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10304 if (CurParsed == NewParsed) {
10305 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10306 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10307 NewFD->setInvalidDecl();
10308 return true;
10309 }
10310 } else {
10311 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10312 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10313 // Handle CPUDispatch/CPUSpecific versions.
10314 // Only 1 CPUDispatch function is allowed, this will make it go through
10315 // the redeclaration errors.
10316 if (NewMVType == MultiVersionKind::CPUDispatch &&
10317 CurFD->hasAttr<CPUDispatchAttr>()) {
10318 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10319 std::equal(
10320 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10321 NewCPUDisp->cpus_begin(),
10322 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10323 return Cur->getName() == New->getName();
10324 })) {
10325 NewFD->setIsMultiVersion();
10326 Redeclaration = true;
10327 OldDecl = ND;
10328 return false;
10329 }
10330
10331 // If the declarations don't match, this is an error condition.
10332 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10333 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10334 NewFD->setInvalidDecl();
10335 return true;
10336 }
10337 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10338
10339 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10340 std::equal(
10341 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10342 NewCPUSpec->cpus_begin(),
10343 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10344 return Cur->getName() == New->getName();
10345 })) {
10346 NewFD->setIsMultiVersion();
10347 Redeclaration = true;
10348 OldDecl = ND;
10349 return false;
10350 }
10351
10352 // Only 1 version of CPUSpecific is allowed for each CPU.
10353 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10354 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10355 if (CurII == NewII) {
10356 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10357 << NewII;
10358 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10359 NewFD->setInvalidDecl();
10360 return true;
10361 }
10362 }
10363 }
10364 }
10365 // If the two decls aren't the same MVType, there is no possible error
10366 // condition.
10367 }
10368 }
10369
10370 // Else, this is simply a non-redecl case. Checking the 'value' is only
10371 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10372 // handled in the attribute adding step.
10373 if (NewMVType == MultiVersionKind::Target &&
10374 CheckMultiVersionValue(S, NewFD)) {
10375 NewFD->setInvalidDecl();
10376 return true;
10377 }
10378
10379 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10380 !OldFD->isMultiVersion(), NewMVType)) {
10381 NewFD->setInvalidDecl();
10382 return true;
10383 }
10384
10385 // Permit forward declarations in the case where these two are compatible.
10386 if (!OldFD->isMultiVersion()) {
10387 OldFD->setIsMultiVersion();
10388 NewFD->setIsMultiVersion();
10389 Redeclaration = true;
10390 OldDecl = OldFD;
10391 return false;
10392 }
10393
10394 NewFD->setIsMultiVersion();
10395 Redeclaration = false;
10396 MergeTypeWithPrevious = false;
10397 OldDecl = nullptr;
10398 Previous.clear();
10399 return false;
10400}
10401
10402
10403/// Check the validity of a mulitversion function declaration.
10404/// Also sets the multiversion'ness' of the function itself.
10405///
10406/// This sets NewFD->isInvalidDecl() to true if there was an error.
10407///
10408/// Returns true if there was an error, false otherwise.
10409static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10410 bool &Redeclaration, NamedDecl *&OldDecl,
10411 bool &MergeTypeWithPrevious,
10412 LookupResult &Previous) {
10413 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10414 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10415 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10416
10417 // Mixing Multiversioning types is prohibited.
10418 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10419 (NewCPUDisp && NewCPUSpec)) {
10420 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10421 NewFD->setInvalidDecl();
10422 return true;
10423 }
10424
10425 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10426
10427 // Main isn't allowed to become a multiversion function, however it IS
10428 // permitted to have 'main' be marked with the 'target' optimization hint.
10429 if (NewFD->isMain()) {
10430 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10431 MVType == MultiVersionKind::CPUDispatch ||
10432 MVType == MultiVersionKind::CPUSpecific) {
10433 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10434 NewFD->setInvalidDecl();
10435 return true;
10436 }
10437 return false;
10438 }
10439
10440 if (!OldDecl || !OldDecl->getAsFunction() ||
10441 OldDecl->getDeclContext()->getRedeclContext() !=
10442 NewFD->getDeclContext()->getRedeclContext()) {
10443 // If there's no previous declaration, AND this isn't attempting to cause
10444 // multiversioning, this isn't an error condition.
10445 if (MVType == MultiVersionKind::None)
10446 return false;
10447 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10448 }
10449
10450 FunctionDecl *OldFD = OldDecl->getAsFunction();
10451
10452 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10453 return false;
10454
10455 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10456 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10457 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10458 NewFD->setInvalidDecl();
10459 return true;
10460 }
10461
10462 // Handle the target potentially causes multiversioning case.
10463 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10464 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10465 Redeclaration, OldDecl,
10466 MergeTypeWithPrevious, Previous);
10467
10468 // At this point, we have a multiversion function decl (in OldFD) AND an
10469 // appropriate attribute in the current function decl. Resolve that these are
10470 // still compatible with previous declarations.
10471 return CheckMultiVersionAdditionalDecl(
10472 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10473 OldDecl, MergeTypeWithPrevious, Previous);
10474}
10475
10476/// Perform semantic checking of a new function declaration.
10477///
10478/// Performs semantic analysis of the new function declaration
10479/// NewFD. This routine performs all semantic checking that does not
10480/// require the actual declarator involved in the declaration, and is
10481/// used both for the declaration of functions as they are parsed
10482/// (called via ActOnDeclarator) and for the declaration of functions
10483/// that have been instantiated via C++ template instantiation (called
10484/// via InstantiateDecl).
10485///
10486/// \param IsMemberSpecialization whether this new function declaration is
10487/// a member specialization (that replaces any definition provided by the
10488/// previous declaration).
10489///
10490/// This sets NewFD->isInvalidDecl() to true if there was an error.
10491///
10492/// \returns true if the function declaration is a redeclaration.
10493bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10494 LookupResult &Previous,
10495 bool IsMemberSpecialization) {
10496 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10497, __PRETTY_FUNCTION__))
10497 "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10497, __PRETTY_FUNCTION__))
;
10498
10499 // Determine whether the type of this function should be merged with
10500 // a previous visible declaration. This never happens for functions in C++,
10501 // and always happens in C if the previous declaration was visible.
10502 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10503 !Previous.isShadowed();
10504
10505 bool Redeclaration = false;
10506 NamedDecl *OldDecl = nullptr;
10507 bool MayNeedOverloadableChecks = false;
10508
10509 // Merge or overload the declaration with an existing declaration of
10510 // the same name, if appropriate.
10511 if (!Previous.empty()) {
10512 // Determine whether NewFD is an overload of PrevDecl or
10513 // a declaration that requires merging. If it's an overload,
10514 // there's no more work to do here; we'll just add the new
10515 // function to the scope.
10516 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10517 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10518 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10519 Redeclaration = true;
10520 OldDecl = Candidate;
10521 }
10522 } else {
10523 MayNeedOverloadableChecks = true;
10524 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10525 /*NewIsUsingDecl*/ false)) {
10526 case Ovl_Match:
10527 Redeclaration = true;
10528 break;
10529
10530 case Ovl_NonFunction:
10531 Redeclaration = true;
10532 break;
10533
10534 case Ovl_Overload:
10535 Redeclaration = false;
10536 break;
10537 }
10538 }
10539 }
10540
10541 // Check for a previous extern "C" declaration with this name.
10542 if (!Redeclaration &&
10543 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10544 if (!Previous.empty()) {
10545 // This is an extern "C" declaration with the same name as a previous
10546 // declaration, and thus redeclares that entity...
10547 Redeclaration = true;
10548 OldDecl = Previous.getFoundDecl();
10549 MergeTypeWithPrevious = false;
10550
10551 // ... except in the presence of __attribute__((overloadable)).
10552 if (OldDecl->hasAttr<OverloadableAttr>() ||
10553 NewFD->hasAttr<OverloadableAttr>()) {
10554 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10555 MayNeedOverloadableChecks = true;
10556 Redeclaration = false;
10557 OldDecl = nullptr;
10558 }
10559 }
10560 }
10561 }
10562
10563 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10564 MergeTypeWithPrevious, Previous))
10565 return Redeclaration;
10566
10567 // C++11 [dcl.constexpr]p8:
10568 // A constexpr specifier for a non-static member function that is not
10569 // a constructor declares that member function to be const.
10570 //
10571 // This needs to be delayed until we know whether this is an out-of-line
10572 // definition of a static member function.
10573 //
10574 // This rule is not present in C++1y, so we produce a backwards
10575 // compatibility warning whenever it happens in C++11.
10576 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10577 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10578 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10579 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10580 CXXMethodDecl *OldMD = nullptr;
10581 if (OldDecl)
10582 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10583 if (!OldMD || !OldMD->isStatic()) {
10584 const FunctionProtoType *FPT =
10585 MD->getType()->castAs<FunctionProtoType>();
10586 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10587 EPI.TypeQuals.addConst();
10588 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10589 FPT->getParamTypes(), EPI));
10590
10591 // Warn that we did this, if we're not performing template instantiation.
10592 // In that case, we'll have warned already when the template was defined.
10593 if (!inTemplateInstantiation()) {
10594 SourceLocation AddConstLoc;
10595 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10596 .IgnoreParens().getAs<FunctionTypeLoc>())
10597 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10598
10599 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10600 << FixItHint::CreateInsertion(AddConstLoc, " const");
10601 }
10602 }
10603 }
10604
10605 if (Redeclaration) {
10606 // NewFD and OldDecl represent declarations that need to be
10607 // merged.
10608 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10609 NewFD->setInvalidDecl();
10610 return Redeclaration;
10611 }
10612
10613 Previous.clear();
10614 Previous.addDecl(OldDecl);
10615
10616 if (FunctionTemplateDecl *OldTemplateDecl =
10617 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10618 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10619 FunctionTemplateDecl *NewTemplateDecl
10620 = NewFD->getDescribedFunctionTemplate();
10621 assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch"
) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10621, __PRETTY_FUNCTION__))
;
10622
10623 // The call to MergeFunctionDecl above may have created some state in
10624 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10625 // can add it as a redeclaration.
10626 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10627
10628 NewFD->setPreviousDeclaration(OldFD);
10629 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10630 if (NewFD->isCXXClassMember()) {
10631 NewFD->setAccess(OldTemplateDecl->getAccess());
10632 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10633 }
10634
10635 // If this is an explicit specialization of a member that is a function
10636 // template, mark it as a member specialization.
10637 if (IsMemberSpecialization &&
10638 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10639 NewTemplateDecl->setMemberSpecialization();
10640 assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast
<void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10640, __PRETTY_FUNCTION__))
;
10641 // Explicit specializations of a member template do not inherit deleted
10642 // status from the parent member template that they are specializing.
10643 if (OldFD->isDeleted()) {
10644 // FIXME: This assert will not hold in the presence of modules.
10645 assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void
> (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10645, __PRETTY_FUNCTION__))
;
10646 // FIXME: We need an update record for this AST mutation.
10647 OldFD->setDeletedAsWritten(false);
10648 }
10649 }
10650
10651 } else {
10652 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10653 auto *OldFD = cast<FunctionDecl>(OldDecl);
10654 // This needs to happen first so that 'inline' propagates.
10655 NewFD->setPreviousDeclaration(OldFD);
10656 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10657 if (NewFD->isCXXClassMember())
10658 NewFD->setAccess(OldFD->getAccess());
10659 }
10660 }
10661 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10662 !NewFD->getAttr<OverloadableAttr>()) {
10663 assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10668, __PRETTY_FUNCTION__))
10664 llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10668, __PRETTY_FUNCTION__))
10665 [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10668, __PRETTY_FUNCTION__))
10666 return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10668, __PRETTY_FUNCTION__))
10667 })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10668, __PRETTY_FUNCTION__))
10668 "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10668, __PRETTY_FUNCTION__))
;
10669
10670 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10671 const auto *FD = dyn_cast<FunctionDecl>(ND);
10672 return FD && !FD->hasAttr<OverloadableAttr>();
10673 });
10674
10675 if (OtherUnmarkedIter != Previous.end()) {
10676 Diag(NewFD->getLocation(),
10677 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10678 Diag((*OtherUnmarkedIter)->getLocation(),
10679 diag::note_attribute_overloadable_prev_overload)
10680 << false;
10681
10682 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10683 }
10684 }
10685
10686 // Semantic checking for this function declaration (in isolation).
10687
10688 if (getLangOpts().CPlusPlus) {
10689 // C++-specific checks.
10690 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10691 CheckConstructor(Constructor);
10692 } else if (CXXDestructorDecl *Destructor =
10693 dyn_cast<CXXDestructorDecl>(NewFD)) {
10694 CXXRecordDecl *Record = Destructor->getParent();
10695 QualType ClassType = Context.getTypeDeclType(Record);
10696
10697 // FIXME: Shouldn't we be able to perform this check even when the class
10698 // type is dependent? Both gcc and edg can handle that.
10699 if (!ClassType->isDependentType()) {
10700 DeclarationName Name
10701 = Context.DeclarationNames.getCXXDestructorName(
10702 Context.getCanonicalType(ClassType));
10703 if (NewFD->getDeclName() != Name) {
10704 Diag(NewFD->getLocation(), diag::err_destructor_name);
10705 NewFD->setInvalidDecl();
10706 return Redeclaration;
10707 }
10708 }
10709 } else if (CXXConversionDecl *Conversion
10710 = dyn_cast<CXXConversionDecl>(NewFD)) {
10711 ActOnConversionDeclarator(Conversion);
10712 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10713 if (auto *TD = Guide->getDescribedFunctionTemplate())
10714 CheckDeductionGuideTemplate(TD);
10715
10716 // A deduction guide is not on the list of entities that can be
10717 // explicitly specialized.
10718 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10719 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10720 << /*explicit specialization*/ 1;
10721 }
10722
10723 // Find any virtual functions that this function overrides.
10724 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10725 if (!Method->isFunctionTemplateSpecialization() &&
10726 !Method->getDescribedFunctionTemplate() &&
10727 Method->isCanonicalDecl()) {
10728 if (AddOverriddenMethods(Method->getParent(), Method)) {
10729 // If the function was marked as "static", we have a problem.
10730 if (NewFD->getStorageClass() == SC_Static) {
10731 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10732 }
10733 }
10734 }
10735 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10736 // C++2a [class.virtual]p6
10737 // A virtual method shall not have a requires-clause.
10738 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10739 diag::err_constrained_virtual_method);
10740
10741 if (Method->isStatic())
10742 checkThisInStaticMemberFunctionType(Method);
10743 }
10744
10745 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10746 if (NewFD->isOverloadedOperator() &&
10747 CheckOverloadedOperatorDeclaration(NewFD)) {
10748 NewFD->setInvalidDecl();
10749 return Redeclaration;
10750 }
10751
10752 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10753 if (NewFD->getLiteralIdentifier() &&
10754 CheckLiteralOperatorDeclaration(NewFD)) {
10755 NewFD->setInvalidDecl();
10756 return Redeclaration;
10757 }
10758
10759 // In C++, check default arguments now that we have merged decls. Unless
10760 // the lexical context is the class, because in this case this is done
10761 // during delayed parsing anyway.
10762 if (!CurContext->isRecord())
10763 CheckCXXDefaultArguments(NewFD);
10764
10765 // If this function declares a builtin function, check the type of this
10766 // declaration against the expected type for the builtin.
10767 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10768 ASTContext::GetBuiltinTypeError Error;
10769 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10770 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10771 // If the type of the builtin differs only in its exception
10772 // specification, that's OK.
10773 // FIXME: If the types do differ in this way, it would be better to
10774 // retain the 'noexcept' form of the type.
10775 if (!T.isNull() &&
10776 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10777 NewFD->getType()))
10778 // The type of this function differs from the type of the builtin,
10779 // so forget about the builtin entirely.
10780 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10781 }
10782
10783 // If this function is declared as being extern "C", then check to see if
10784 // the function returns a UDT (class, struct, or union type) that is not C
10785 // compatible, and if it does, warn the user.
10786 // But, issue any diagnostic on the first declaration only.
10787 if (Previous.empty() && NewFD->isExternC()) {
10788 QualType R = NewFD->getReturnType();
10789 if (R->isIncompleteType() && !R->isVoidType())
10790 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10791 << NewFD << R;
10792 else if (!R.isPODType(Context) && !R->isVoidType() &&
10793 !R->isObjCObjectPointerType())
10794 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10795 }
10796
10797 // C++1z [dcl.fct]p6:
10798 // [...] whether the function has a non-throwing exception-specification
10799 // [is] part of the function type
10800 //
10801 // This results in an ABI break between C++14 and C++17 for functions whose
10802 // declared type includes an exception-specification in a parameter or
10803 // return type. (Exception specifications on the function itself are OK in
10804 // most cases, and exception specifications are not permitted in most other
10805 // contexts where they could make it into a mangling.)
10806 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10807 auto HasNoexcept = [&](QualType T) -> bool {
10808 // Strip off declarator chunks that could be between us and a function
10809 // type. We don't need to look far, exception specifications are very
10810 // restricted prior to C++17.
10811 if (auto *RT = T->getAs<ReferenceType>())
10812 T = RT->getPointeeType();
10813 else if (T->isAnyPointerType())
10814 T = T->getPointeeType();
10815 else if (auto *MPT = T->getAs<MemberPointerType>())
10816 T = MPT->getPointeeType();
10817 if (auto *FPT = T->getAs<FunctionProtoType>())
10818 if (FPT->isNothrow())
10819 return true;
10820 return false;
10821 };
10822
10823 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10824 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10825 for (QualType T : FPT->param_types())
10826 AnyNoexcept |= HasNoexcept(T);
10827 if (AnyNoexcept)
10828 Diag(NewFD->getLocation(),
10829 diag::warn_cxx17_compat_exception_spec_in_signature)
10830 << NewFD;
10831 }
10832
10833 if (!Redeclaration && LangOpts.CUDA)
10834 checkCUDATargetOverload(NewFD, Previous);
10835 }
10836 return Redeclaration;
10837}
10838
10839void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10840 // C++11 [basic.start.main]p3:
10841 // A program that [...] declares main to be inline, static or
10842 // constexpr is ill-formed.
10843 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10844 // appear in a declaration of main.
10845 // static main is not an error under C99, but we should warn about it.
10846 // We accept _Noreturn main as an extension.
10847 if (FD->getStorageClass() == SC_Static)
10848 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10849 ? diag::err_static_main : diag::warn_static_main)
10850 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10851 if (FD->isInlineSpecified())
10852 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10853 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10854 if (DS.isNoreturnSpecified()) {
10855 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10856 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10857 Diag(NoreturnLoc, diag::ext_noreturn_main);
10858 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10859 << FixItHint::CreateRemoval(NoreturnRange);
10860 }
10861 if (FD->isConstexpr()) {
10862 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10863 << FD->isConsteval()
10864 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10865 FD->setConstexprKind(CSK_unspecified);
10866 }
10867
10868 if (getLangOpts().OpenCL) {
10869 Diag(FD->getLocation(), diag::err_opencl_no_main)
10870 << FD->hasAttr<OpenCLKernelAttr>();
10871 FD->setInvalidDecl();
10872 return;
10873 }
10874
10875 QualType T = FD->getType();
10876 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10876, __PRETTY_FUNCTION__))
;
10877 const FunctionType* FT = T->castAs<FunctionType>();
10878
10879 // Set default calling convention for main()
10880 if (FT->getCallConv() != CC_C) {
10881 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10882 FD->setType(QualType(FT, 0));
10883 T = Context.getCanonicalType(FD->getType());
10884 }
10885
10886 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10887 // In C with GNU extensions we allow main() to have non-integer return
10888 // type, but we should warn about the extension, and we disable the
10889 // implicit-return-zero rule.
10890
10891 // GCC in C mode accepts qualified 'int'.
10892 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10893 FD->setHasImplicitReturnZero(true);
10894 else {
10895 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10896 SourceRange RTRange = FD->getReturnTypeSourceRange();
10897 if (RTRange.isValid())
10898 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10899 << FixItHint::CreateReplacement(RTRange, "int");
10900 }
10901 } else {
10902 // In C and C++, main magically returns 0 if you fall off the end;
10903 // set the flag which tells us that.
10904 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10905
10906 // All the standards say that main() should return 'int'.
10907 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10908 FD->setHasImplicitReturnZero(true);
10909 else {
10910 // Otherwise, this is just a flat-out error.
10911 SourceRange RTRange = FD->getReturnTypeSourceRange();
10912 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10913 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10914 : FixItHint());
10915 FD->setInvalidDecl(true);
10916 }
10917 }
10918
10919 // Treat protoless main() as nullary.
10920 if (isa<FunctionNoProtoType>(FT)) return;
10921
10922 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10923 unsigned nparams = FTP->getNumParams();
10924 assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void>
(0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10924, __PRETTY_FUNCTION__))
;
10925
10926 bool HasExtraParameters = (nparams > 3);
10927
10928 if (FTP->isVariadic()) {
10929 Diag(FD->getLocation(), diag::ext_variadic_main);
10930 // FIXME: if we had information about the location of the ellipsis, we
10931 // could add a FixIt hint to remove it as a parameter.
10932 }
10933
10934 // Darwin passes an undocumented fourth argument of type char**. If
10935 // other platforms start sprouting these, the logic below will start
10936 // getting shifty.
10937 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10938 HasExtraParameters = false;
10939
10940 if (HasExtraParameters) {
10941 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10942 FD->setInvalidDecl(true);
10943 nparams = 3;
10944 }
10945
10946 // FIXME: a lot of the following diagnostics would be improved
10947 // if we had some location information about types.
10948
10949 QualType CharPP =
10950 Context.getPointerType(Context.getPointerType(Context.CharTy));
10951 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10952
10953 for (unsigned i = 0; i < nparams; ++i) {
10954 QualType AT = FTP->getParamType(i);
10955
10956 bool mismatch = true;
10957
10958 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10959 mismatch = false;
10960 else if (Expected[i] == CharPP) {
10961 // As an extension, the following forms are okay:
10962 // char const **
10963 // char const * const *
10964 // char * const *
10965
10966 QualifierCollector qs;
10967 const PointerType* PT;
10968 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10969 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10970 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10971 Context.CharTy)) {
10972 qs.removeConst();
10973 mismatch = !qs.empty();
10974 }
10975 }
10976
10977 if (mismatch) {
10978 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10979 // TODO: suggest replacing given type with expected type
10980 FD->setInvalidDecl(true);
10981 }
10982 }
10983
10984 if (nparams == 1 && !FD->isInvalidDecl()) {
10985 Diag(FD->getLocation(), diag::warn_main_one_arg);
10986 }
10987
10988 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10989 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10990 FD->setInvalidDecl();
10991 }
10992}
10993
10994void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10995 QualType T = FD->getType();
10996 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 10996, __PRETTY_FUNCTION__))
;
10997 const FunctionType *FT = T->castAs<FunctionType>();
10998
10999 // Set an implicit return of 'zero' if the function can return some integral,
11000 // enumeration, pointer or nullptr type.
11001 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11002 FT->getReturnType()->isAnyPointerType() ||
11003 FT->getReturnType()->isNullPtrType())
11004 // DllMain is exempt because a return value of zero means it failed.
11005 if (FD->getName() != "DllMain")
11006 FD->setHasImplicitReturnZero(true);
11007
11008 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11009 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11010 FD->setInvalidDecl();
11011 }
11012}
11013
11014bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11015 // FIXME: Need strict checking. In C89, we need to check for
11016 // any assignment, increment, decrement, function-calls, or
11017 // commas outside of a sizeof. In C99, it's the same list,
11018 // except that the aforementioned are allowed in unevaluated
11019 // expressions. Everything else falls under the
11020 // "may accept other forms of constant expressions" exception.
11021 // (We never end up here for C++, so the constant expression
11022 // rules there don't matter.)
11023 const Expr *Culprit;
11024 if (Init->isConstantInitializer(Context, false, &Culprit))
11025 return false;
11026 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11027 << Culprit->getSourceRange();
11028 return true;
11029}
11030
11031namespace {
11032 // Visits an initialization expression to see if OrigDecl is evaluated in
11033 // its own initialization and throws a warning if it does.
11034 class SelfReferenceChecker
11035 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11036 Sema &S;
11037 Decl *OrigDecl;
11038 bool isRecordType;
11039 bool isPODType;
11040 bool isReferenceType;
11041
11042 bool isInitList;
11043 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11044
11045 public:
11046 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11047
11048 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11049 S(S), OrigDecl(OrigDecl) {
11050 isPODType = false;
11051 isRecordType = false;
11052 isReferenceType = false;
11053 isInitList = false;
11054 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11055 isPODType = VD->getType().isPODType(S.Context);
11056 isRecordType = VD->getType()->isRecordType();
11057 isReferenceType = VD->getType()->isReferenceType();
11058 }
11059 }
11060
11061 // For most expressions, just call the visitor. For initializer lists,
11062 // track the index of the field being initialized since fields are
11063 // initialized in order allowing use of previously initialized fields.
11064 void CheckExpr(Expr *E) {
11065 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11066 if (!InitList) {
11067 Visit(E);
11068 return;
11069 }
11070
11071 // Track and increment the index here.
11072 isInitList = true;
11073 InitFieldIndex.push_back(0);
11074 for (auto Child : InitList->children()) {
11075 CheckExpr(cast<Expr>(Child));
11076 ++InitFieldIndex.back();
11077 }
11078 InitFieldIndex.pop_back();
11079 }
11080
11081 // Returns true if MemberExpr is checked and no further checking is needed.
11082 // Returns false if additional checking is required.
11083 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11084 llvm::SmallVector<FieldDecl*, 4> Fields;
11085 Expr *Base = E;
11086 bool ReferenceField = false;
11087
11088 // Get the field members used.
11089 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11090 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11091 if (!FD)
11092 return false;
11093 Fields.push_back(FD);
11094 if (FD->getType()->isReferenceType())
11095 ReferenceField = true;
11096 Base = ME->getBase()->IgnoreParenImpCasts();
11097 }
11098
11099 // Keep checking only if the base Decl is the same.
11100 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11101 if (!DRE || DRE->getDecl() != OrigDecl)
11102 return false;
11103
11104 // A reference field can be bound to an unininitialized field.
11105 if (CheckReference && !ReferenceField)
11106 return true;
11107
11108 // Convert FieldDecls to their index number.
11109 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11110 for (const FieldDecl *I : llvm::reverse(Fields))
11111 UsedFieldIndex.push_back(I->getFieldIndex());
11112
11113 // See if a warning is needed by checking the first difference in index
11114 // numbers. If field being used has index less than the field being
11115 // initialized, then the use is safe.
11116 for (auto UsedIter = UsedFieldIndex.begin(),
11117 UsedEnd = UsedFieldIndex.end(),
11118 OrigIter = InitFieldIndex.begin(),
11119 OrigEnd = InitFieldIndex.end();
11120 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11121 if (*UsedIter < *OrigIter)
11122 return true;
11123 if (*UsedIter > *OrigIter)
11124 break;
11125 }
11126
11127 // TODO: Add a different warning which will print the field names.
11128 HandleDeclRefExpr(DRE);
11129 return true;
11130 }
11131
11132 // For most expressions, the cast is directly above the DeclRefExpr.
11133 // For conditional operators, the cast can be outside the conditional
11134 // operator if both expressions are DeclRefExpr's.
11135 void HandleValue(Expr *E) {
11136 E = E->IgnoreParens();
11137 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11138 HandleDeclRefExpr(DRE);
11139 return;
11140 }
11141
11142 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11143 Visit(CO->getCond());
11144 HandleValue(CO->getTrueExpr());
11145 HandleValue(CO->getFalseExpr());
11146 return;
11147 }
11148
11149 if (BinaryConditionalOperator *BCO =
11150 dyn_cast<BinaryConditionalOperator>(E)) {
11151 Visit(BCO->getCond());
11152 HandleValue(BCO->getFalseExpr());
11153 return;
11154 }
11155
11156 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11157 HandleValue(OVE->getSourceExpr());
11158 return;
11159 }
11160
11161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11162 if (BO->getOpcode() == BO_Comma) {
11163 Visit(BO->getLHS());
11164 HandleValue(BO->getRHS());
11165 return;
11166 }
11167 }
11168
11169 if (isa<MemberExpr>(E)) {
11170 if (isInitList) {
11171 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11172 false /*CheckReference*/))
11173 return;
11174 }
11175
11176 Expr *Base = E->IgnoreParenImpCasts();
11177 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11178 // Check for static member variables and don't warn on them.
11179 if (!isa<FieldDecl>(ME->getMemberDecl()))
11180 return;
11181 Base = ME->getBase()->IgnoreParenImpCasts();
11182 }
11183 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11184 HandleDeclRefExpr(DRE);
11185 return;
11186 }
11187
11188 Visit(E);
11189 }
11190
11191 // Reference types not handled in HandleValue are handled here since all
11192 // uses of references are bad, not just r-value uses.
11193 void VisitDeclRefExpr(DeclRefExpr *E) {
11194 if (isReferenceType)
11195 HandleDeclRefExpr(E);
11196 }
11197
11198 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11199 if (E->getCastKind() == CK_LValueToRValue) {
11200 HandleValue(E->getSubExpr());
11201 return;
11202 }
11203
11204 Inherited::VisitImplicitCastExpr(E);
11205 }
11206
11207 void VisitMemberExpr(MemberExpr *E) {
11208 if (isInitList) {
11209 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11210 return;
11211 }
11212
11213 // Don't warn on arrays since they can be treated as pointers.
11214 if (E->getType()->canDecayToPointerType()) return;
11215
11216 // Warn when a non-static method call is followed by non-static member
11217 // field accesses, which is followed by a DeclRefExpr.
11218 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11219 bool Warn = (MD && !MD->isStatic());
11220 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11221 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11222 if (!isa<FieldDecl>(ME->getMemberDecl()))
11223 Warn = false;
11224 Base = ME->getBase()->IgnoreParenImpCasts();
11225 }
11226
11227 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11228 if (Warn)
11229 HandleDeclRefExpr(DRE);
11230 return;
11231 }
11232
11233 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11234 // Visit that expression.
11235 Visit(Base);
11236 }
11237
11238 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11239 Expr *Callee = E->getCallee();
11240
11241 if (isa<UnresolvedLookupExpr>(Callee))
11242 return Inherited::VisitCXXOperatorCallExpr(E);
11243
11244 Visit(Callee);
11245 for (auto Arg: E->arguments())
11246 HandleValue(Arg->IgnoreParenImpCasts());
11247 }
11248
11249 void VisitUnaryOperator(UnaryOperator *E) {
11250 // For POD record types, addresses of its own members are well-defined.
11251 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11252 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11253 if (!isPODType)
11254 HandleValue(E->getSubExpr());
11255 return;
11256 }
11257
11258 if (E->isIncrementDecrementOp()) {
11259 HandleValue(E->getSubExpr());
11260 return;
11261 }
11262
11263 Inherited::VisitUnaryOperator(E);
11264 }
11265
11266 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11267
11268 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11269 if (E->getConstructor()->isCopyConstructor()) {
11270 Expr *ArgExpr = E->getArg(0);
11271 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11272 if (ILE->getNumInits() == 1)
11273 ArgExpr = ILE->getInit(0);
11274 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11275 if (ICE->getCastKind() == CK_NoOp)
11276 ArgExpr = ICE->getSubExpr();
11277 HandleValue(ArgExpr);
11278 return;
11279 }
11280 Inherited::VisitCXXConstructExpr(E);
11281 }
11282
11283 void VisitCallExpr(CallExpr *E) {
11284 // Treat std::move as a use.
11285 if (E->isCallToStdMove()) {
11286 HandleValue(E->getArg(0));
11287 return;
11288 }
11289
11290 Inherited::VisitCallExpr(E);
11291 }
11292
11293 void VisitBinaryOperator(BinaryOperator *E) {
11294 if (E->isCompoundAssignmentOp()) {
11295 HandleValue(E->getLHS());
11296 Visit(E->getRHS());
11297 return;
11298 }
11299
11300 Inherited::VisitBinaryOperator(E);
11301 }
11302
11303 // A custom visitor for BinaryConditionalOperator is needed because the
11304 // regular visitor would check the condition and true expression separately
11305 // but both point to the same place giving duplicate diagnostics.
11306 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11307 Visit(E->getCond());
11308 Visit(E->getFalseExpr());
11309 }
11310
11311 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11312 Decl* ReferenceDecl = DRE->getDecl();
11313 if (OrigDecl != ReferenceDecl) return;
11314 unsigned diag;
11315 if (isReferenceType) {
11316 diag = diag::warn_uninit_self_reference_in_reference_init;
11317 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11318 diag = diag::warn_static_self_reference_in_init;
11319 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11320 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11321 DRE->getDecl()->getType()->isRecordType()) {
11322 diag = diag::warn_uninit_self_reference_in_init;
11323 } else {
11324 // Local variables will be handled by the CFG analysis.
11325 return;
11326 }
11327
11328 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11329 S.PDiag(diag)
11330 << DRE->getDecl() << OrigDecl->getLocation()
11331 << DRE->getSourceRange());
11332 }
11333 };
11334
11335 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11336 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11337 bool DirectInit) {
11338 // Parameters arguments are occassionially constructed with itself,
11339 // for instance, in recursive functions. Skip them.
11340 if (isa<ParmVarDecl>(OrigDecl))
11341 return;
11342
11343 E = E->IgnoreParens();
11344
11345 // Skip checking T a = a where T is not a record or reference type.
11346 // Doing so is a way to silence uninitialized warnings.
11347 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11348 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11349 if (ICE->getCastKind() == CK_LValueToRValue)
11350 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11351 if (DRE->getDecl() == OrigDecl)
11352 return;
11353
11354 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11355 }
11356} // end anonymous namespace
11357
11358namespace {
11359 // Simple wrapper to add the name of a variable or (if no variable is
11360 // available) a DeclarationName into a diagnostic.
11361 struct VarDeclOrName {
11362 VarDecl *VDecl;
11363 DeclarationName Name;
11364
11365 friend const Sema::SemaDiagnosticBuilder &
11366 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11367 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11368 }
11369 };
11370} // end anonymous namespace
11371
11372QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11373 DeclarationName Name, QualType Type,
11374 TypeSourceInfo *TSI,
11375 SourceRange Range, bool DirectInit,
11376 Expr *Init) {
11377 bool IsInitCapture = !VDecl;
11378 assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11379, __PRETTY_FUNCTION__))
11379 "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11379, __PRETTY_FUNCTION__))
;
11380
11381 VarDeclOrName VN{VDecl, Name};
11382
11383 DeducedType *Deduced = Type->getContainedDeducedType();
11384 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11384, __PRETTY_FUNCTION__))
;
11385
11386 // C++11 [dcl.spec.auto]p3
11387 if (!Init) {
11388 assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast
<void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11388, __PRETTY_FUNCTION__))
;
11389
11390 // Except for class argument deduction, and then for an initializing
11391 // declaration only, i.e. no static at class scope or extern.
11392 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11393 VDecl->hasExternalStorage() ||
11394 VDecl->isStaticDataMember()) {
11395 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11396 << VDecl->getDeclName() << Type;
11397 return QualType();
11398 }
11399 }
11400
11401 ArrayRef<Expr*> DeduceInits;
11402 if (Init)
11403 DeduceInits = Init;
11404
11405 if (DirectInit) {
11406 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11407 DeduceInits = PL->exprs();
11408 }
11409
11410 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11411 assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?"
) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11411, __PRETTY_FUNCTION__))
;
11412 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11413 InitializationKind Kind = InitializationKind::CreateForInit(
11414 VDecl->getLocation(), DirectInit, Init);
11415 // FIXME: Initialization should not be taking a mutable list of inits.
11416 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11417 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11418 InitsCopy);
11419 }
11420
11421 if (DirectInit) {
11422 if (auto *IL = dyn_cast<InitListExpr>(Init))
11423 DeduceInits = IL->inits();
11424 }
11425
11426 // Deduction only works if we have exactly one source expression.
11427 if (DeduceInits.empty()) {
11428 // It isn't possible to write this directly, but it is possible to
11429 // end up in this situation with "auto x(some_pack...);"
11430 Diag(Init->getBeginLoc(), IsInitCapture
11431 ? diag::err_init_capture_no_expression
11432 : diag::err_auto_var_init_no_expression)
11433 << VN << Type << Range;
11434 return QualType();
11435 }
11436
11437 if (DeduceInits.size() > 1) {
11438 Diag(DeduceInits[1]->getBeginLoc(),
11439 IsInitCapture ? diag::err_init_capture_multiple_expressions
11440 : diag::err_auto_var_init_multiple_expressions)
11441 << VN << Type << Range;
11442 return QualType();
11443 }
11444
11445 Expr *DeduceInit = DeduceInits[0];
11446 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11447 Diag(Init->getBeginLoc(), IsInitCapture
11448 ? diag::err_init_capture_paren_braces
11449 : diag::err_auto_var_init_paren_braces)
11450 << isa<InitListExpr>(Init) << VN << Type << Range;
11451 return QualType();
11452 }
11453
11454 // Expressions default to 'id' when we're in a debugger.
11455 bool DefaultedAnyToId = false;
11456 if (getLangOpts().DebuggerCastResultToId &&
11457 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11458 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11459 if (Result.isInvalid()) {
11460 return QualType();
11461 }
11462 Init = Result.get();
11463 DefaultedAnyToId = true;
11464 }
11465
11466 // C++ [dcl.decomp]p1:
11467 // If the assignment-expression [...] has array type A and no ref-qualifier
11468 // is present, e has type cv A
11469 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11470 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11471 DeduceInit->getType()->isConstantArrayType())
11472 return Context.getQualifiedType(DeduceInit->getType(),
11473 Type.getQualifiers());
11474
11475 QualType DeducedType;
11476 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11477 if (!IsInitCapture)
11478 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11479 else if (isa<InitListExpr>(Init))
11480 Diag(Range.getBegin(),
11481 diag::err_init_capture_deduction_failure_from_init_list)
11482 << VN
11483 << (DeduceInit->getType().isNull() ? TSI->getType()
11484 : DeduceInit->getType())
11485 << DeduceInit->getSourceRange();
11486 else
11487 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11488 << VN << TSI->getType()
11489 << (DeduceInit->getType().isNull() ? TSI->getType()
11490 : DeduceInit->getType())
11491 << DeduceInit->getSourceRange();
11492 }
11493
11494 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11495 // 'id' instead of a specific object type prevents most of our usual
11496 // checks.
11497 // We only want to warn outside of template instantiations, though:
11498 // inside a template, the 'id' could have come from a parameter.
11499 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11500 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11501 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11502 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11503 }
11504
11505 return DeducedType;
11506}
11507
11508bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11509 Expr *Init) {
11510 QualType DeducedType = deduceVarTypeFromInitializer(
11511 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11512 VDecl->getSourceRange(), DirectInit, Init);
11513 if (DeducedType.isNull()) {
11514 VDecl->setInvalidDecl();
11515 return true;
11516 }
11517
11518 VDecl->setType(DeducedType);
11519 assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) :
__assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11519, __PRETTY_FUNCTION__))
;
11520
11521 // In ARC, infer lifetime.
11522 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11523 VDecl->setInvalidDecl();
11524
11525 if (getLangOpts().OpenCL)
11526 deduceOpenCLAddressSpace(VDecl);
11527
11528 // If this is a redeclaration, check that the type we just deduced matches
11529 // the previously declared type.
11530 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11531 // We never need to merge the type, because we cannot form an incomplete
11532 // array of auto, nor deduce such a type.
11533 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11534 }
11535
11536 // Check the deduced type is valid for a variable declaration.
11537 CheckVariableDeclarationType(VDecl);
11538 return VDecl->isInvalidDecl();
11539}
11540
11541void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11542 SourceLocation Loc) {
11543 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11544 Init = CE->getSubExpr();
11545
11546 QualType InitType = Init->getType();
11547 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11549, __PRETTY_FUNCTION__))
11548 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11549, __PRETTY_FUNCTION__))
11549 "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11549, __PRETTY_FUNCTION__))
;
11550 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11551 for (auto I : ILE->inits()) {
11552 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11553 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11554 continue;
11555 SourceLocation SL = I->getExprLoc();
11556 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11557 }
11558 return;
11559 }
11560
11561 if (isa<ImplicitValueInitExpr>(Init)) {
11562 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11563 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11564 NTCUK_Init);
11565 } else {
11566 // Assume all other explicit initializers involving copying some existing
11567 // object.
11568 // TODO: ignore any explicit initializers where we can guarantee
11569 // copy-elision.
11570 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11571 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11572 }
11573}
11574
11575namespace {
11576
11577bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11578 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11579 // in the source code or implicitly by the compiler if it is in a union
11580 // defined in a system header and has non-trivial ObjC ownership
11581 // qualifications. We don't want those fields to participate in determining
11582 // whether the containing union is non-trivial.
11583 return FD->hasAttr<UnavailableAttr>();
11584}
11585
11586struct DiagNonTrivalCUnionDefaultInitializeVisitor
11587 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11588 void> {
11589 using Super =
11590 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11591 void>;
11592
11593 DiagNonTrivalCUnionDefaultInitializeVisitor(
11594 QualType OrigTy, SourceLocation OrigLoc,
11595 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11596 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11597
11598 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11599 const FieldDecl *FD, bool InNonTrivialUnion) {
11600 if (const auto *AT = S.Context.getAsArrayType(QT))
11601 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11602 InNonTrivialUnion);
11603 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11604 }
11605
11606 void visitARCStrong(QualType QT, const FieldDecl *FD,
11607 bool InNonTrivialUnion) {
11608 if (InNonTrivialUnion)
11609 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11610 << 1 << 0 << QT << FD->getName();
11611 }
11612
11613 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11614 if (InNonTrivialUnion)
11615 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11616 << 1 << 0 << QT << FD->getName();
11617 }
11618
11619 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11620 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11621 if (RD->isUnion()) {
11622 if (OrigLoc.isValid()) {
11623 bool IsUnion = false;
11624 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11625 IsUnion = OrigRD->isUnion();
11626 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11627 << 0 << OrigTy << IsUnion << UseContext;
11628 // Reset OrigLoc so that this diagnostic is emitted only once.
11629 OrigLoc = SourceLocation();
11630 }
11631 InNonTrivialUnion = true;
11632 }
11633
11634 if (InNonTrivialUnion)
11635 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11636 << 0 << 0 << QT.getUnqualifiedType() << "";
11637
11638 for (const FieldDecl *FD : RD->fields())
11639 if (!shouldIgnoreForRecordTriviality(FD))
11640 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11641 }
11642
11643 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11644
11645 // The non-trivial C union type or the struct/union type that contains a
11646 // non-trivial C union.
11647 QualType OrigTy;
11648 SourceLocation OrigLoc;
11649 Sema::NonTrivialCUnionContext UseContext;
11650 Sema &S;
11651};
11652
11653struct DiagNonTrivalCUnionDestructedTypeVisitor
11654 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11655 using Super =
11656 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11657
11658 DiagNonTrivalCUnionDestructedTypeVisitor(
11659 QualType OrigTy, SourceLocation OrigLoc,
11660 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11661 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11662
11663 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11664 const FieldDecl *FD, bool InNonTrivialUnion) {
11665 if (const auto *AT = S.Context.getAsArrayType(QT))
11666 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11667 InNonTrivialUnion);
11668 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11669 }
11670
11671 void visitARCStrong(QualType QT, const FieldDecl *FD,
11672 bool InNonTrivialUnion) {
11673 if (InNonTrivialUnion)
11674 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11675 << 1 << 1 << QT << FD->getName();
11676 }
11677
11678 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11679 if (InNonTrivialUnion)
11680 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11681 << 1 << 1 << QT << FD->getName();
11682 }
11683
11684 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11685 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11686 if (RD->isUnion()) {
11687 if (OrigLoc.isValid()) {
11688 bool IsUnion = false;
11689 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11690 IsUnion = OrigRD->isUnion();
11691 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11692 << 1 << OrigTy << IsUnion << UseContext;
11693 // Reset OrigLoc so that this diagnostic is emitted only once.
11694 OrigLoc = SourceLocation();
11695 }
11696 InNonTrivialUnion = true;
11697 }
11698
11699 if (InNonTrivialUnion)
11700 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11701 << 0 << 1 << QT.getUnqualifiedType() << "";
11702
11703 for (const FieldDecl *FD : RD->fields())
11704 if (!shouldIgnoreForRecordTriviality(FD))
11705 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11706 }
11707
11708 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11709 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11710 bool InNonTrivialUnion) {}
11711
11712 // The non-trivial C union type or the struct/union type that contains a
11713 // non-trivial C union.
11714 QualType OrigTy;
11715 SourceLocation OrigLoc;
11716 Sema::NonTrivialCUnionContext UseContext;
11717 Sema &S;
11718};
11719
11720struct DiagNonTrivalCUnionCopyVisitor
11721 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11722 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11723
11724 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11725 Sema::NonTrivialCUnionContext UseContext,
11726 Sema &S)
11727 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11728
11729 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11730 const FieldDecl *FD, bool InNonTrivialUnion) {
11731 if (const auto *AT = S.Context.getAsArrayType(QT))
11732 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11733 InNonTrivialUnion);
11734 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11735 }
11736
11737 void visitARCStrong(QualType QT, const FieldDecl *FD,
11738 bool InNonTrivialUnion) {
11739 if (InNonTrivialUnion)
11740 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11741 << 1 << 2 << QT << FD->getName();
11742 }
11743
11744 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11745 if (InNonTrivialUnion)
11746 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11747 << 1 << 2 << QT << FD->getName();
11748 }
11749
11750 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11751 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11752 if (RD->isUnion()) {
11753 if (OrigLoc.isValid()) {
11754 bool IsUnion = false;
11755 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11756 IsUnion = OrigRD->isUnion();
11757 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11758 << 2 << OrigTy << IsUnion << UseContext;
11759 // Reset OrigLoc so that this diagnostic is emitted only once.
11760 OrigLoc = SourceLocation();
11761 }
11762 InNonTrivialUnion = true;
11763 }
11764
11765 if (InNonTrivialUnion)
11766 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11767 << 0 << 2 << QT.getUnqualifiedType() << "";
11768
11769 for (const FieldDecl *FD : RD->fields())
11770 if (!shouldIgnoreForRecordTriviality(FD))
11771 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11772 }
11773
11774 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11775 const FieldDecl *FD, bool InNonTrivialUnion) {}
11776 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11777 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11778 bool InNonTrivialUnion) {}
11779
11780 // The non-trivial C union type or the struct/union type that contains a
11781 // non-trivial C union.
11782 QualType OrigTy;
11783 SourceLocation OrigLoc;
11784 Sema::NonTrivialCUnionContext UseContext;
11785 Sema &S;
11786};
11787
11788} // namespace
11789
11790void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11791 NonTrivialCUnionContext UseContext,
11792 unsigned NonTrivialKind) {
11793 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11796, __PRETTY_FUNCTION__))
11794 QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11796, __PRETTY_FUNCTION__))
11795 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11796, __PRETTY_FUNCTION__))
11796 "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11796, __PRETTY_FUNCTION__))
;
11797
11798 if ((NonTrivialKind & NTCUK_Init) &&
11799 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11800 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11801 .visit(QT, nullptr, false);
11802 if ((NonTrivialKind & NTCUK_Destruct) &&
11803 QT.hasNonTrivialToPrimitiveDestructCUnion())
11804 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11805 .visit(QT, nullptr, false);
11806 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11807 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11808 .visit(QT, nullptr, false);
11809}
11810
11811/// AddInitializerToDecl - Adds the initializer Init to the
11812/// declaration dcl. If DirectInit is true, this is C++ direct
11813/// initialization rather than copy initialization.
11814void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11815 // If there is no declaration, there was an error parsing it. Just ignore
11816 // the initializer.
11817 if (!RealDecl || RealDecl->isInvalidDecl()) {
11818 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11819 return;
11820 }
11821
11822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11823 // Pure-specifiers are handled in ActOnPureSpecifier.
11824 Diag(Method->getLocation(), diag::err_member_function_initialization)
11825 << Method->getDeclName() << Init->getSourceRange();
11826 Method->setInvalidDecl();
11827 return;
11828 }
11829
11830 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11831 if (!VDecl) {
11832 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"
) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 11832, __PRETTY_FUNCTION__))
;
11833 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11834 RealDecl->setInvalidDecl();
11835 return;
11836 }
11837
11838 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11839 if (VDecl->getType()->isUndeducedType()) {
11840 // Attempt typo correction early so that the type of the init expression can
11841 // be deduced based on the chosen correction if the original init contains a
11842 // TypoExpr.
11843 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11844 if (!Res.isUsable()) {
11845 RealDecl->setInvalidDecl();
11846 return;
11847 }
11848 Init = Res.get();
11849
11850 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11851 return;
11852 }
11853
11854 // dllimport cannot be used on variable definitions.
11855 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11856 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11857 VDecl->setInvalidDecl();
11858 return;
11859 }
11860
11861 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11862 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11863 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11864 VDecl->setInvalidDecl();
11865 return;
11866 }
11867
11868 if (!VDecl->getType()->isDependentType()) {
11869 // A definition must end up with a complete type, which means it must be
11870 // complete with the restriction that an array type might be completed by
11871 // the initializer; note that later code assumes this restriction.
11872 QualType BaseDeclType = VDecl->getType();
11873 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11874 BaseDeclType = Array->getElementType();
11875 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11876 diag::err_typecheck_decl_incomplete_type)) {
11877 RealDecl->setInvalidDecl();
11878 return;
11879 }
11880
11881 // The variable can not have an abstract class type.
11882 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11883 diag::err_abstract_type_in_decl,
11884 AbstractVariableType))
11885 VDecl->setInvalidDecl();
11886 }
11887
11888 // If adding the initializer will turn this declaration into a definition,
11889 // and we already have a definition for this variable, diagnose or otherwise
11890 // handle the situation.
11891 VarDecl *Def;
11892 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11893 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11894 !VDecl->isThisDeclarationADemotedDefinition() &&
11895 checkVarDeclRedefinition(Def, VDecl))
11896 return;
11897
11898 if (getLangOpts().CPlusPlus) {
11899 // C++ [class.static.data]p4
11900 // If a static data member is of const integral or const
11901 // enumeration type, its declaration in the class definition can
11902 // specify a constant-initializer which shall be an integral
11903 // constant expression (5.19). In that case, the member can appear
11904 // in integral constant expressions. The member shall still be
11905 // defined in a namespace scope if it is used in the program and the
11906 // namespace scope definition shall not contain an initializer.
11907 //
11908 // We already performed a redefinition check above, but for static
11909 // data members we also need to check whether there was an in-class
11910 // declaration with an initializer.
11911 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11912 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11913 << VDecl->getDeclName();
11914 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11915 diag::note_previous_initializer)
11916 << 0;
11917 return;
11918 }
11919
11920 if (VDecl->hasLocalStorage())
11921 setFunctionHasBranchProtectedScope();
11922
11923 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11924 VDecl->setInvalidDecl();
11925 return;
11926 }
11927 }
11928
11929 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11930 // a kernel function cannot be initialized."
11931 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11932 Diag(VDecl->getLocation(), diag::err_local_cant_init);
11933 VDecl->setInvalidDecl();
11934 return;
11935 }
11936
11937 // Get the decls type and save a reference for later, since
11938 // CheckInitializerTypes may change it.
11939 QualType DclT = VDecl->getType(), SavT = DclT;
11940
11941 // Expressions default to 'id' when we're in a debugger
11942 // and we are assigning it to a variable of Objective-C pointer type.
11943 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11944 Init->getType() == Context.UnknownAnyTy) {
11945 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11946 if (Result.isInvalid()) {
11947 VDecl->setInvalidDecl();
11948 return;
11949 }
11950 Init = Result.get();
11951 }
11952
11953 // Perform the initialization.
11954 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11955 if (!VDecl->isInvalidDecl()) {
11956 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11957 InitializationKind Kind = InitializationKind::CreateForInit(
11958 VDecl->getLocation(), DirectInit, Init);
11959
11960 MultiExprArg Args = Init;
11961 if (CXXDirectInit)
11962 Args = MultiExprArg(CXXDirectInit->getExprs(),
11963 CXXDirectInit->getNumExprs());
11964
11965 // Try to correct any TypoExprs in the initialization arguments.
11966 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11967 ExprResult Res = CorrectDelayedTyposInExpr(
11968 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11969 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11970 return Init.Failed() ? ExprError() : E;
11971 });
11972 if (Res.isInvalid()) {
11973 VDecl->setInvalidDecl();
11974 } else if (Res.get() != Args[Idx]) {
11975 Args[Idx] = Res.get();
11976 }
11977 }
11978 if (VDecl->isInvalidDecl())
11979 return;
11980
11981 InitializationSequence InitSeq(*this, Entity, Kind, Args,
11982 /*TopLevelOfInitList=*/false,
11983 /*TreatUnavailableAsInvalid=*/false);
11984 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11985 if (Result.isInvalid()) {
11986 VDecl->setInvalidDecl();
11987 return;
11988 }
11989
11990 Init = Result.getAs<Expr>();
11991 }
11992
11993 // Check for self-references within variable initializers.
11994 // Variables declared within a function/method body (except for references)
11995 // are handled by a dataflow analysis.
11996 // This is undefined behavior in C++, but valid in C.
11997 if (getLangOpts().CPlusPlus) {
11998 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11999 VDecl->getType()->isReferenceType()) {
12000 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12001 }
12002 }
12003
12004 // If the type changed, it means we had an incomplete type that was
12005 // completed by the initializer. For example:
12006 // int ary[] = { 1, 3, 5 };
12007 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12008 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12009 VDecl->setType(DclT);
12010
12011 if (!VDecl->isInvalidDecl()) {
12012 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12013
12014 if (VDecl->hasAttr<BlocksAttr>())
12015 checkRetainCycles(VDecl, Init);
12016
12017 // It is safe to assign a weak reference into a strong variable.
12018 // Although this code can still have problems:
12019 // id x = self.weakProp;
12020 // id y = self.weakProp;
12021 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12022 // paths through the function. This should be revisited if
12023 // -Wrepeated-use-of-weak is made flow-sensitive.
12024 if (FunctionScopeInfo *FSI = getCurFunction())
12025 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12026 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12027 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12028 Init->getBeginLoc()))
12029 FSI->markSafeWeakUse(Init);
12030 }
12031
12032 // The initialization is usually a full-expression.
12033 //
12034 // FIXME: If this is a braced initialization of an aggregate, it is not
12035 // an expression, and each individual field initializer is a separate
12036 // full-expression. For instance, in:
12037 //
12038 // struct Temp { ~Temp(); };
12039 // struct S { S(Temp); };
12040 // struct T { S a, b; } t = { Temp(), Temp() }
12041 //
12042 // we should destroy the first Temp before constructing the second.
12043 ExprResult Result =
12044 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12045 /*DiscardedValue*/ false, VDecl->isConstexpr());
12046 if (Result.isInvalid()) {
12047 VDecl->setInvalidDecl();
12048 return;
12049 }
12050 Init = Result.get();
12051
12052 // Attach the initializer to the decl.
12053 VDecl->setInit(Init);
12054
12055 if (VDecl->isLocalVarDecl()) {
12056 // Don't check the initializer if the declaration is malformed.
12057 if (VDecl->isInvalidDecl()) {
12058 // do nothing
12059
12060 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12061 // This is true even in C++ for OpenCL.
12062 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12063 CheckForConstantInitializer(Init, DclT);
12064
12065 // Otherwise, C++ does not restrict the initializer.
12066 } else if (getLangOpts().CPlusPlus) {
12067 // do nothing
12068
12069 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12070 // static storage duration shall be constant expressions or string literals.
12071 } else if (VDecl->getStorageClass() == SC_Static) {
12072 CheckForConstantInitializer(Init, DclT);
12073
12074 // C89 is stricter than C99 for aggregate initializers.
12075 // C89 6.5.7p3: All the expressions [...] in an initializer list
12076 // for an object that has aggregate or union type shall be
12077 // constant expressions.
12078 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12079 isa<InitListExpr>(Init)) {
12080 const Expr *Culprit;
12081 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12082 Diag(Culprit->getExprLoc(),
12083 diag::ext_aggregate_init_not_constant)
12084 << Culprit->getSourceRange();
12085 }
12086 }
12087
12088 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12089 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12090 if (VDecl->hasLocalStorage())
12091 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12092 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12093 VDecl->getLexicalDeclContext()->isRecord()) {
12094 // This is an in-class initialization for a static data member, e.g.,
12095 //
12096 // struct S {
12097 // static const int value = 17;
12098 // };
12099
12100 // C++ [class.mem]p4:
12101 // A member-declarator can contain a constant-initializer only
12102 // if it declares a static member (9.4) of const integral or
12103 // const enumeration type, see 9.4.2.
12104 //
12105 // C++11 [class.static.data]p3:
12106 // If a non-volatile non-inline const static data member is of integral
12107 // or enumeration type, its declaration in the class definition can
12108 // specify a brace-or-equal-initializer in which every initializer-clause
12109 // that is an assignment-expression is a constant expression. A static
12110 // data member of literal type can be declared in the class definition
12111 // with the constexpr specifier; if so, its declaration shall specify a
12112 // brace-or-equal-initializer in which every initializer-clause that is
12113 // an assignment-expression is a constant expression.
12114
12115 // Do nothing on dependent types.
12116 if (DclT->isDependentType()) {
12117
12118 // Allow any 'static constexpr' members, whether or not they are of literal
12119 // type. We separately check that every constexpr variable is of literal
12120 // type.
12121 } else if (VDecl->isConstexpr()) {
12122
12123 // Require constness.
12124 } else if (!DclT.isConstQualified()) {
12125 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12126 << Init->getSourceRange();
12127 VDecl->setInvalidDecl();
12128
12129 // We allow integer constant expressions in all cases.
12130 } else if (DclT->isIntegralOrEnumerationType()) {
12131 // Check whether the expression is a constant expression.
12132 SourceLocation Loc;
12133 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12134 // In C++11, a non-constexpr const static data member with an
12135 // in-class initializer cannot be volatile.
12136 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12137 else if (Init->isValueDependent())
12138 ; // Nothing to check.
12139 else if (Init->isIntegerConstantExpr(Context, &Loc))
12140 ; // Ok, it's an ICE!
12141 else if (Init->getType()->isScopedEnumeralType() &&
12142 Init->isCXX11ConstantExpr(Context))
12143 ; // Ok, it is a scoped-enum constant expression.
12144 else if (Init->isEvaluatable(Context)) {
12145 // If we can constant fold the initializer through heroics, accept it,
12146 // but report this as a use of an extension for -pedantic.
12147 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12148 << Init->getSourceRange();
12149 } else {
12150 // Otherwise, this is some crazy unknown case. Report the issue at the
12151 // location provided by the isIntegerConstantExpr failed check.
12152 Diag(Loc, diag::err_in_class_initializer_non_constant)
12153 << Init->getSourceRange();
12154 VDecl->setInvalidDecl();
12155 }
12156
12157 // We allow foldable floating-point constants as an extension.
12158 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12159 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12160 // it anyway and provide a fixit to add the 'constexpr'.
12161 if (getLangOpts().CPlusPlus11) {
12162 Diag(VDecl->getLocation(),
12163 diag::ext_in_class_initializer_float_type_cxx11)
12164 << DclT << Init->getSourceRange();
12165 Diag(VDecl->getBeginLoc(),
12166 diag::note_in_class_initializer_float_type_cxx11)
12167 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12168 } else {
12169 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12170 << DclT << Init->getSourceRange();
12171
12172 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12173 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12174 << Init->getSourceRange();
12175 VDecl->setInvalidDecl();
12176 }
12177 }
12178
12179 // Suggest adding 'constexpr' in C++11 for literal types.
12180 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12181 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12182 << DclT << Init->getSourceRange()
12183 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12184 VDecl->setConstexpr(true);
12185
12186 } else {
12187 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12188 << DclT << Init->getSourceRange();
12189 VDecl->setInvalidDecl();
12190 }
12191 } else if (VDecl->isFileVarDecl()) {
12192 // In C, extern is typically used to avoid tentative definitions when
12193 // declaring variables in headers, but adding an intializer makes it a
12194 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12195 // In C++, extern is often used to give implictly static const variables
12196 // external linkage, so don't warn in that case. If selectany is present,
12197 // this might be header code intended for C and C++ inclusion, so apply the
12198 // C++ rules.
12199 if (VDecl->getStorageClass() == SC_Extern &&
12200 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12201 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12202 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12203 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12204 Diag(VDecl->getLocation(), diag::warn_extern_init);
12205
12206 // In Microsoft C++ mode, a const variable defined in namespace scope has
12207 // external linkage by default if the variable is declared with
12208 // __declspec(dllexport).
12209 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12210 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12211 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12212 VDecl->setStorageClass(SC_Extern);
12213
12214 // C99 6.7.8p4. All file scoped initializers need to be constant.
12215 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12216 CheckForConstantInitializer(Init, DclT);
12217 }
12218
12219 QualType InitType = Init->getType();
12220 if (!InitType.isNull() &&
12221 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12222 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12223 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12224
12225 // We will represent direct-initialization similarly to copy-initialization:
12226 // int x(1); -as-> int x = 1;
12227 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12228 //
12229 // Clients that want to distinguish between the two forms, can check for
12230 // direct initializer using VarDecl::getInitStyle().
12231 // A major benefit is that clients that don't particularly care about which
12232 // exactly form was it (like the CodeGen) can handle both cases without
12233 // special case code.
12234
12235 // C++ 8.5p11:
12236 // The form of initialization (using parentheses or '=') is generally
12237 // insignificant, but does matter when the entity being initialized has a
12238 // class type.
12239 if (CXXDirectInit) {
12240 assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init."
) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 12240, __PRETTY_FUNCTION__))
;
12241 VDecl->setInitStyle(VarDecl::CallInit);
12242 } else if (DirectInit) {
12243 // This must be list-initialization. No other way is direct-initialization.
12244 VDecl->setInitStyle(VarDecl::ListInit);
12245 }
12246
12247 CheckCompleteVariableDeclaration(VDecl);
12248}
12249
12250/// ActOnInitializerError - Given that there was an error parsing an
12251/// initializer for the given declaration, try to return to some form
12252/// of sanity.
12253void Sema::ActOnInitializerError(Decl *D) {
12254 // Our main concern here is re-establishing invariants like "a
12255 // variable's type is either dependent or complete".
12256 if (!D || D->isInvalidDecl()) return;
12257
12258 VarDecl *VD = dyn_cast<VarDecl>(D);
12259 if (!VD) return;
12260
12261 // Bindings are not usable if we can't make sense of the initializer.
12262 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12263 for (auto *BD : DD->bindings())
12264 BD->setInvalidDecl();
12265
12266 // Auto types are meaningless if we can't make sense of the initializer.
12267 if (ParsingInitForAutoVars.count(D)) {
12268 D->setInvalidDecl();
12269 return;
12270 }
12271
12272 QualType Ty = VD->getType();
12273 if (Ty->isDependentType()) return;
12274
12275 // Require a complete type.
12276 if (RequireCompleteType(VD->getLocation(),
12277 Context.getBaseElementType(Ty),
12278 diag::err_typecheck_decl_incomplete_type)) {
12279 VD->setInvalidDecl();
12280 return;
12281 }
12282
12283 // Require a non-abstract type.
12284 if (RequireNonAbstractType(VD->getLocation(), Ty,
12285 diag::err_abstract_type_in_decl,
12286 AbstractVariableType)) {
12287 VD->setInvalidDecl();
12288 return;
12289 }
12290
12291 // Don't bother complaining about constructors or destructors,
12292 // though.
12293}
12294
12295void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12296 // If there is no declaration, there was an error parsing it. Just ignore it.
12297 if (!RealDecl)
12298 return;
12299
12300 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12301 QualType Type = Var->getType();
12302
12303 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12304 if (isa<DecompositionDecl>(RealDecl)) {
12305 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12306 Var->setInvalidDecl();
12307 return;
12308 }
12309
12310 if (Type->isUndeducedType() &&
12311 DeduceVariableDeclarationType(Var, false, nullptr))
12312 return;
12313
12314 // C++11 [class.static.data]p3: A static data member can be declared with
12315 // the constexpr specifier; if so, its declaration shall specify
12316 // a brace-or-equal-initializer.
12317 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12318 // the definition of a variable [...] or the declaration of a static data
12319 // member.
12320 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12321 !Var->isThisDeclarationADemotedDefinition()) {
12322 if (Var->isStaticDataMember()) {
12323 // C++1z removes the relevant rule; the in-class declaration is always
12324 // a definition there.
12325 if (!getLangOpts().CPlusPlus17 &&
12326 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12327 Diag(Var->getLocation(),
12328 diag::err_constexpr_static_mem_var_requires_init)
12329 << Var->getDeclName();
12330 Var->setInvalidDecl();
12331 return;
12332 }
12333 } else {
12334 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12335 Var->setInvalidDecl();
12336 return;
12337 }
12338 }
12339
12340 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12341 // be initialized.
12342 if (!Var->isInvalidDecl() &&
12343 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12344 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12345 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12346 Var->setInvalidDecl();
12347 return;
12348 }
12349
12350 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12351 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12352 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12353 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12354 NTCUC_DefaultInitializedObject, NTCUK_Init);
12355
12356
12357 switch (DefKind) {
12358 case VarDecl::Definition:
12359 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12360 break;
12361
12362 // We have an out-of-line definition of a static data member
12363 // that has an in-class initializer, so we type-check this like
12364 // a declaration.
12365 //
12366 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12367
12368 case VarDecl::DeclarationOnly:
12369 // It's only a declaration.
12370
12371 // Block scope. C99 6.7p7: If an identifier for an object is
12372 // declared with no linkage (C99 6.2.2p6), the type for the
12373 // object shall be complete.
12374 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12375 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12376 RequireCompleteType(Var->getLocation(), Type,
12377 diag::err_typecheck_decl_incomplete_type))
12378 Var->setInvalidDecl();
12379
12380 // Make sure that the type is not abstract.
12381 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12382 RequireNonAbstractType(Var->getLocation(), Type,
12383 diag::err_abstract_type_in_decl,
12384 AbstractVariableType))
12385 Var->setInvalidDecl();
12386 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12387 Var->getStorageClass() == SC_PrivateExtern) {
12388 Diag(Var->getLocation(), diag::warn_private_extern);
12389 Diag(Var->getLocation(), diag::note_private_extern);
12390 }
12391
12392 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12393 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12394 ExternalDeclarations.push_back(Var);
12395
12396 return;
12397
12398 case VarDecl::TentativeDefinition:
12399 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12400 // object that has file scope without an initializer, and without a
12401 // storage-class specifier or with the storage-class specifier "static",
12402 // constitutes a tentative definition. Note: A tentative definition with
12403 // external linkage is valid (C99 6.2.2p5).
12404 if (!Var->isInvalidDecl()) {
12405 if (const IncompleteArrayType *ArrayT
12406 = Context.getAsIncompleteArrayType(Type)) {
12407 if (RequireCompleteType(Var->getLocation(),
12408 ArrayT->getElementType(),
12409 diag::err_illegal_decl_array_incomplete_type))
12410 Var->setInvalidDecl();
12411 } else if (Var->getStorageClass() == SC_Static) {
12412 // C99 6.9.2p3: If the declaration of an identifier for an object is
12413 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12414 // declared type shall not be an incomplete type.
12415 // NOTE: code such as the following
12416 // static struct s;
12417 // struct s { int a; };
12418 // is accepted by gcc. Hence here we issue a warning instead of
12419 // an error and we do not invalidate the static declaration.
12420 // NOTE: to avoid multiple warnings, only check the first declaration.
12421 if (Var->isFirstDecl())
12422 RequireCompleteType(Var->getLocation(), Type,
12423 diag::ext_typecheck_decl_incomplete_type);
12424 }
12425 }
12426
12427 // Record the tentative definition; we're done.
12428 if (!Var->isInvalidDecl())
12429 TentativeDefinitions.push_back(Var);
12430 return;
12431 }
12432
12433 // Provide a specific diagnostic for uninitialized variable
12434 // definitions with incomplete array type.
12435 if (Type->isIncompleteArrayType()) {
12436 Diag(Var->getLocation(),
12437 diag::err_typecheck_incomplete_array_needs_initializer);
12438 Var->setInvalidDecl();
12439 return;
12440 }
12441
12442 // Provide a specific diagnostic for uninitialized variable
12443 // definitions with reference type.
12444 if (Type->isReferenceType()) {
12445 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12446 << Var->getDeclName()
12447 << SourceRange(Var->getLocation(), Var->getLocation());
12448 Var->setInvalidDecl();
12449 return;
12450 }
12451
12452 // Do not attempt to type-check the default initializer for a
12453 // variable with dependent type.
12454 if (Type->isDependentType())
12455 return;
12456
12457 if (Var->isInvalidDecl())
12458 return;
12459
12460 if (!Var->hasAttr<AliasAttr>()) {
12461 if (RequireCompleteType(Var->getLocation(),
12462 Context.getBaseElementType(Type),
12463 diag::err_typecheck_decl_incomplete_type)) {
12464 Var->setInvalidDecl();
12465 return;
12466 }
12467 } else {
12468 return;
12469 }
12470
12471 // The variable can not have an abstract class type.
12472 if (RequireNonAbstractType(Var->getLocation(), Type,
12473 diag::err_abstract_type_in_decl,
12474 AbstractVariableType)) {
12475 Var->setInvalidDecl();
12476 return;
12477 }
12478
12479 // Check for jumps past the implicit initializer. C++0x
12480 // clarifies that this applies to a "variable with automatic
12481 // storage duration", not a "local variable".
12482 // C++11 [stmt.dcl]p3
12483 // A program that jumps from a point where a variable with automatic
12484 // storage duration is not in scope to a point where it is in scope is
12485 // ill-formed unless the variable has scalar type, class type with a
12486 // trivial default constructor and a trivial destructor, a cv-qualified
12487 // version of one of these types, or an array of one of the preceding
12488 // types and is declared without an initializer.
12489 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12490 if (const RecordType *Record
12491 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12492 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12493 // Mark the function (if we're in one) for further checking even if the
12494 // looser rules of C++11 do not require such checks, so that we can
12495 // diagnose incompatibilities with C++98.
12496 if (!CXXRecord->isPOD())
12497 setFunctionHasBranchProtectedScope();
12498 }
12499 }
12500 // In OpenCL, we can't initialize objects in the __local address space,
12501 // even implicitly, so don't synthesize an implicit initializer.
12502 if (getLangOpts().OpenCL &&
12503 Var->getType().getAddressSpace() == LangAS::opencl_local)
12504 return;
12505 // C++03 [dcl.init]p9:
12506 // If no initializer is specified for an object, and the
12507 // object is of (possibly cv-qualified) non-POD class type (or
12508 // array thereof), the object shall be default-initialized; if
12509 // the object is of const-qualified type, the underlying class
12510 // type shall have a user-declared default
12511 // constructor. Otherwise, if no initializer is specified for
12512 // a non- static object, the object and its subobjects, if
12513 // any, have an indeterminate initial value); if the object
12514 // or any of its subobjects are of const-qualified type, the
12515 // program is ill-formed.
12516 // C++0x [dcl.init]p11:
12517 // If no initializer is specified for an object, the object is
12518 // default-initialized; [...].
12519 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12520 InitializationKind Kind
12521 = InitializationKind::CreateDefault(Var->getLocation());
12522
12523 InitializationSequence InitSeq(*this, Entity, Kind, None);
12524 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12525 if (Init.isInvalid())
12526 Var->setInvalidDecl();
12527 else if (Init.get()) {
12528 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12529 // This is important for template substitution.
12530 Var->setInitStyle(VarDecl::CallInit);
12531 }
12532
12533 CheckCompleteVariableDeclaration(Var);
12534 }
12535}
12536
12537void Sema::ActOnCXXForRangeDecl(Decl *D) {
12538 // If there is no declaration, there was an error parsing it. Ignore it.
12539 if (!D)
12540 return;
12541
12542 VarDecl *VD = dyn_cast<VarDecl>(D);
12543 if (!VD) {
12544 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12545 D->setInvalidDecl();
12546 return;
12547 }
12548
12549 VD->setCXXForRangeDecl(true);
12550
12551 // for-range-declaration cannot be given a storage class specifier.
12552 int Error = -1;
12553 switch (VD->getStorageClass()) {
12554 case SC_None:
12555 break;
12556 case SC_Extern:
12557 Error = 0;
12558 break;
12559 case SC_Static:
12560 Error = 1;
12561 break;
12562 case SC_PrivateExtern:
12563 Error = 2;
12564 break;
12565 case SC_Auto:
12566 Error = 3;
12567 break;
12568 case SC_Register:
12569 Error = 4;
12570 break;
12571 }
12572 if (Error != -1) {
12573 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12574 << VD->getDeclName() << Error;
12575 D->setInvalidDecl();
12576 }
12577}
12578
12579StmtResult
12580Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12581 IdentifierInfo *Ident,
12582 ParsedAttributes &Attrs,
12583 SourceLocation AttrEnd) {
12584 // C++1y [stmt.iter]p1:
12585 // A range-based for statement of the form
12586 // for ( for-range-identifier : for-range-initializer ) statement
12587 // is equivalent to
12588 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12589 DeclSpec DS(Attrs.getPool().getFactory());
12590
12591 const char *PrevSpec;
12592 unsigned DiagID;
12593 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12594 getPrintingPolicy());
12595
12596 Declarator D(DS, DeclaratorContext::ForContext);
12597 D.SetIdentifier(Ident, IdentLoc);
12598 D.takeAttributes(Attrs, AttrEnd);
12599
12600 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12601 IdentLoc);
12602 Decl *Var = ActOnDeclarator(S, D);
12603 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12604 FinalizeDeclaration(Var);
12605 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12606 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12607}
12608
12609void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12610 if (var->isInvalidDecl()) return;
1
Assuming the condition is false
2
Taking false branch
12611
12612 if (getLangOpts().OpenCL) {
3
Assuming field 'OpenCL' is 0
4
Taking false branch
12613 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12614 // initialiser
12615 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12616 !var->hasInit()) {
12617 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12618 << 1 /*Init*/;
12619 var->setInvalidDecl();
12620 return;
12621 }
12622 }
12623
12624 // In Objective-C, don't allow jumps past the implicit initialization of a
12625 // local retaining variable.
12626 if (getLangOpts().ObjC &&
5
Assuming field 'ObjC' is 0
12627 var->hasLocalStorage()) {
12628 switch (var->getType().getObjCLifetime()) {
12629 case Qualifiers::OCL_None:
12630 case Qualifiers::OCL_ExplicitNone:
12631 case Qualifiers::OCL_Autoreleasing:
12632 break;
12633
12634 case Qualifiers::OCL_Weak:
12635 case Qualifiers::OCL_Strong:
12636 setFunctionHasBranchProtectedScope();
12637 break;
12638 }
12639 }
12640
12641 if (var->hasLocalStorage() &&
6
Taking false branch
12642 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12643 setFunctionHasBranchProtectedScope();
12644
12645 // Warn about externally-visible variables being defined without a
12646 // prior declaration. We only want to do this for global
12647 // declarations, but we also specifically need to avoid doing it for
12648 // class members because the linkage of an anonymous class can
12649 // change if it's later given a typedef name.
12650 if (var->isThisDeclarationADefinition() &&
7
Assuming the condition is false
8
Taking false branch
12651 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12652 var->isExternallyVisible() && var->hasLinkage() &&
12653 !var->isInline() && !var->getDescribedVarTemplate() &&
12654 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12655 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12656 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12657 var->getLocation())) {
12658 // Find a previous declaration that's not a definition.
12659 VarDecl *prev = var->getPreviousDecl();
12660 while (prev && prev->isThisDeclarationADefinition())
12661 prev = prev->getPreviousDecl();
12662
12663 if (!prev) {
12664 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12665 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12666 << /* variable */ 0;
12667 }
12668 }
12669
12670 // Cache the result of checking for constant initialization.
12671 Optional<bool> CacheHasConstInit;
12672 const Expr *CacheCulprit = nullptr;
9
'CacheCulprit' initialized to a null pointer value
12673 auto checkConstInit = [&]() mutable {
12674 if (!CacheHasConstInit)
12675 CacheHasConstInit = var->getInit()->isConstantInitializer(
12676 Context, var->getType()->isReferenceType(), &CacheCulprit);
12677 return *CacheHasConstInit;
12678 };
12679
12680 if (var->getTLSKind() == VarDecl::TLS_Static) {
10
Assuming the condition is false
11
Taking false branch
12681 if (var->getType().isDestructedType()) {
12682 // GNU C++98 edits for __thread, [basic.start.term]p3:
12683 // The type of an object with thread storage duration shall not
12684 // have a non-trivial destructor.
12685 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12686 if (getLangOpts().CPlusPlus11)
12687 Diag(var->getLocation(), diag::note_use_thread_local);
12688 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12689 if (!checkConstInit()) {
12690 // GNU C++98 edits for __thread, [basic.start.init]p4:
12691 // An object of thread storage duration shall not require dynamic
12692 // initialization.
12693 // FIXME: Need strict checking here.
12694 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12695 << CacheCulprit->getSourceRange();
12696 if (getLangOpts().CPlusPlus11)
12697 Diag(var->getLocation(), diag::note_use_thread_local);
12698 }
12699 }
12700 }
12701
12702 // Apply section attributes and pragmas to global variables.
12703 bool GlobalStorage = var->hasGlobalStorage();
12
Calling 'VarDecl::hasGlobalStorage'
21
Returning from 'VarDecl::hasGlobalStorage'
12704 if (GlobalStorage
21.1
'GlobalStorage' is true
21.1
'GlobalStorage' is true
21.1
'GlobalStorage' is true
&& var->isThisDeclarationADefinition() &&
22
Assuming the condition is false
12705 !inTemplateInstantiation()) {
12706 PragmaStack<StringLiteral *> *Stack = nullptr;
12707 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12708 if (var->getType().isConstQualified())
12709 Stack = &ConstSegStack;
12710 else if (!var->getInit()) {
12711 Stack = &BSSSegStack;
12712 SectionFlags |= ASTContext::PSF_Write;
12713 } else {
12714 Stack = &DataSegStack;
12715 SectionFlags |= ASTContext::PSF_Write;
12716 }
12717 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12718 var->addAttr(SectionAttr::CreateImplicit(
12719 Context, Stack->CurrentValue->getString(),
12720 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12721 SectionAttr::Declspec_allocate));
12722 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12723 if (UnifySection(SA->getName(), SectionFlags, var))
12724 var->dropAttr<SectionAttr>();
12725
12726 // Apply the init_seg attribute if this has an initializer. If the
12727 // initializer turns out to not be dynamic, we'll end up ignoring this
12728 // attribute.
12729 if (CurInitSeg && var->getInit())
12730 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12731 CurInitSegLoc,
12732 AttributeCommonInfo::AS_Pragma));
12733 }
12734
12735 // All the following checks are C++ only.
12736 if (!getLangOpts().CPlusPlus) {
23
Assuming field 'CPlusPlus' is not equal to 0
24
Taking false branch
12737 // If this variable must be emitted, add it as an initializer for the
12738 // current module.
12739 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12740 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12741 return;
12742 }
12743
12744 if (auto *DD
25.1
'DD' is null
25.1
'DD' is null
25.1
'DD' is null
= dyn_cast<DecompositionDecl>(var))
25
Assuming 'var' is not a 'DecompositionDecl'
26
Taking false branch
12745 CheckCompleteDecompositionDeclaration(DD);
12746
12747 QualType type = var->getType();
12748 if (type->isDependentType()) return;
27
Assuming the condition is false
28
Taking false branch
12749
12750 if (var->hasAttr<BlocksAttr>())
29
Taking false branch
12751 getCurFunction()->addByrefBlockVar(var);
12752
12753 Expr *Init = var->getInit();
12754 bool IsGlobal = GlobalStorage
29.1
'GlobalStorage' is true
29.1
'GlobalStorage' is true
29.1
'GlobalStorage' is true
&& !var->isStaticLocal();
12755 QualType baseType = Context.getBaseElementType(type);
12756
12757 if (Init && !Init->isValueDependent()) {
30
Assuming 'Init' is non-null
31
Assuming the condition is true
32
Taking true branch
12758 if (var->isConstexpr()) {
33
Assuming the condition is false
34
Taking false branch
12759 SmallVector<PartialDiagnosticAt, 8> Notes;
12760 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12761 SourceLocation DiagLoc = var->getLocation();
12762 // If the note doesn't add any useful information other than a source
12763 // location, fold it into the primary diagnostic.
12764 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12765 diag::note_invalid_subexpr_in_const_expr) {
12766 DiagLoc = Notes[0].first;
12767 Notes.clear();
12768 }
12769 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12770 << var << Init->getSourceRange();
12771 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12772 Diag(Notes[I].first, Notes[I].second);
12773 }
12774 } else if (var->mightBeUsableInConstantExpressions(Context)) {
35
Assuming the condition is false
36
Taking false branch
12775 // Check whether the initializer of a const variable of integral or
12776 // enumeration type is an ICE now, since we can't tell whether it was
12777 // initialized by a constant expression if we check later.
12778 var->checkInitIsICE();
12779 }
12780
12781 // Don't emit further diagnostics about constexpr globals since they
12782 // were just diagnosed.
12783 if (!var->isConstexpr() && GlobalStorage
42.1
'GlobalStorage' is true
42.1
'GlobalStorage' is true
42.1
'GlobalStorage' is true
&& var->hasAttr<ConstInitAttr>()) {
37
Calling 'VarDecl::isConstexpr'
41
Returning from 'VarDecl::isConstexpr'
42
Assuming the condition is true
43
Calling 'Decl::hasAttr'
46
Returning from 'Decl::hasAttr'
47
Taking true branch
12784 // FIXME: Need strict checking in C++03 here.
12785 bool DiagErr = getLangOpts().CPlusPlus11
48
Assuming field 'CPlusPlus11' is not equal to 0
49
'?' condition is true
12786 ? !var->checkInitIsICE() : !checkConstInit();
50
Assuming the condition is true
12787 if (DiagErr
50.1
'DiagErr' is true
50.1
'DiagErr' is true
50.1
'DiagErr' is true
) {
51
Taking true branch
12788 auto *Attr = var->getAttr<ConstInitAttr>();
12789 Diag(var->getLocation(), diag::err_require_constant_init_failed)
12790 << Init->getSourceRange();
12791 Diag(Attr->getLocation(),
12792 diag::note_declared_required_constant_init_here)
12793 << Attr->getRange() << Attr->isConstinit();
12794 if (getLangOpts().CPlusPlus11) {
52
Assuming field 'CPlusPlus11' is 0
53
Taking false branch
12795 APValue Value;
12796 SmallVector<PartialDiagnosticAt, 8> Notes;
12797 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12798 for (auto &it : Notes)
12799 Diag(it.first, it.second);
12800 } else {
12801 Diag(CacheCulprit->getExprLoc(),
54
Called C++ object pointer is null
12802 diag::note_invalid_subexpr_in_const_expr)
12803 << CacheCulprit->getSourceRange();
12804 }
12805 }
12806 }
12807 else if (!var->isConstexpr() && IsGlobal &&
12808 !getDiagnostics().isIgnored(diag::warn_global_constructor,
12809 var->getLocation())) {
12810 // Warn about globals which don't have a constant initializer. Don't
12811 // warn about globals with a non-trivial destructor because we already
12812 // warned about them.
12813 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12814 if (!(RD && !RD->hasTrivialDestructor())) {
12815 if (!checkConstInit())
12816 Diag(var->getLocation(), diag::warn_global_constructor)
12817 << Init->getSourceRange();
12818 }
12819 }
12820 }
12821
12822 // Require the destructor.
12823 if (const RecordType *recordType = baseType->getAs<RecordType>())
12824 FinalizeVarWithDestructor(var, recordType);
12825
12826 // If this variable must be emitted, add it as an initializer for the current
12827 // module.
12828 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12829 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12830}
12831
12832/// Determines if a variable's alignment is dependent.
12833static bool hasDependentAlignment(VarDecl *VD) {
12834 if (VD->getType()->isDependentType())
12835 return true;
12836 for (auto *I : VD->specific_attrs<AlignedAttr>())
12837 if (I->isAlignmentDependent())
12838 return true;
12839 return false;
12840}
12841
12842/// Check if VD needs to be dllexport/dllimport due to being in a
12843/// dllexport/import function.
12844void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12845 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 12845, __PRETTY_FUNCTION__))
;
12846
12847 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12848
12849 // Find outermost function when VD is in lambda function.
12850 while (FD && !getDLLAttr(FD) &&
12851 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12852 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12853 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12854 }
12855
12856 if (!FD)
12857 return;
12858
12859 // Static locals inherit dll attributes from their function.
12860 if (Attr *A = getDLLAttr(FD)) {
12861 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12862 NewAttr->setInherited(true);
12863 VD->addAttr(NewAttr);
12864 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12865 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12866 NewAttr->setInherited(true);
12867 VD->addAttr(NewAttr);
12868
12869 // Export this function to enforce exporting this static variable even
12870 // if it is not used in this compilation unit.
12871 if (!FD->hasAttr<DLLExportAttr>())
12872 FD->addAttr(NewAttr);
12873
12874 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12875 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12876 NewAttr->setInherited(true);
12877 VD->addAttr(NewAttr);
12878 }
12879}
12880
12881/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12882/// any semantic actions necessary after any initializer has been attached.
12883void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12884 // Note that we are no longer parsing the initializer for this declaration.
12885 ParsingInitForAutoVars.erase(ThisDecl);
12886
12887 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12888 if (!VD)
12889 return;
12890
12891 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12892 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12893 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12894 if (PragmaClangBSSSection.Valid)
12895 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12896 Context, PragmaClangBSSSection.SectionName,
12897 PragmaClangBSSSection.PragmaLocation,
12898 AttributeCommonInfo::AS_Pragma));
12899 if (PragmaClangDataSection.Valid)
12900 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12901 Context, PragmaClangDataSection.SectionName,
12902 PragmaClangDataSection.PragmaLocation,
12903 AttributeCommonInfo::AS_Pragma));
12904 if (PragmaClangRodataSection.Valid)
12905 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12906 Context, PragmaClangRodataSection.SectionName,
12907 PragmaClangRodataSection.PragmaLocation,
12908 AttributeCommonInfo::AS_Pragma));
12909 if (PragmaClangRelroSection.Valid)
12910 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12911 Context, PragmaClangRelroSection.SectionName,
12912 PragmaClangRelroSection.PragmaLocation,
12913 AttributeCommonInfo::AS_Pragma));
12914 }
12915
12916 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12917 for (auto *BD : DD->bindings()) {
12918 FinalizeDeclaration(BD);
12919 }
12920 }
12921
12922 checkAttributesAfterMerging(*this, *VD);
12923
12924 // Perform TLS alignment check here after attributes attached to the variable
12925 // which may affect the alignment have been processed. Only perform the check
12926 // if the target has a maximum TLS alignment (zero means no constraints).
12927 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12928 // Protect the check so that it's not performed on dependent types and
12929 // dependent alignments (we can't determine the alignment in that case).
12930 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12931 !VD->isInvalidDecl()) {
12932 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12933 if (Context.getDeclAlign(VD) > MaxAlignChars) {
12934 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12935 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12936 << (unsigned)MaxAlignChars.getQuantity();
12937 }
12938 }
12939 }
12940
12941 if (VD->isStaticLocal()) {
12942 CheckStaticLocalForDllExport(VD);
12943
12944 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12945 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12946 // function, only __shared__ variables or variables without any device
12947 // memory qualifiers may be declared with static storage class.
12948 // Note: It is unclear how a function-scope non-const static variable
12949 // without device memory qualifier is implemented, therefore only static
12950 // const variable without device memory qualifier is allowed.
12951 [&]() {
12952 if (!getLangOpts().CUDA)
12953 return;
12954 if (VD->hasAttr<CUDASharedAttr>())
12955 return;
12956 if (VD->getType().isConstQualified() &&
12957 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12958 return;
12959 if (CUDADiagIfDeviceCode(VD->getLocation(),
12960 diag::err_device_static_local_var)
12961 << CurrentCUDATarget())
12962 VD->setInvalidDecl();
12963 }();
12964 }
12965 }
12966
12967 // Perform check for initializers of device-side global variables.
12968 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12969 // 7.5). We must also apply the same checks to all __shared__
12970 // variables whether they are local or not. CUDA also allows
12971 // constant initializers for __constant__ and __device__ variables.
12972 if (getLangOpts().CUDA)
12973 checkAllowedCUDAInitializer(VD);
12974
12975 // Grab the dllimport or dllexport attribute off of the VarDecl.
12976 const InheritableAttr *DLLAttr = getDLLAttr(VD);
12977
12978 // Imported static data members cannot be defined out-of-line.
12979 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12980 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12981 VD->isThisDeclarationADefinition()) {
12982 // We allow definitions of dllimport class template static data members
12983 // with a warning.
12984 CXXRecordDecl *Context =
12985 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12986 bool IsClassTemplateMember =
12987 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12988 Context->getDescribedClassTemplate();
12989
12990 Diag(VD->getLocation(),
12991 IsClassTemplateMember
12992 ? diag::warn_attribute_dllimport_static_field_definition
12993 : diag::err_attribute_dllimport_static_field_definition);
12994 Diag(IA->getLocation(), diag::note_attribute);
12995 if (!IsClassTemplateMember)
12996 VD->setInvalidDecl();
12997 }
12998 }
12999
13000 // dllimport/dllexport variables cannot be thread local, their TLS index
13001 // isn't exported with the variable.
13002 if (DLLAttr && VD->getTLSKind()) {
13003 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13004 if (F && getDLLAttr(F)) {
13005 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13005, __PRETTY_FUNCTION__))
;
13006 // But if this is a static local in a dlimport/dllexport function, the
13007 // function will never be inlined, which means the var would never be
13008 // imported, so having it marked import/export is safe.
13009 } else {
13010 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13011 << DLLAttr;
13012 VD->setInvalidDecl();
13013 }
13014 }
13015
13016 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13017 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13018 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13019 VD->dropAttr<UsedAttr>();
13020 }
13021 }
13022
13023 const DeclContext *DC = VD->getDeclContext();
13024 // If there's a #pragma GCC visibility in scope, and this isn't a class
13025 // member, set the visibility of this variable.
13026 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13027 AddPushedVisibilityAttribute(VD);
13028
13029 // FIXME: Warn on unused var template partial specializations.
13030 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13031 MarkUnusedFileScopedDecl(VD);
13032
13033 // Now we have parsed the initializer and can update the table of magic
13034 // tag values.
13035 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13036 !VD->getType()->isIntegralOrEnumerationType())
13037 return;
13038
13039 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13040 const Expr *MagicValueExpr = VD->getInit();
13041 if (!MagicValueExpr) {
13042 continue;
13043 }
13044 llvm::APSInt MagicValueInt;
13045 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
13046 Diag(I->getRange().getBegin(),
13047 diag::err_type_tag_for_datatype_not_ice)
13048 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13049 continue;
13050 }
13051 if (MagicValueInt.getActiveBits() > 64) {
13052 Diag(I->getRange().getBegin(),
13053 diag::err_type_tag_for_datatype_too_large)
13054 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13055 continue;
13056 }
13057 uint64_t MagicValue = MagicValueInt.getZExtValue();
13058 RegisterTypeTagForDatatype(I->getArgumentKind(),
13059 MagicValue,
13060 I->getMatchingCType(),
13061 I->getLayoutCompatible(),
13062 I->getMustBeNull());
13063 }
13064}
13065
13066static bool hasDeducedAuto(DeclaratorDecl *DD) {
13067 auto *VD = dyn_cast<VarDecl>(DD);
13068 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13069}
13070
13071Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13072 ArrayRef<Decl *> Group) {
13073 SmallVector<Decl*, 8> Decls;
13074
13075 if (DS.isTypeSpecOwned())
13076 Decls.push_back(DS.getRepAsDecl());
13077
13078 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13079 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13080 bool DiagnosedMultipleDecomps = false;
13081 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13082 bool DiagnosedNonDeducedAuto = false;
13083
13084 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13085 if (Decl *D = Group[i]) {
13086 // For declarators, there are some additional syntactic-ish checks we need
13087 // to perform.
13088 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13089 if (!FirstDeclaratorInGroup)
13090 FirstDeclaratorInGroup = DD;
13091 if (!FirstDecompDeclaratorInGroup)
13092 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13093 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13094 !hasDeducedAuto(DD))
13095 FirstNonDeducedAutoInGroup = DD;
13096
13097 if (FirstDeclaratorInGroup != DD) {
13098 // A decomposition declaration cannot be combined with any other
13099 // declaration in the same group.
13100 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13101 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13102 diag::err_decomp_decl_not_alone)
13103 << FirstDeclaratorInGroup->getSourceRange()
13104 << DD->getSourceRange();
13105 DiagnosedMultipleDecomps = true;
13106 }
13107
13108 // A declarator that uses 'auto' in any way other than to declare a
13109 // variable with a deduced type cannot be combined with any other
13110 // declarator in the same group.
13111 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13112 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13113 diag::err_auto_non_deduced_not_alone)
13114 << FirstNonDeducedAutoInGroup->getType()
13115 ->hasAutoForTrailingReturnType()
13116 << FirstDeclaratorInGroup->getSourceRange()
13117 << DD->getSourceRange();
13118 DiagnosedNonDeducedAuto = true;
13119 }
13120 }
13121 }
13122
13123 Decls.push_back(D);
13124 }
13125 }
13126
13127 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13128 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13129 handleTagNumbering(Tag, S);
13130 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13131 getLangOpts().CPlusPlus)
13132 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13133 }
13134 }
13135
13136 return BuildDeclaratorGroup(Decls);
13137}
13138
13139/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13140/// group, performing any necessary semantic checking.
13141Sema::DeclGroupPtrTy
13142Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13143 // C++14 [dcl.spec.auto]p7: (DR1347)
13144 // If the type that replaces the placeholder type is not the same in each
13145 // deduction, the program is ill-formed.
13146 if (Group.size() > 1) {
13147 QualType Deduced;
13148 VarDecl *DeducedDecl = nullptr;
13149 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13150 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13151 if (!D || D->isInvalidDecl())
13152 break;
13153 DeducedType *DT = D->getType()->getContainedDeducedType();
13154 if (!DT || DT->getDeducedType().isNull())
13155 continue;
13156 if (Deduced.isNull()) {
13157 Deduced = DT->getDeducedType();
13158 DeducedDecl = D;
13159 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13160 auto *AT = dyn_cast<AutoType>(DT);
13161 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13162 diag::err_auto_different_deductions)
13163 << (AT ? (unsigned)AT->getKeyword() : 3)
13164 << Deduced << DeducedDecl->getDeclName()
13165 << DT->getDeducedType() << D->getDeclName()
13166 << DeducedDecl->getInit()->getSourceRange()
13167 << D->getInit()->getSourceRange();
13168 D->setInvalidDecl();
13169 break;
13170 }
13171 }
13172 }
13173
13174 ActOnDocumentableDecls(Group);
13175
13176 return DeclGroupPtrTy::make(
13177 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13178}
13179
13180void Sema::ActOnDocumentableDecl(Decl *D) {
13181 ActOnDocumentableDecls(D);
13182}
13183
13184void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13185 // Don't parse the comment if Doxygen diagnostics are ignored.
13186 if (Group.empty() || !Group[0])
13187 return;
13188
13189 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13190 Group[0]->getLocation()) &&
13191 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13192 Group[0]->getLocation()))
13193 return;
13194
13195 if (Group.size() >= 2) {
13196 // This is a decl group. Normally it will contain only declarations
13197 // produced from declarator list. But in case we have any definitions or
13198 // additional declaration references:
13199 // 'typedef struct S {} S;'
13200 // 'typedef struct S *S;'
13201 // 'struct S *pS;'
13202 // FinalizeDeclaratorGroup adds these as separate declarations.
13203 Decl *MaybeTagDecl = Group[0];
13204 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13205 Group = Group.slice(1);
13206 }
13207 }
13208
13209 // FIMXE: We assume every Decl in the group is in the same file.
13210 // This is false when preprocessor constructs the group from decls in
13211 // different files (e. g. macros or #include).
13212 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13213}
13214
13215/// Common checks for a parameter-declaration that should apply to both function
13216/// parameters and non-type template parameters.
13217void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13218 // Check that there are no default arguments inside the type of this
13219 // parameter.
13220 if (getLangOpts().CPlusPlus)
13221 CheckExtraCXXDefaultArguments(D);
13222
13223 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13224 if (D.getCXXScopeSpec().isSet()) {
13225 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13226 << D.getCXXScopeSpec().getRange();
13227 }
13228
13229 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13230 // simple identifier except [...irrelevant cases...].
13231 switch (D.getName().getKind()) {
13232 case UnqualifiedIdKind::IK_Identifier:
13233 break;
13234
13235 case UnqualifiedIdKind::IK_OperatorFunctionId:
13236 case UnqualifiedIdKind::IK_ConversionFunctionId:
13237 case UnqualifiedIdKind::IK_LiteralOperatorId:
13238 case UnqualifiedIdKind::IK_ConstructorName:
13239 case UnqualifiedIdKind::IK_DestructorName:
13240 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13241 case UnqualifiedIdKind::IK_DeductionGuideName:
13242 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13243 << GetNameForDeclarator(D).getName();
13244 break;
13245
13246 case UnqualifiedIdKind::IK_TemplateId:
13247 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13248 // GetNameForDeclarator would not produce a useful name in this case.
13249 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13250 break;
13251 }
13252}
13253
13254/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13255/// to introduce parameters into function prototype scope.
13256Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13257 const DeclSpec &DS = D.getDeclSpec();
13258
13259 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13260
13261 // C++03 [dcl.stc]p2 also permits 'auto'.
13262 StorageClass SC = SC_None;
13263 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13264 SC = SC_Register;
13265 // In C++11, the 'register' storage class specifier is deprecated.
13266 // In C++17, it is not allowed, but we tolerate it as an extension.
13267 if (getLangOpts().CPlusPlus11) {
13268 Diag(DS.getStorageClassSpecLoc(),
13269 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13270 : diag::warn_deprecated_register)
13271 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13272 }
13273 } else if (getLangOpts().CPlusPlus &&
13274 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13275 SC = SC_Auto;
13276 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13277 Diag(DS.getStorageClassSpecLoc(),
13278 diag::err_invalid_storage_class_in_func_decl);
13279 D.getMutableDeclSpec().ClearStorageClassSpecs();
13280 }
13281
13282 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13283 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13284 << DeclSpec::getSpecifierName(TSCS);
13285 if (DS.isInlineSpecified())
13286 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13287 << getLangOpts().CPlusPlus17;
13288 if (DS.hasConstexprSpecifier())
13289 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13290 << 0 << D.getDeclSpec().getConstexprSpecifier();
13291
13292 DiagnoseFunctionSpecifiers(DS);
13293
13294 CheckFunctionOrTemplateParamDeclarator(S, D);
13295
13296 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13297 QualType parmDeclType = TInfo->getType();
13298
13299 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13300 IdentifierInfo *II = D.getIdentifier();
13301 if (II) {
13302 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13303 ForVisibleRedeclaration);
13304 LookupName(R, S);
13305 if (R.isSingleResult()) {
13306 NamedDecl *PrevDecl = R.getFoundDecl();
13307 if (PrevDecl->isTemplateParameter()) {
13308 // Maybe we will complain about the shadowed template parameter.
13309 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13310 // Just pretend that we didn't see the previous declaration.
13311 PrevDecl = nullptr;
13312 } else if (S->isDeclScope(PrevDecl)) {
13313 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13314 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13315
13316 // Recover by removing the name
13317 II = nullptr;
13318 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13319 D.setInvalidType(true);
13320 }
13321 }
13322 }
13323
13324 // Temporarily put parameter variables in the translation unit, not
13325 // the enclosing context. This prevents them from accidentally
13326 // looking like class members in C++.
13327 ParmVarDecl *New =
13328 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13329 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13330
13331 if (D.isInvalidType())
13332 New->setInvalidDecl();
13333
13334 assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void>
(0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13334, __PRETTY_FUNCTION__))
;
13335 assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast<
void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13335, __PRETTY_FUNCTION__))
;
13336 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13337 S->getNextFunctionPrototypeIndex());
13338
13339 // Add the parameter declaration into this scope.
13340 S->AddDecl(New);
13341 if (II)
13342 IdResolver.AddDecl(New);
13343
13344 ProcessDeclAttributes(S, New, D);
13345
13346 if (D.getDeclSpec().isModulePrivateSpecified())
13347 Diag(New->getLocation(), diag::err_module_private_local)
13348 << 1 << New->getDeclName()
13349 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13350 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13351
13352 if (New->hasAttr<BlocksAttr>()) {
13353 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13354 }
13355
13356 if (getLangOpts().OpenCL)
13357 deduceOpenCLAddressSpace(New);
13358
13359 return New;
13360}
13361
13362/// Synthesizes a variable for a parameter arising from a
13363/// typedef.
13364ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13365 SourceLocation Loc,
13366 QualType T) {
13367 /* FIXME: setting StartLoc == Loc.
13368 Would it be worth to modify callers so as to provide proper source
13369 location for the unnamed parameters, embedding the parameter's type? */
13370 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13371 T, Context.getTrivialTypeSourceInfo(T, Loc),
13372 SC_None, nullptr);
13373 Param->setImplicit();
13374 return Param;
13375}
13376
13377void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13378 // Don't diagnose unused-parameter errors in template instantiations; we
13379 // will already have done so in the template itself.
13380 if (inTemplateInstantiation())
13381 return;
13382
13383 for (const ParmVarDecl *Parameter : Parameters) {
13384 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13385 !Parameter->hasAttr<UnusedAttr>()) {
13386 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13387 << Parameter->getDeclName();
13388 }
13389 }
13390}
13391
13392void Sema::DiagnoseSizeOfParametersAndReturnValue(
13393 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13394 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13395 return;
13396
13397 // Warn if the return value is pass-by-value and larger than the specified
13398 // threshold.
13399 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13400 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13401 if (Size > LangOpts.NumLargeByValueCopy)
13402 Diag(D->getLocation(), diag::warn_return_value_size)
13403 << D->getDeclName() << Size;
13404 }
13405
13406 // Warn if any parameter is pass-by-value and larger than the specified
13407 // threshold.
13408 for (const ParmVarDecl *Parameter : Parameters) {
13409 QualType T = Parameter->getType();
13410 if (T->isDependentType() || !T.isPODType(Context))
13411 continue;
13412 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13413 if (Size > LangOpts.NumLargeByValueCopy)
13414 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13415 << Parameter->getDeclName() << Size;
13416 }
13417}
13418
13419ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13420 SourceLocation NameLoc, IdentifierInfo *Name,
13421 QualType T, TypeSourceInfo *TSInfo,
13422 StorageClass SC) {
13423 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13424 if (getLangOpts().ObjCAutoRefCount &&
13425 T.getObjCLifetime() == Qualifiers::OCL_None &&
13426 T->isObjCLifetimeType()) {
13427
13428 Qualifiers::ObjCLifetime lifetime;
13429
13430 // Special cases for arrays:
13431 // - if it's const, use __unsafe_unretained
13432 // - otherwise, it's an error
13433 if (T->isArrayType()) {
13434 if (!T.isConstQualified()) {
13435 if (DelayedDiagnostics.shouldDelayDiagnostics())
13436 DelayedDiagnostics.add(
13437 sema::DelayedDiagnostic::makeForbiddenType(
13438 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13439 else
13440 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13441 << TSInfo->getTypeLoc().getSourceRange();
13442 }
13443 lifetime = Qualifiers::OCL_ExplicitNone;
13444 } else {
13445 lifetime = T->getObjCARCImplicitLifetime();
13446 }
13447 T = Context.getLifetimeQualifiedType(T, lifetime);
13448 }
13449
13450 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13451 Context.getAdjustedParameterType(T),
13452 TSInfo, SC, nullptr);
13453
13454 // Make a note if we created a new pack in the scope of a lambda, so that
13455 // we know that references to that pack must also be expanded within the
13456 // lambda scope.
13457 if (New->isParameterPack())
13458 if (auto *LSI = getEnclosingLambda())
13459 LSI->LocalPacks.push_back(New);
13460
13461 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13462 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13463 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13464 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13465
13466 // Parameters can not be abstract class types.
13467 // For record types, this is done by the AbstractClassUsageDiagnoser once
13468 // the class has been completely parsed.
13469 if (!CurContext->isRecord() &&
13470 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13471 AbstractParamType))
13472 New->setInvalidDecl();
13473
13474 // Parameter declarators cannot be interface types. All ObjC objects are
13475 // passed by reference.
13476 if (T->isObjCObjectType()) {
13477 SourceLocation TypeEndLoc =
13478 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13479 Diag(NameLoc,
13480 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13481 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13482 T = Context.getObjCObjectPointerType(T);
13483 New->setType(T);
13484 }
13485
13486 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13487 // duration shall not be qualified by an address-space qualifier."
13488 // Since all parameters have automatic store duration, they can not have
13489 // an address space.
13490 if (T.getAddressSpace() != LangAS::Default &&
13491 // OpenCL allows function arguments declared to be an array of a type
13492 // to be qualified with an address space.
13493 !(getLangOpts().OpenCL &&
13494 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13495 Diag(NameLoc, diag::err_arg_with_address_space);
13496 New->setInvalidDecl();
13497 }
13498
13499 return New;
13500}
13501
13502void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13503 SourceLocation LocAfterDecls) {
13504 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13505
13506 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13507 // for a K&R function.
13508 if (!FTI.hasPrototype) {
13509 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13510 --i;
13511 if (FTI.Params[i].Param == nullptr) {
13512 SmallString<256> Code;
13513 llvm::raw_svector_ostream(Code)
13514 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13515 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13516 << FTI.Params[i].Ident
13517 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13518
13519 // Implicitly declare the argument as type 'int' for lack of a better
13520 // type.
13521 AttributeFactory attrs;
13522 DeclSpec DS(attrs);
13523 const char* PrevSpec; // unused
13524 unsigned DiagID; // unused
13525 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13526 DiagID, Context.getPrintingPolicy());
13527 // Use the identifier location for the type source range.
13528 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13529 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13530 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13531 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13532 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13533 }
13534 }
13535 }
13536}
13537
13538Decl *
13539Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13540 MultiTemplateParamsArg TemplateParameterLists,
13541 SkipBodyInfo *SkipBody) {
13542 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused"
) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13542, __PRETTY_FUNCTION__))
;
13543 assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!"
) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13543, __PRETTY_FUNCTION__))
;
13544 Scope *ParentScope = FnBodyScope->getParent();
13545
13546 D.setFunctionDefinitionKind(FDK_Definition);
13547 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13548 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13549}
13550
13551void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13552 Consumer.HandleInlineFunctionDefinition(D);
13553}
13554
13555static bool
13556ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13557 const FunctionDecl *&PossiblePrototype) {
13558 // Don't warn about invalid declarations.
13559 if (FD->isInvalidDecl())
13560 return false;
13561
13562 // Or declarations that aren't global.
13563 if (!FD->isGlobal())
13564 return false;
13565
13566 // Don't warn about C++ member functions.
13567 if (isa<CXXMethodDecl>(FD))
13568 return false;
13569
13570 // Don't warn about 'main'.
13571 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13572 if (IdentifierInfo *II = FD->getIdentifier())
13573 if (II->isStr("main"))
13574 return false;
13575
13576 // Don't warn about inline functions.
13577 if (FD->isInlined())
13578 return false;
13579
13580 // Don't warn about function templates.
13581 if (FD->getDescribedFunctionTemplate())
13582 return false;
13583
13584 // Don't warn about function template specializations.
13585 if (FD->isFunctionTemplateSpecialization())
13586 return false;
13587
13588 // Don't warn for OpenCL kernels.
13589 if (FD->hasAttr<OpenCLKernelAttr>())
13590 return false;
13591
13592 // Don't warn on explicitly deleted functions.
13593 if (FD->isDeleted())
13594 return false;
13595
13596 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13597 Prev; Prev = Prev->getPreviousDecl()) {
13598 // Ignore any declarations that occur in function or method
13599 // scope, because they aren't visible from the header.
13600 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13601 continue;
13602
13603 PossiblePrototype = Prev;
13604 return Prev->getType()->isFunctionNoProtoType();
13605 }
13606
13607 return true;
13608}
13609
13610void
13611Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13612 const FunctionDecl *EffectiveDefinition,
13613 SkipBodyInfo *SkipBody) {
13614 const FunctionDecl *Definition = EffectiveDefinition;
13615 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13616 // If this is a friend function defined in a class template, it does not
13617 // have a body until it is used, nevertheless it is a definition, see
13618 // [temp.inst]p2:
13619 //
13620 // ... for the purpose of determining whether an instantiated redeclaration
13621 // is valid according to [basic.def.odr] and [class.mem], a declaration that
13622 // corresponds to a definition in the template is considered to be a
13623 // definition.
13624 //
13625 // The following code must produce redefinition error:
13626 //
13627 // template<typename T> struct C20 { friend void func_20() {} };
13628 // C20<int> c20i;
13629 // void func_20() {}
13630 //
13631 for (auto I : FD->redecls()) {
13632 if (I != FD && !I->isInvalidDecl() &&
13633 I->getFriendObjectKind() != Decl::FOK_None) {
13634 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13635 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13636 // A merged copy of the same function, instantiated as a member of
13637 // the same class, is OK.
13638 if (declaresSameEntity(OrigFD, Original) &&
13639 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13640 cast<Decl>(FD->getLexicalDeclContext())))
13641 continue;
13642 }
13643
13644 if (Original->isThisDeclarationADefinition()) {
13645 Definition = I;
13646 break;
13647 }
13648 }
13649 }
13650 }
13651 }
13652
13653 if (!Definition)
13654 // Similar to friend functions a friend function template may be a
13655 // definition and do not have a body if it is instantiated in a class
13656 // template.
13657 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13658 for (auto I : FTD->redecls()) {
13659 auto D = cast<FunctionTemplateDecl>(I);
13660 if (D != FTD) {
13661 assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13662, __PRETTY_FUNCTION__))
13662 "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13662, __PRETTY_FUNCTION__))
;
13663 if (D->getFriendObjectKind() != Decl::FOK_None)
13664 if (FunctionTemplateDecl *FT =
13665 D->getInstantiatedFromMemberTemplate()) {
13666 if (FT->isThisDeclarationADefinition()) {
13667 Definition = D->getTemplatedDecl();
13668 break;
13669 }
13670 }
13671 }
13672 }
13673 }
13674
13675 if (!Definition)
13676 return;
13677
13678 if (canRedefineFunction(Definition, getLangOpts()))
13679 return;
13680
13681 // Don't emit an error when this is redefinition of a typo-corrected
13682 // definition.
13683 if (TypoCorrectedFunctionDefinitions.count(Definition))
13684 return;
13685
13686 // If we don't have a visible definition of the function, and it's inline or
13687 // a template, skip the new definition.
13688 if (SkipBody && !hasVisibleDefinition(Definition) &&
13689 (Definition->getFormalLinkage() == InternalLinkage ||
13690 Definition->isInlined() ||
13691 Definition->getDescribedFunctionTemplate() ||
13692 Definition->getNumTemplateParameterLists())) {
13693 SkipBody->ShouldSkip = true;
13694 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13695 if (auto *TD = Definition->getDescribedFunctionTemplate())
13696 makeMergedDefinitionVisible(TD);
13697 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13698 return;
13699 }
13700
13701 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13702 Definition->getStorageClass() == SC_Extern)
13703 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13704 << FD->getDeclName() << getLangOpts().CPlusPlus;
13705 else
13706 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13707
13708 Diag(Definition->getLocation(), diag::note_previous_definition);
13709 FD->setInvalidDecl();
13710}
13711
13712static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13713 Sema &S) {
13714 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13715
13716 LambdaScopeInfo *LSI = S.PushLambdaScope();
13717 LSI->CallOperator = CallOperator;
13718 LSI->Lambda = LambdaClass;
13719 LSI->ReturnType = CallOperator->getReturnType();
13720 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13721
13722 if (LCD == LCD_None)
13723 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13724 else if (LCD == LCD_ByCopy)
13725 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13726 else if (LCD == LCD_ByRef)
13727 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13728 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13729
13730 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13731 LSI->Mutable = !CallOperator->isConst();
13732
13733 // Add the captures to the LSI so they can be noted as already
13734 // captured within tryCaptureVar.
13735 auto I = LambdaClass->field_begin();
13736 for (const auto &C : LambdaClass->captures()) {
13737 if (C.capturesVariable()) {
13738 VarDecl *VD = C.getCapturedVar();
13739 if (VD->isInitCapture())
13740 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13741 QualType CaptureType = VD->getType();
13742 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13743 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13744 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13745 /*EllipsisLoc*/C.isPackExpansion()
13746 ? C.getEllipsisLoc() : SourceLocation(),
13747 CaptureType, /*Invalid*/false);
13748
13749 } else if (C.capturesThis()) {
13750 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13751 C.getCaptureKind() == LCK_StarThis);
13752 } else {
13753 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13754 I->getType());
13755 }
13756 ++I;
13757 }
13758}
13759
13760Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13761 SkipBodyInfo *SkipBody) {
13762 if (!D) {
13763 // Parsing the function declaration failed in some way. Push on a fake scope
13764 // anyway so we can try to parse the function body.
13765 PushFunctionScope();
13766 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13767 return D;
13768 }
13769
13770 FunctionDecl *FD = nullptr;
13771
13772 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13773 FD = FunTmpl->getTemplatedDecl();
13774 else
13775 FD = cast<FunctionDecl>(D);
13776
13777 // Do not push if it is a lambda because one is already pushed when building
13778 // the lambda in ActOnStartOfLambdaDefinition().
13779 if (!isLambdaCallOperator(FD))
13780 PushExpressionEvaluationContext(
13781 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13782 : ExprEvalContexts.back().Context);
13783
13784 // Check for defining attributes before the check for redefinition.
13785 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13786 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13787 FD->dropAttr<AliasAttr>();
13788 FD->setInvalidDecl();
13789 }
13790 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13791 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13792 FD->dropAttr<IFuncAttr>();
13793 FD->setInvalidDecl();
13794 }
13795
13796 // See if this is a redefinition. If 'will have body' is already set, then
13797 // these checks were already performed when it was set.
13798 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13799 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13800
13801 // If we're skipping the body, we're done. Don't enter the scope.
13802 if (SkipBody && SkipBody->ShouldSkip)
13803 return D;
13804 }
13805
13806 // Mark this function as "will have a body eventually". This lets users to
13807 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13808 // this function.
13809 FD->setWillHaveBody();
13810
13811 // If we are instantiating a generic lambda call operator, push
13812 // a LambdaScopeInfo onto the function stack. But use the information
13813 // that's already been calculated (ActOnLambdaExpr) to prime the current
13814 // LambdaScopeInfo.
13815 // When the template operator is being specialized, the LambdaScopeInfo,
13816 // has to be properly restored so that tryCaptureVariable doesn't try
13817 // and capture any new variables. In addition when calculating potential
13818 // captures during transformation of nested lambdas, it is necessary to
13819 // have the LSI properly restored.
13820 if (isGenericLambdaCallOperatorSpecialization(FD)) {
13821 assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13823, __PRETTY_FUNCTION__))
13822 "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13823, __PRETTY_FUNCTION__))
13823 "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13823, __PRETTY_FUNCTION__))
;
13824 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13825 } else {
13826 // Enter a new function scope
13827 PushFunctionScope();
13828 }
13829
13830 // Builtin functions cannot be defined.
13831 if (unsigned BuiltinID = FD->getBuiltinID()) {
13832 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13833 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13834 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13835 FD->setInvalidDecl();
13836 }
13837 }
13838
13839 // The return type of a function definition must be complete
13840 // (C99 6.9.1p3, C++ [dcl.fct]p6).
13841 QualType ResultType = FD->getReturnType();
13842 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13843 !FD->isInvalidDecl() &&
13844 RequireCompleteType(FD->getLocation(), ResultType,
13845 diag::err_func_def_incomplete_result))
13846 FD->setInvalidDecl();
13847
13848 if (FnBodyScope)
13849 PushDeclContext(FnBodyScope, FD);
13850
13851 // Check the validity of our function parameters
13852 CheckParmsForFunctionDef(FD->parameters(),
13853 /*CheckParameterNames=*/true);
13854
13855 // Add non-parameter declarations already in the function to the current
13856 // scope.
13857 if (FnBodyScope) {
13858 for (Decl *NPD : FD->decls()) {
13859 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13860 if (!NonParmDecl)
13861 continue;
13862 assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13863, __PRETTY_FUNCTION__))
13863 "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13863, __PRETTY_FUNCTION__))
;
13864
13865 // If the decl has a name, make it accessible in the current scope.
13866 if (NonParmDecl->getDeclName())
13867 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13868
13869 // Similarly, dive into enums and fish their constants out, making them
13870 // accessible in this scope.
13871 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13872 for (auto *EI : ED->enumerators())
13873 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13874 }
13875 }
13876 }
13877
13878 // Introduce our parameters into the function scope
13879 for (auto Param : FD->parameters()) {
13880 Param->setOwningFunction(FD);
13881
13882 // If this has an identifier, add it to the scope stack.
13883 if (Param->getIdentifier() && FnBodyScope) {
13884 CheckShadow(FnBodyScope, Param);
13885
13886 PushOnScopeChains(Param, FnBodyScope);
13887 }
13888 }
13889
13890 // Ensure that the function's exception specification is instantiated.
13891 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13892 ResolveExceptionSpec(D->getLocation(), FPT);
13893
13894 // dllimport cannot be applied to non-inline function definitions.
13895 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13896 !FD->isTemplateInstantiation()) {
13897 assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void
> (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 13897, __PRETTY_FUNCTION__))
;
13898 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13899 FD->setInvalidDecl();
13900 return D;
13901 }
13902 // We want to attach documentation to original Decl (which might be
13903 // a function template).
13904 ActOnDocumentableDecl(D);
13905 if (getCurLexicalContext()->isObjCContainer() &&
13906 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13907 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13908 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13909
13910 return D;
13911}
13912
13913/// Given the set of return statements within a function body,
13914/// compute the variables that are subject to the named return value
13915/// optimization.
13916///
13917/// Each of the variables that is subject to the named return value
13918/// optimization will be marked as NRVO variables in the AST, and any
13919/// return statement that has a marked NRVO variable as its NRVO candidate can
13920/// use the named return value optimization.
13921///
13922/// This function applies a very simplistic algorithm for NRVO: if every return
13923/// statement in the scope of a variable has the same NRVO candidate, that
13924/// candidate is an NRVO variable.
13925void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13926 ReturnStmt **Returns = Scope->Returns.data();
13927
13928 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13929 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13930 if (!NRVOCandidate->isNRVOVariable())
13931 Returns[I]->setNRVOCandidate(nullptr);
13932 }
13933 }
13934}
13935
13936bool Sema::canDelayFunctionBody(const Declarator &D) {
13937 // We can't delay parsing the body of a constexpr function template (yet).
13938 if (D.getDeclSpec().hasConstexprSpecifier())
13939 return false;
13940
13941 // We can't delay parsing the body of a function template with a deduced
13942 // return type (yet).
13943 if (D.getDeclSpec().hasAutoTypeSpec()) {
13944 // If the placeholder introduces a non-deduced trailing return type,
13945 // we can still delay parsing it.
13946 if (D.getNumTypeObjects()) {
13947 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13948 if (Outer.Kind == DeclaratorChunk::Function &&
13949 Outer.Fun.hasTrailingReturnType()) {
13950 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13951 return Ty.isNull() || !Ty->isUndeducedType();
13952 }
13953 }
13954 return false;
13955 }
13956
13957 return true;
13958}
13959
13960bool Sema::canSkipFunctionBody(Decl *D) {
13961 // We cannot skip the body of a function (or function template) which is
13962 // constexpr, since we may need to evaluate its body in order to parse the
13963 // rest of the file.
13964 // We cannot skip the body of a function with an undeduced return type,
13965 // because any callers of that function need to know the type.
13966 if (const FunctionDecl *FD = D->getAsFunction()) {
13967 if (FD->isConstexpr())
13968 return false;
13969 // We can't simply call Type::isUndeducedType here, because inside template
13970 // auto can be deduced to a dependent type, which is not considered
13971 // "undeduced".
13972 if (FD->getReturnType()->getContainedDeducedType())
13973 return false;
13974 }
13975 return Consumer.shouldSkipFunctionBody(D);
13976}
13977
13978Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13979 if (!Decl)
13980 return nullptr;
13981 if (FunctionDecl *FD = Decl->getAsFunction())
13982 FD->setHasSkippedBody();
13983 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13984 MD->setHasSkippedBody();
13985 return Decl;
13986}
13987
13988Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13989 return ActOnFinishFunctionBody(D, BodyArg, false);
13990}
13991
13992/// RAII object that pops an ExpressionEvaluationContext when exiting a function
13993/// body.
13994class ExitFunctionBodyRAII {
13995public:
13996 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13997 ~ExitFunctionBodyRAII() {
13998 if (!IsLambda)
13999 S.PopExpressionEvaluationContext();
14000 }
14001
14002private:
14003 Sema &S;
14004 bool IsLambda = false;
14005};
14006
14007static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14008 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14009
14010 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14011 if (EscapeInfo.count(BD))
14012 return EscapeInfo[BD];
14013
14014 bool R = false;
14015 const BlockDecl *CurBD = BD;
14016
14017 do {
14018 R = !CurBD->doesNotEscape();
14019 if (R)
14020 break;
14021 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14022 } while (CurBD);
14023
14024 return EscapeInfo[BD] = R;
14025 };
14026
14027 // If the location where 'self' is implicitly retained is inside a escaping
14028 // block, emit a diagnostic.
14029 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14030 S.ImplicitlyRetainedSelfLocs)
14031 if (IsOrNestedInEscapingBlock(P.second))
14032 S.Diag(P.first, diag::warn_implicitly_retains_self)
14033 << FixItHint::CreateInsertion(P.first, "self->");
14034}
14035
14036Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14037 bool IsInstantiation) {
14038 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14039
14040 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14041 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14042
14043 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14044 CheckCompletedCoroutineBody(FD, Body);
14045
14046 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14047 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14048 // meant to pop the context added in ActOnStartOfFunctionDef().
14049 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14050
14051 if (FD) {
14052 FD->setBody(Body);
14053 FD->setWillHaveBody(false);
14054
14055 if (getLangOpts().CPlusPlus14) {
14056 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14057 FD->getReturnType()->isUndeducedType()) {
14058 // If the function has a deduced result type but contains no 'return'
14059 // statements, the result type as written must be exactly 'auto', and
14060 // the deduced result type is 'void'.
14061 if (!FD->getReturnType()->getAs<AutoType>()) {
14062 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14063 << FD->getReturnType();
14064 FD->setInvalidDecl();
14065 } else {
14066 // Substitute 'void' for the 'auto' in the type.
14067 TypeLoc ResultType = getReturnTypeLoc(FD);
14068 Context.adjustDeducedFunctionResultType(
14069 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14070 }
14071 }
14072 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14073 // In C++11, we don't use 'auto' deduction rules for lambda call
14074 // operators because we don't support return type deduction.
14075 auto *LSI = getCurLambda();
14076 if (LSI->HasImplicitReturnType) {
14077 deduceClosureReturnType(*LSI);
14078
14079 // C++11 [expr.prim.lambda]p4:
14080 // [...] if there are no return statements in the compound-statement
14081 // [the deduced type is] the type void
14082 QualType RetType =
14083 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14084
14085 // Update the return type to the deduced type.
14086 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14087 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14088 Proto->getExtProtoInfo()));
14089 }
14090 }
14091
14092 // If the function implicitly returns zero (like 'main') or is naked,
14093 // don't complain about missing return statements.
14094 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14095 WP.disableCheckFallThrough();
14096
14097 // MSVC permits the use of pure specifier (=0) on function definition,
14098 // defined at class scope, warn about this non-standard construct.
14099 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14100 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14101
14102 if (!FD->isInvalidDecl()) {
14103 // Don't diagnose unused parameters of defaulted or deleted functions.
14104 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14105 DiagnoseUnusedParameters(FD->parameters());
14106 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14107 FD->getReturnType(), FD);
14108
14109 // If this is a structor, we need a vtable.
14110 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14111 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14112 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14113 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14114
14115 // Try to apply the named return value optimization. We have to check
14116 // if we can do this here because lambdas keep return statements around
14117 // to deduce an implicit return type.
14118 if (FD->getReturnType()->isRecordType() &&
14119 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14120 computeNRVO(Body, getCurFunction());
14121 }
14122
14123 // GNU warning -Wmissing-prototypes:
14124 // Warn if a global function is defined without a previous
14125 // prototype declaration. This warning is issued even if the
14126 // definition itself provides a prototype. The aim is to detect
14127 // global functions that fail to be declared in header files.
14128 const FunctionDecl *PossiblePrototype = nullptr;
14129 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14130 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14131
14132 if (PossiblePrototype) {
14133 // We found a declaration that is not a prototype,
14134 // but that could be a zero-parameter prototype
14135 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14136 TypeLoc TL = TI->getTypeLoc();
14137 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14138 Diag(PossiblePrototype->getLocation(),
14139 diag::note_declaration_not_a_prototype)
14140 << (FD->getNumParams() != 0)
14141 << (FD->getNumParams() == 0
14142 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14143 : FixItHint{});
14144 }
14145 } else {
14146 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14147 << /* function */ 1
14148 << (FD->getStorageClass() == SC_None
14149 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14150 "static ")
14151 : FixItHint{});
14152 }
14153
14154 // GNU warning -Wstrict-prototypes
14155 // Warn if K&R function is defined without a previous declaration.
14156 // This warning is issued only if the definition itself does not provide
14157 // a prototype. Only K&R definitions do not provide a prototype.
14158 if (!FD->hasWrittenPrototype()) {
14159 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14160 TypeLoc TL = TI->getTypeLoc();
14161 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14162 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14163 }
14164 }
14165
14166 // Warn on CPUDispatch with an actual body.
14167 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14168 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14169 if (!CmpndBody->body_empty())
14170 Diag(CmpndBody->body_front()->getBeginLoc(),
14171 diag::warn_dispatch_body_ignored);
14172
14173 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14174 const CXXMethodDecl *KeyFunction;
14175 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14176 MD->isVirtual() &&
14177 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14178 MD == KeyFunction->getCanonicalDecl()) {
14179 // Update the key-function state if necessary for this ABI.
14180 if (FD->isInlined() &&
14181 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14182 Context.setNonKeyFunction(MD);
14183
14184 // If the newly-chosen key function is already defined, then we
14185 // need to mark the vtable as used retroactively.
14186 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14187 const FunctionDecl *Definition;
14188 if (KeyFunction && KeyFunction->isDefined(Definition))
14189 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14190 } else {
14191 // We just defined they key function; mark the vtable as used.
14192 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14193 }
14194 }
14195 }
14196
14197 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14198, __PRETTY_FUNCTION__))
14198 "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14198, __PRETTY_FUNCTION__))
;
14199 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14200 assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused"
) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14200, __PRETTY_FUNCTION__))
;
14201 MD->setBody(Body);
14202 if (!MD->isInvalidDecl()) {
14203 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14204 MD->getReturnType(), MD);
14205
14206 if (Body)
14207 computeNRVO(Body, getCurFunction());
14208 }
14209 if (getCurFunction()->ObjCShouldCallSuper) {
14210 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14211 << MD->getSelector().getAsString();
14212 getCurFunction()->ObjCShouldCallSuper = false;
14213 }
14214 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14215 const ObjCMethodDecl *InitMethod = nullptr;
14216 bool isDesignated =
14217 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14218 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14218, __PRETTY_FUNCTION__))
;
14219 (void)isDesignated;
14220
14221 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14222 auto IFace = MD->getClassInterface();
14223 if (!IFace)
14224 return false;
14225 auto SuperD = IFace->getSuperClass();
14226 if (!SuperD)
14227 return false;
14228 return SuperD->getIdentifier() ==
14229 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14230 };
14231 // Don't issue this warning for unavailable inits or direct subclasses
14232 // of NSObject.
14233 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14234 Diag(MD->getLocation(),
14235 diag::warn_objc_designated_init_missing_super_call);
14236 Diag(InitMethod->getLocation(),
14237 diag::note_objc_designated_init_marked_here);
14238 }
14239 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14240 }
14241 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14242 // Don't issue this warning for unavaialable inits.
14243 if (!MD->isUnavailable())
14244 Diag(MD->getLocation(),
14245 diag::warn_objc_secondary_init_missing_init_call);
14246 getCurFunction()->ObjCWarnForNoInitDelegation = false;
14247 }
14248
14249 diagnoseImplicitlyRetainedSelf(*this);
14250 } else {
14251 // Parsing the function declaration failed in some way. Pop the fake scope
14252 // we pushed on.
14253 PopFunctionScopeInfo(ActivePolicy, dcl);
14254 return nullptr;
14255 }
14256
14257 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14258 DiagnoseUnguardedAvailabilityViolations(dcl);
14259
14260 assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14262, __PRETTY_FUNCTION__))
14261 "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14262, __PRETTY_FUNCTION__))
14262 "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14262, __PRETTY_FUNCTION__))
;
14263
14264 // Verify and clean out per-function state.
14265 if (Body && (!FD || !FD->isDefaulted())) {
14266 // C++ constructors that have function-try-blocks can't have return
14267 // statements in the handlers of that block. (C++ [except.handle]p14)
14268 // Verify this.
14269 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14270 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14271
14272 // Verify that gotos and switch cases don't jump into scopes illegally.
14273 if (getCurFunction()->NeedsScopeChecking() &&
14274 !PP.isCodeCompletionEnabled())
14275 DiagnoseInvalidJumps(Body);
14276
14277 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14278 if (!Destructor->getParent()->isDependentType())
14279 CheckDestructor(Destructor);
14280
14281 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14282 Destructor->getParent());
14283 }
14284
14285 // If any errors have occurred, clear out any temporaries that may have
14286 // been leftover. This ensures that these temporaries won't be picked up for
14287 // deletion in some later function.
14288 if (getDiagnostics().hasErrorOccurred() ||
14289 getDiagnostics().getSuppressAllDiagnostics()) {
14290 DiscardCleanupsInEvaluationContext();
14291 }
14292 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14293 !isa<FunctionTemplateDecl>(dcl)) {
14294 // Since the body is valid, issue any analysis-based warnings that are
14295 // enabled.
14296 ActivePolicy = &WP;
14297 }
14298
14299 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14300 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14301 FD->setInvalidDecl();
14302
14303 if (FD && FD->hasAttr<NakedAttr>()) {
14304 for (const Stmt *S : Body->children()) {
14305 // Allow local register variables without initializer as they don't
14306 // require prologue.
14307 bool RegisterVariables = false;
14308 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14309 for (const auto *Decl : DS->decls()) {
14310 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14311 RegisterVariables =
14312 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14313 if (!RegisterVariables)
14314 break;
14315 }
14316 }
14317 }
14318 if (RegisterVariables)
14319 continue;
14320 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14321 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14322 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14323 FD->setInvalidDecl();
14324 break;
14325 }
14326 }
14327 }
14328
14329 assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14331, __PRETTY_FUNCTION__))
14330 ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14331, __PRETTY_FUNCTION__))
14331 "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14331, __PRETTY_FUNCTION__))
;
14332 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14332, __PRETTY_FUNCTION__))
;
14333 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14334, __PRETTY_FUNCTION__))
14334 "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14334, __PRETTY_FUNCTION__))
;
14335 }
14336
14337 if (!IsInstantiation)
14338 PopDeclContext();
14339
14340 PopFunctionScopeInfo(ActivePolicy, dcl);
14341 // If any errors have occurred, clear out any temporaries that may have
14342 // been leftover. This ensures that these temporaries won't be picked up for
14343 // deletion in some later function.
14344 if (getDiagnostics().hasErrorOccurred()) {
14345 DiscardCleanupsInEvaluationContext();
14346 }
14347
14348 return dcl;
14349}
14350
14351/// When we finish delayed parsing of an attribute, we must attach it to the
14352/// relevant Decl.
14353void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14354 ParsedAttributes &Attrs) {
14355 // Always attach attributes to the underlying decl.
14356 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14357 D = TD->getTemplatedDecl();
14358 ProcessDeclAttributeList(S, D, Attrs);
14359
14360 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14361 if (Method->isStatic())
14362 checkThisInStaticMemberFunctionAttributes(Method);
14363}
14364
14365/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14366/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14367NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14368 IdentifierInfo &II, Scope *S) {
14369 // Find the scope in which the identifier is injected and the corresponding
14370 // DeclContext.
14371 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14372 // In that case, we inject the declaration into the translation unit scope
14373 // instead.
14374 Scope *BlockScope = S;
14375 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14376 BlockScope = BlockScope->getParent();
14377
14378 Scope *ContextScope = BlockScope;
14379 while (!ContextScope->getEntity())
14380 ContextScope = ContextScope->getParent();
14381 ContextRAII SavedContext(*this, ContextScope->getEntity());
14382
14383 // Before we produce a declaration for an implicitly defined
14384 // function, see whether there was a locally-scoped declaration of
14385 // this name as a function or variable. If so, use that
14386 // (non-visible) declaration, and complain about it.
14387 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14388 if (ExternCPrev) {
14389 // We still need to inject the function into the enclosing block scope so
14390 // that later (non-call) uses can see it.
14391 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14392
14393 // C89 footnote 38:
14394 // If in fact it is not defined as having type "function returning int",
14395 // the behavior is undefined.
14396 if (!isa<FunctionDecl>(ExternCPrev) ||
14397 !Context.typesAreCompatible(
14398 cast<FunctionDecl>(ExternCPrev)->getType(),
14399 Context.getFunctionNoProtoType(Context.IntTy))) {
14400 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14401 << ExternCPrev << !getLangOpts().C99;
14402 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14403 return ExternCPrev;
14404 }
14405 }
14406
14407 // Extension in C99. Legal in C90, but warn about it.
14408 unsigned diag_id;
14409 if (II.getName().startswith("__builtin_"))
14410 diag_id = diag::warn_builtin_unknown;
14411 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14412 else if (getLangOpts().OpenCL)
14413 diag_id = diag::err_opencl_implicit_function_decl;
14414 else if (getLangOpts().C99)
14415 diag_id = diag::ext_implicit_function_decl;
14416 else
14417 diag_id = diag::warn_implicit_function_decl;
14418 Diag(Loc, diag_id) << &II;
14419
14420 // If we found a prior declaration of this function, don't bother building
14421 // another one. We've already pushed that one into scope, so there's nothing
14422 // more to do.
14423 if (ExternCPrev)
14424 return ExternCPrev;
14425
14426 // Because typo correction is expensive, only do it if the implicit
14427 // function declaration is going to be treated as an error.
14428 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14429 TypoCorrection Corrected;
14430 DeclFilterCCC<FunctionDecl> CCC{};
14431 if (S && (Corrected =
14432 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14433 S, nullptr, CCC, CTK_NonError)))
14434 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14435 /*ErrorRecovery*/false);
14436 }
14437
14438 // Set a Declarator for the implicit definition: int foo();
14439 const char *Dummy;
14440 AttributeFactory attrFactory;
14441 DeclSpec DS(attrFactory);
14442 unsigned DiagID;
14443 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14444 Context.getPrintingPolicy());
14445 (void)Error; // Silence warning.
14446 assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast
<void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14446, __PRETTY_FUNCTION__))
;
14447 SourceLocation NoLoc;
14448 Declarator D(DS, DeclaratorContext::BlockContext);
14449 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14450 /*IsAmbiguous=*/false,
14451 /*LParenLoc=*/NoLoc,
14452 /*Params=*/nullptr,
14453 /*NumParams=*/0,
14454 /*EllipsisLoc=*/NoLoc,
14455 /*RParenLoc=*/NoLoc,
14456 /*RefQualifierIsLvalueRef=*/true,
14457 /*RefQualifierLoc=*/NoLoc,
14458 /*MutableLoc=*/NoLoc, EST_None,
14459 /*ESpecRange=*/SourceRange(),
14460 /*Exceptions=*/nullptr,
14461 /*ExceptionRanges=*/nullptr,
14462 /*NumExceptions=*/0,
14463 /*NoexceptExpr=*/nullptr,
14464 /*ExceptionSpecTokens=*/nullptr,
14465 /*DeclsInPrototype=*/None, Loc,
14466 Loc, D),
14467 std::move(DS.getAttributes()), SourceLocation());
14468 D.SetIdentifier(&II, Loc);
14469
14470 // Insert this function into the enclosing block scope.
14471 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14472 FD->setImplicit();
14473
14474 AddKnownFunctionAttributes(FD);
14475
14476 return FD;
14477}
14478
14479/// If this function is a C++ replaceable global allocation function
14480/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14481/// adds any function attributes that we know a priori based on the standard.
14482///
14483/// We need to check for duplicate attributes both here and where user-written
14484/// attributes are applied to declarations.
14485void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14486 FunctionDecl *FD) {
14487 if (FD->isInvalidDecl())
14488 return;
14489
14490 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14491 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14492 return;
14493
14494 Optional<unsigned> AlignmentParam;
14495 bool IsNothrow = false;
14496 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14497 return;
14498
14499 // C++2a [basic.stc.dynamic.allocation]p4:
14500 // An allocation function that has a non-throwing exception specification
14501 // indicates failure by returning a null pointer value. Any other allocation
14502 // function never returns a null pointer value and indicates failure only by
14503 // throwing an exception [...]
14504 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14505 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14506
14507 // C++2a [basic.stc.dynamic.allocation]p2:
14508 // An allocation function attempts to allocate the requested amount of
14509 // storage. [...] If the request succeeds, the value returned by a
14510 // replaceable allocation function is a [...] pointer value p0 different
14511 // from any previously returned value p1 [...]
14512 //
14513 // However, this particular information is being added in codegen,
14514 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14515
14516 // C++2a [basic.stc.dynamic.allocation]p2:
14517 // An allocation function attempts to allocate the requested amount of
14518 // storage. If it is successful, it returns the address of the start of a
14519 // block of storage whose length in bytes is at least as large as the
14520 // requested size.
14521 if (!FD->hasAttr<AllocSizeAttr>()) {
14522 FD->addAttr(AllocSizeAttr::CreateImplicit(
14523 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14524 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14525 }
14526
14527 // C++2a [basic.stc.dynamic.allocation]p3:
14528 // For an allocation function [...], the pointer returned on a successful
14529 // call shall represent the address of storage that is aligned as follows:
14530 // (3.1) If the allocation function takes an argument of type
14531 // std​::​align_­val_­t, the storage will have the alignment
14532 // specified by the value of this argument.
14533 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14534 FD->addAttr(AllocAlignAttr::CreateImplicit(
14535 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14536 }
14537
14538 // FIXME:
14539 // C++2a [basic.stc.dynamic.allocation]p3:
14540 // For an allocation function [...], the pointer returned on a successful
14541 // call shall represent the address of storage that is aligned as follows:
14542 // (3.2) Otherwise, if the allocation function is named operator new[],
14543 // the storage is aligned for any object that does not have
14544 // new-extended alignment ([basic.align]) and is no larger than the
14545 // requested size.
14546 // (3.3) Otherwise, the storage is aligned for any object that does not
14547 // have new-extended alignment and is of the requested size.
14548}
14549
14550/// Adds any function attributes that we know a priori based on
14551/// the declaration of this function.
14552///
14553/// These attributes can apply both to implicitly-declared builtins
14554/// (like __builtin___printf_chk) or to library-declared functions
14555/// like NSLog or printf.
14556///
14557/// We need to check for duplicate attributes both here and where user-written
14558/// attributes are applied to declarations.
14559void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14560 if (FD->isInvalidDecl())
14561 return;
14562
14563 // If this is a built-in function, map its builtin attributes to
14564 // actual attributes.
14565 if (unsigned BuiltinID = FD->getBuiltinID()) {
14566 // Handle printf-formatting attributes.
14567 unsigned FormatIdx;
14568 bool HasVAListArg;
14569 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14570 if (!FD->hasAttr<FormatAttr>()) {
14571 const char *fmt = "printf";
14572 unsigned int NumParams = FD->getNumParams();
14573 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14574 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14575 fmt = "NSString";
14576 FD->addAttr(FormatAttr::CreateImplicit(Context,
14577 &Context.Idents.get(fmt),
14578 FormatIdx+1,
14579 HasVAListArg ? 0 : FormatIdx+2,
14580 FD->getLocation()));
14581 }
14582 }
14583 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14584 HasVAListArg)) {
14585 if (!FD->hasAttr<FormatAttr>())
14586 FD->addAttr(FormatAttr::CreateImplicit(Context,
14587 &Context.Idents.get("scanf"),
14588 FormatIdx+1,
14589 HasVAListArg ? 0 : FormatIdx+2,
14590 FD->getLocation()));
14591 }
14592
14593 // Handle automatically recognized callbacks.
14594 SmallVector<int, 4> Encoding;
14595 if (!FD->hasAttr<CallbackAttr>() &&
14596 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14597 FD->addAttr(CallbackAttr::CreateImplicit(
14598 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14599
14600 // Mark const if we don't care about errno and that is the only thing
14601 // preventing the function from being const. This allows IRgen to use LLVM
14602 // intrinsics for such functions.
14603 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14604 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14605 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14606
14607 // We make "fma" on some platforms const because we know it does not set
14608 // errno in those environments even though it could set errno based on the
14609 // C standard.
14610 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14611 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14612 !FD->hasAttr<ConstAttr>()) {
14613 switch (BuiltinID) {
14614 case Builtin::BI__builtin_fma:
14615 case Builtin::BI__builtin_fmaf:
14616 case Builtin::BI__builtin_fmal:
14617 case Builtin::BIfma:
14618 case Builtin::BIfmaf:
14619 case Builtin::BIfmal:
14620 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14621 break;
14622 default:
14623 break;
14624 }
14625 }
14626
14627 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14628 !FD->hasAttr<ReturnsTwiceAttr>())
14629 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14630 FD->getLocation()));
14631 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14632 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14633 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14634 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14635 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14636 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14637 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14638 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14639 // Add the appropriate attribute, depending on the CUDA compilation mode
14640 // and which target the builtin belongs to. For example, during host
14641 // compilation, aux builtins are __device__, while the rest are __host__.
14642 if (getLangOpts().CUDAIsDevice !=
14643 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14644 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14645 else
14646 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14647 }
14648 }
14649
14650 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14651
14652 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14653 // throw, add an implicit nothrow attribute to any extern "C" function we come
14654 // across.
14655 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14656 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14657 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14658 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14659 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14660 }
14661
14662 IdentifierInfo *Name = FD->getIdentifier();
14663 if (!Name)
14664 return;
14665 if ((!getLangOpts().CPlusPlus &&
14666 FD->getDeclContext()->isTranslationUnit()) ||
14667 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14668 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14669 LinkageSpecDecl::lang_c)) {
14670 // Okay: this could be a libc/libm/Objective-C function we know
14671 // about.
14672 } else
14673 return;
14674
14675 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14676 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14677 // target-specific builtins, perhaps?
14678 if (!FD->hasAttr<FormatAttr>())
14679 FD->addAttr(FormatAttr::CreateImplicit(Context,
14680 &Context.Idents.get("printf"), 2,
14681 Name->isStr("vasprintf") ? 0 : 3,
14682 FD->getLocation()));
14683 }
14684
14685 if (Name->isStr("__CFStringMakeConstantString")) {
14686 // We already have a __builtin___CFStringMakeConstantString,
14687 // but builds that use -fno-constant-cfstrings don't go through that.
14688 if (!FD->hasAttr<FormatArgAttr>())
14689 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14690 FD->getLocation()));
14691 }
14692}
14693
14694TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14695 TypeSourceInfo *TInfo) {
14696 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14696, __PRETTY_FUNCTION__))
;
14697 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14697, __PRETTY_FUNCTION__))
;
14698
14699 if (!TInfo) {
14700 assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type"
) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14700, __PRETTY_FUNCTION__))
;
14701 TInfo = Context.getTrivialTypeSourceInfo(T);
14702 }
14703
14704 // Scope manipulation handled by caller.
14705 TypedefDecl *NewTD =
14706 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14707 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14708
14709 // Bail out immediately if we have an invalid declaration.
14710 if (D.isInvalidType()) {
14711 NewTD->setInvalidDecl();
14712 return NewTD;
14713 }
14714
14715 if (D.getDeclSpec().isModulePrivateSpecified()) {
14716 if (CurContext->isFunctionOrMethod())
14717 Diag(NewTD->getLocation(), diag::err_module_private_local)
14718 << 2 << NewTD->getDeclName()
14719 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14720 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14721 else
14722 NewTD->setModulePrivate();
14723 }
14724
14725 // C++ [dcl.typedef]p8:
14726 // If the typedef declaration defines an unnamed class (or
14727 // enum), the first typedef-name declared by the declaration
14728 // to be that class type (or enum type) is used to denote the
14729 // class type (or enum type) for linkage purposes only.
14730 // We need to check whether the type was declared in the declaration.
14731 switch (D.getDeclSpec().getTypeSpecType()) {
14732 case TST_enum:
14733 case TST_struct:
14734 case TST_interface:
14735 case TST_union:
14736 case TST_class: {
14737 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14738 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14739 break;
14740 }
14741
14742 default:
14743 break;
14744 }
14745
14746 return NewTD;
14747}
14748
14749/// Check that this is a valid underlying type for an enum declaration.
14750bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14751 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14752 QualType T = TI->getType();
14753
14754 if (T->isDependentType())
14755 return false;
14756
14757 if (const BuiltinType *BT = T->getAs<BuiltinType>())
14758 if (BT->isInteger())
14759 return false;
14760
14761 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14762 return true;
14763}
14764
14765/// Check whether this is a valid redeclaration of a previous enumeration.
14766/// \return true if the redeclaration was invalid.
14767bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14768 QualType EnumUnderlyingTy, bool IsFixed,
14769 const EnumDecl *Prev) {
14770 if (IsScoped != Prev->isScoped()) {
14771 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14772 << Prev->isScoped();
14773 Diag(Prev->getLocation(), diag::note_previous_declaration);
14774 return true;
14775 }
14776
14777 if (IsFixed && Prev->isFixed()) {
14778 if (!EnumUnderlyingTy->isDependentType() &&
14779 !Prev->getIntegerType()->isDependentType() &&
14780 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14781 Prev->getIntegerType())) {
14782 // TODO: Highlight the underlying type of the redeclaration.
14783 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14784 << EnumUnderlyingTy << Prev->getIntegerType();
14785 Diag(Prev->getLocation(), diag::note_previous_declaration)
14786 << Prev->getIntegerTypeRange();
14787 return true;
14788 }
14789 } else if (IsFixed != Prev->isFixed()) {
14790 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14791 << Prev->isFixed();
14792 Diag(Prev->getLocation(), diag::note_previous_declaration);
14793 return true;
14794 }
14795
14796 return false;
14797}
14798
14799/// Get diagnostic %select index for tag kind for
14800/// redeclaration diagnostic message.
14801/// WARNING: Indexes apply to particular diagnostics only!
14802///
14803/// \returns diagnostic %select index.
14804static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14805 switch (Tag) {
14806 case TTK_Struct: return 0;
14807 case TTK_Interface: return 1;
14808 case TTK_Class: return 2;
14809 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14809)
;
14810 }
14811}
14812
14813/// Determine if tag kind is a class-key compatible with
14814/// class for redeclaration (class, struct, or __interface).
14815///
14816/// \returns true iff the tag kind is compatible.
14817static bool isClassCompatTagKind(TagTypeKind Tag)
14818{
14819 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14820}
14821
14822Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14823 TagTypeKind TTK) {
14824 if (isa<TypedefDecl>(PrevDecl))
14825 return NTK_Typedef;
14826 else if (isa<TypeAliasDecl>(PrevDecl))
14827 return NTK_TypeAlias;
14828 else if (isa<ClassTemplateDecl>(PrevDecl))
14829 return NTK_Template;
14830 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14831 return NTK_TypeAliasTemplate;
14832 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14833 return NTK_TemplateTemplateArgument;
14834 switch (TTK) {
14835 case TTK_Struct:
14836 case TTK_Interface:
14837 case TTK_Class:
14838 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14839 case TTK_Union:
14840 return NTK_NonUnion;
14841 case TTK_Enum:
14842 return NTK_NonEnum;
14843 }
14844 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 14844)
;
14845}
14846
14847/// Determine whether a tag with a given kind is acceptable
14848/// as a redeclaration of the given tag declaration.
14849///
14850/// \returns true if the new tag kind is acceptable, false otherwise.
14851bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14852 TagTypeKind NewTag, bool isDefinition,
14853 SourceLocation NewTagLoc,
14854 const IdentifierInfo *Name) {
14855 // C++ [dcl.type.elab]p3:
14856 // The class-key or enum keyword present in the
14857 // elaborated-type-specifier shall agree in kind with the
14858 // declaration to which the name in the elaborated-type-specifier
14859 // refers. This rule also applies to the form of
14860 // elaborated-type-specifier that declares a class-name or
14861 // friend class since it can be construed as referring to the
14862 // definition of the class. Thus, in any
14863 // elaborated-type-specifier, the enum keyword shall be used to
14864 // refer to an enumeration (7.2), the union class-key shall be
14865 // used to refer to a union (clause 9), and either the class or
14866 // struct class-key shall be used to refer to a class (clause 9)
14867 // declared using the class or struct class-key.
14868 TagTypeKind OldTag = Previous->getTagKind();
14869 if (OldTag != NewTag &&
14870 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14871 return false;
14872
14873 // Tags are compatible, but we might still want to warn on mismatched tags.
14874 // Non-class tags can't be mismatched at this point.
14875 if (!isClassCompatTagKind(NewTag))
14876 return true;
14877
14878 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14879 // by our warning analysis. We don't want to warn about mismatches with (eg)
14880 // declarations in system headers that are designed to be specialized, but if
14881 // a user asks us to warn, we should warn if their code contains mismatched
14882 // declarations.
14883 auto IsIgnoredLoc = [&](SourceLocation Loc) {
14884 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14885 Loc);
14886 };
14887 if (IsIgnoredLoc(NewTagLoc))
14888 return true;
14889
14890 auto IsIgnored = [&](const TagDecl *Tag) {
14891 return IsIgnoredLoc(Tag->getLocation());
14892 };
14893 while (IsIgnored(Previous)) {
14894 Previous = Previous->getPreviousDecl();
14895 if (!Previous)
14896 return true;
14897 OldTag = Previous->getTagKind();
14898 }
14899
14900 bool isTemplate = false;
14901 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14902 isTemplate = Record->getDescribedClassTemplate();
14903
14904 if (inTemplateInstantiation()) {
14905 if (OldTag != NewTag) {
14906 // In a template instantiation, do not offer fix-its for tag mismatches
14907 // since they usually mess up the template instead of fixing the problem.
14908 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14909 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14910 << getRedeclDiagFromTagKind(OldTag);
14911 // FIXME: Note previous location?
14912 }
14913 return true;
14914 }
14915
14916 if (isDefinition) {
14917 // On definitions, check all previous tags and issue a fix-it for each
14918 // one that doesn't match the current tag.
14919 if (Previous->getDefinition()) {
14920 // Don't suggest fix-its for redefinitions.
14921 return true;
14922 }
14923
14924 bool previousMismatch = false;
14925 for (const TagDecl *I : Previous->redecls()) {
14926 if (I->getTagKind() != NewTag) {
14927 // Ignore previous declarations for which the warning was disabled.
14928 if (IsIgnored(I))
14929 continue;
14930
14931 if (!previousMismatch) {
14932 previousMismatch = true;
14933 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14934 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14935 << getRedeclDiagFromTagKind(I->getTagKind());
14936 }
14937 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14938 << getRedeclDiagFromTagKind(NewTag)
14939 << FixItHint::CreateReplacement(I->getInnerLocStart(),
14940 TypeWithKeyword::getTagTypeKindName(NewTag));
14941 }
14942 }
14943 return true;
14944 }
14945
14946 // Identify the prevailing tag kind: this is the kind of the definition (if
14947 // there is a non-ignored definition), or otherwise the kind of the prior
14948 // (non-ignored) declaration.
14949 const TagDecl *PrevDef = Previous->getDefinition();
14950 if (PrevDef && IsIgnored(PrevDef))
14951 PrevDef = nullptr;
14952 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14953 if (Redecl->getTagKind() != NewTag) {
14954 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14955 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14956 << getRedeclDiagFromTagKind(OldTag);
14957 Diag(Redecl->getLocation(), diag::note_previous_use);
14958
14959 // If there is a previous definition, suggest a fix-it.
14960 if (PrevDef) {
14961 Diag(NewTagLoc, diag::note_struct_class_suggestion)
14962 << getRedeclDiagFromTagKind(Redecl->getTagKind())
14963 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14964 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14965 }
14966 }
14967
14968 return true;
14969}
14970
14971/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14972/// from an outer enclosing namespace or file scope inside a friend declaration.
14973/// This should provide the commented out code in the following snippet:
14974/// namespace N {
14975/// struct X;
14976/// namespace M {
14977/// struct Y { friend struct /*N::*/ X; };
14978/// }
14979/// }
14980static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14981 SourceLocation NameLoc) {
14982 // While the decl is in a namespace, do repeated lookup of that name and see
14983 // if we get the same namespace back. If we do not, continue until
14984 // translation unit scope, at which point we have a fully qualified NNS.
14985 SmallVector<IdentifierInfo *, 4> Namespaces;
14986 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14987 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14988 // This tag should be declared in a namespace, which can only be enclosed by
14989 // other namespaces. Bail if there's an anonymous namespace in the chain.
14990 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14991 if (!Namespace || Namespace->isAnonymousNamespace())
14992 return FixItHint();
14993 IdentifierInfo *II = Namespace->getIdentifier();
14994 Namespaces.push_back(II);
14995 NamedDecl *Lookup = SemaRef.LookupSingleName(
14996 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14997 if (Lookup == Namespace)
14998 break;
14999 }
15000
15001 // Once we have all the namespaces, reverse them to go outermost first, and
15002 // build an NNS.
15003 SmallString<64> Insertion;
15004 llvm::raw_svector_ostream OS(Insertion);
15005 if (DC->isTranslationUnit())
15006 OS << "::";
15007 std::reverse(Namespaces.begin(), Namespaces.end());
15008 for (auto *II : Namespaces)
15009 OS << II->getName() << "::";
15010 return FixItHint::CreateInsertion(NameLoc, Insertion);
15011}
15012
15013/// Determine whether a tag originally declared in context \p OldDC can
15014/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15015/// found a declaration in \p OldDC as a previous decl, perhaps through a
15016/// using-declaration).
15017static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15018 DeclContext *NewDC) {
15019 OldDC = OldDC->getRedeclContext();
15020 NewDC = NewDC->getRedeclContext();
15021
15022 if (OldDC->Equals(NewDC))
15023 return true;
15024
15025 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15026 // encloses the other).
15027 if (S.getLangOpts().MSVCCompat &&
15028 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15029 return true;
15030
15031 return false;
15032}
15033
15034/// This is invoked when we see 'struct foo' or 'struct {'. In the
15035/// former case, Name will be non-null. In the later case, Name will be null.
15036/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15037/// reference/declaration/definition of a tag.
15038///
15039/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15040/// trailing-type-specifier) other than one in an alias-declaration.
15041///
15042/// \param SkipBody If non-null, will be set to indicate if the caller should
15043/// skip the definition of this tag and treat it as if it were a declaration.
15044Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15045 SourceLocation KWLoc, CXXScopeSpec &SS,
15046 IdentifierInfo *Name, SourceLocation NameLoc,
15047 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15048 SourceLocation ModulePrivateLoc,
15049 MultiTemplateParamsArg TemplateParameterLists,
15050 bool &OwnedDecl, bool &IsDependent,
15051 SourceLocation ScopedEnumKWLoc,
15052 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15053 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15054 SkipBodyInfo *SkipBody) {
15055 // If this is not a definition, it must have a name.
15056 IdentifierInfo *OrigName = Name;
15057 assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15058, __PRETTY_FUNCTION__))
15058 "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15058, __PRETTY_FUNCTION__))
;
15059 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference)
? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15059, __PRETTY_FUNCTION__))
;
15060
15061 OwnedDecl = false;
15062 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15063 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15064
15065 // FIXME: Check member specializations more carefully.
15066 bool isMemberSpecialization = false;
15067 bool Invalid = false;
15068
15069 // We only need to do this matching if we have template parameters
15070 // or a scope specifier, which also conveniently avoids this work
15071 // for non-C++ cases.
15072 if (TemplateParameterLists.size() > 0 ||
15073 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15074 if (TemplateParameterList *TemplateParams =
15075 MatchTemplateParametersToScopeSpecifier(
15076 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15077 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15078 if (Kind == TTK_Enum) {
15079 Diag(KWLoc, diag::err_enum_template);
15080 return nullptr;
15081 }
15082
15083 if (TemplateParams->size() > 0) {
15084 // This is a declaration or definition of a class template (which may
15085 // be a member of another template).
15086
15087 if (Invalid)
15088 return nullptr;
15089
15090 OwnedDecl = false;
15091 DeclResult Result = CheckClassTemplate(
15092 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15093 AS, ModulePrivateLoc,
15094 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15095 TemplateParameterLists.data(), SkipBody);
15096 return Result.get();
15097 } else {
15098 // The "template<>" header is extraneous.
15099 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15100 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15101 isMemberSpecialization = true;
15102 }
15103 }
15104 }
15105
15106 // Figure out the underlying type if this a enum declaration. We need to do
15107 // this early, because it's needed to detect if this is an incompatible
15108 // redeclaration.
15109 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15110 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15111
15112 if (Kind == TTK_Enum) {
15113 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15114 // No underlying type explicitly specified, or we failed to parse the
15115 // type, default to int.
15116 EnumUnderlying = Context.IntTy.getTypePtr();
15117 } else if (UnderlyingType.get()) {
15118 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15119 // integral type; any cv-qualification is ignored.
15120 TypeSourceInfo *TI = nullptr;
15121 GetTypeFromParser(UnderlyingType.get(), &TI);
15122 EnumUnderlying = TI;
15123
15124 if (CheckEnumUnderlyingType(TI))
15125 // Recover by falling back to int.
15126 EnumUnderlying = Context.IntTy.getTypePtr();
15127
15128 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15129 UPPC_FixedUnderlyingType))
15130 EnumUnderlying = Context.IntTy.getTypePtr();
15131
15132 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15133 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15134 // of 'int'. However, if this is an unfixed forward declaration, don't set
15135 // the underlying type unless the user enables -fms-compatibility. This
15136 // makes unfixed forward declared enums incomplete and is more conforming.
15137 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15138 EnumUnderlying = Context.IntTy.getTypePtr();
15139 }
15140 }
15141
15142 DeclContext *SearchDC = CurContext;
15143 DeclContext *DC = CurContext;
15144 bool isStdBadAlloc = false;
15145 bool isStdAlignValT = false;
15146
15147 RedeclarationKind Redecl = forRedeclarationInCurContext();
15148 if (TUK == TUK_Friend || TUK == TUK_Reference)
15149 Redecl = NotForRedeclaration;
15150
15151 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15152 /// implemented asks for structural equivalence checking, the returned decl
15153 /// here is passed back to the parser, allowing the tag body to be parsed.
15154 auto createTagFromNewDecl = [&]() -> TagDecl * {
15155 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage"
) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15155, __PRETTY_FUNCTION__))
;
15156 // If there is an identifier, use the location of the identifier as the
15157 // location of the decl, otherwise use the location of the struct/union
15158 // keyword.
15159 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15160 TagDecl *New = nullptr;
15161
15162 if (Kind == TTK_Enum) {
15163 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15164 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15165 // If this is an undefined enum, bail.
15166 if (TUK != TUK_Definition && !Invalid)
15167 return nullptr;
15168 if (EnumUnderlying) {
15169 EnumDecl *ED = cast<EnumDecl>(New);
15170 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15171 ED->setIntegerTypeSourceInfo(TI);
15172 else
15173 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15174 ED->setPromotionType(ED->getIntegerType());
15175 }
15176 } else { // struct/union
15177 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15178 nullptr);
15179 }
15180
15181 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15182 // Add alignment attributes if necessary; these attributes are checked
15183 // when the ASTContext lays out the structure.
15184 //
15185 // It is important for implementing the correct semantics that this
15186 // happen here (in ActOnTag). The #pragma pack stack is
15187 // maintained as a result of parser callbacks which can occur at
15188 // many points during the parsing of a struct declaration (because
15189 // the #pragma tokens are effectively skipped over during the
15190 // parsing of the struct).
15191 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15192 AddAlignmentAttributesForRecord(RD);
15193 AddMsStructLayoutForRecord(RD);
15194 }
15195 }
15196 New->setLexicalDeclContext(CurContext);
15197 return New;
15198 };
15199
15200 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15201 if (Name && SS.isNotEmpty()) {
15202 // We have a nested-name tag ('struct foo::bar').
15203
15204 // Check for invalid 'foo::'.
15205 if (SS.isInvalid()) {
15206 Name = nullptr;
15207 goto CreateNewDecl;
15208 }
15209
15210 // If this is a friend or a reference to a class in a dependent
15211 // context, don't try to make a decl for it.
15212 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15213 DC = computeDeclContext(SS, false);
15214 if (!DC) {
15215 IsDependent = true;
15216 return nullptr;
15217 }
15218 } else {
15219 DC = computeDeclContext(SS, true);
15220 if (!DC) {
15221 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15222 << SS.getRange();
15223 return nullptr;
15224 }
15225 }
15226
15227 if (RequireCompleteDeclContext(SS, DC))
15228 return nullptr;
15229
15230 SearchDC = DC;
15231 // Look-up name inside 'foo::'.
15232 LookupQualifiedName(Previous, DC);
15233
15234 if (Previous.isAmbiguous())
15235 return nullptr;
15236
15237 if (Previous.empty()) {
15238 // Name lookup did not find anything. However, if the
15239 // nested-name-specifier refers to the current instantiation,
15240 // and that current instantiation has any dependent base
15241 // classes, we might find something at instantiation time: treat
15242 // this as a dependent elaborated-type-specifier.
15243 // But this only makes any sense for reference-like lookups.
15244 if (Previous.wasNotFoundInCurrentInstantiation() &&
15245 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15246 IsDependent = true;
15247 return nullptr;
15248 }
15249
15250 // A tag 'foo::bar' must already exist.
15251 Diag(NameLoc, diag::err_not_tag_in_scope)
15252 << Kind << Name << DC << SS.getRange();
15253 Name = nullptr;
15254 Invalid = true;
15255 goto CreateNewDecl;
15256 }
15257 } else if (Name) {
15258 // C++14 [class.mem]p14:
15259 // If T is the name of a class, then each of the following shall have a
15260 // name different from T:
15261 // -- every member of class T that is itself a type
15262 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15263 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15264 return nullptr;
15265
15266 // If this is a named struct, check to see if there was a previous forward
15267 // declaration or definition.
15268 // FIXME: We're looking into outer scopes here, even when we
15269 // shouldn't be. Doing so can result in ambiguities that we
15270 // shouldn't be diagnosing.
15271 LookupName(Previous, S);
15272
15273 // When declaring or defining a tag, ignore ambiguities introduced
15274 // by types using'ed into this scope.
15275 if (Previous.isAmbiguous() &&
15276 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15277 LookupResult::Filter F = Previous.makeFilter();
15278 while (F.hasNext()) {
15279 NamedDecl *ND = F.next();
15280 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15281 SearchDC->getRedeclContext()))
15282 F.erase();
15283 }
15284 F.done();
15285 }
15286
15287 // C++11 [namespace.memdef]p3:
15288 // If the name in a friend declaration is neither qualified nor
15289 // a template-id and the declaration is a function or an
15290 // elaborated-type-specifier, the lookup to determine whether
15291 // the entity has been previously declared shall not consider
15292 // any scopes outside the innermost enclosing namespace.
15293 //
15294 // MSVC doesn't implement the above rule for types, so a friend tag
15295 // declaration may be a redeclaration of a type declared in an enclosing
15296 // scope. They do implement this rule for friend functions.
15297 //
15298 // Does it matter that this should be by scope instead of by
15299 // semantic context?
15300 if (!Previous.empty() && TUK == TUK_Friend) {
15301 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15302 LookupResult::Filter F = Previous.makeFilter();
15303 bool FriendSawTagOutsideEnclosingNamespace = false;
15304 while (F.hasNext()) {
15305 NamedDecl *ND = F.next();
15306 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15307 if (DC->isFileContext() &&
15308 !EnclosingNS->Encloses(ND->getDeclContext())) {
15309 if (getLangOpts().MSVCCompat)
15310 FriendSawTagOutsideEnclosingNamespace = true;
15311 else
15312 F.erase();
15313 }
15314 }
15315 F.done();
15316
15317 // Diagnose this MSVC extension in the easy case where lookup would have
15318 // unambiguously found something outside the enclosing namespace.
15319 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15320 NamedDecl *ND = Previous.getFoundDecl();
15321 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15322 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15323 }
15324 }
15325
15326 // Note: there used to be some attempt at recovery here.
15327 if (Previous.isAmbiguous())
15328 return nullptr;
15329
15330 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15331 // FIXME: This makes sure that we ignore the contexts associated
15332 // with C structs, unions, and enums when looking for a matching
15333 // tag declaration or definition. See the similar lookup tweak
15334 // in Sema::LookupName; is there a better way to deal with this?
15335 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15336 SearchDC = SearchDC->getParent();
15337 }
15338 }
15339
15340 if (Previous.isSingleResult() &&
15341 Previous.getFoundDecl()->isTemplateParameter()) {
15342 // Maybe we will complain about the shadowed template parameter.
15343 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15344 // Just pretend that we didn't see the previous declaration.
15345 Previous.clear();
15346 }
15347
15348 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15349 DC->Equals(getStdNamespace())) {
15350 if (Name->isStr("bad_alloc")) {
15351 // This is a declaration of or a reference to "std::bad_alloc".
15352 isStdBadAlloc = true;
15353
15354 // If std::bad_alloc has been implicitly declared (but made invisible to
15355 // name lookup), fill in this implicit declaration as the previous
15356 // declaration, so that the declarations get chained appropriately.
15357 if (Previous.empty() && StdBadAlloc)
15358 Previous.addDecl(getStdBadAlloc());
15359 } else if (Name->isStr("align_val_t")) {
15360 isStdAlignValT = true;
15361 if (Previous.empty() && StdAlignValT)
15362 Previous.addDecl(getStdAlignValT());
15363 }
15364 }
15365
15366 // If we didn't find a previous declaration, and this is a reference
15367 // (or friend reference), move to the correct scope. In C++, we
15368 // also need to do a redeclaration lookup there, just in case
15369 // there's a shadow friend decl.
15370 if (Name && Previous.empty() &&
15371 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15372 if (Invalid) goto CreateNewDecl;
15373 assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15373, __PRETTY_FUNCTION__))
;
15374
15375 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15376 // C++ [basic.scope.pdecl]p5:
15377 // -- for an elaborated-type-specifier of the form
15378 //
15379 // class-key identifier
15380 //
15381 // if the elaborated-type-specifier is used in the
15382 // decl-specifier-seq or parameter-declaration-clause of a
15383 // function defined in namespace scope, the identifier is
15384 // declared as a class-name in the namespace that contains
15385 // the declaration; otherwise, except as a friend
15386 // declaration, the identifier is declared in the smallest
15387 // non-class, non-function-prototype scope that contains the
15388 // declaration.
15389 //
15390 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15391 // C structs and unions.
15392 //
15393 // It is an error in C++ to declare (rather than define) an enum
15394 // type, including via an elaborated type specifier. We'll
15395 // diagnose that later; for now, declare the enum in the same
15396 // scope as we would have picked for any other tag type.
15397 //
15398 // GNU C also supports this behavior as part of its incomplete
15399 // enum types extension, while GNU C++ does not.
15400 //
15401 // Find the context where we'll be declaring the tag.
15402 // FIXME: We would like to maintain the current DeclContext as the
15403 // lexical context,
15404 SearchDC = getTagInjectionContext(SearchDC);
15405
15406 // Find the scope where we'll be declaring the tag.
15407 S = getTagInjectionScope(S, getLangOpts());
15408 } else {
15409 assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15409, __PRETTY_FUNCTION__))
;
15410 // C++ [namespace.memdef]p3:
15411 // If a friend declaration in a non-local class first declares a
15412 // class or function, the friend class or function is a member of
15413 // the innermost enclosing namespace.
15414 SearchDC = SearchDC->getEnclosingNamespaceContext();
15415 }
15416
15417 // In C++, we need to do a redeclaration lookup to properly
15418 // diagnose some problems.
15419 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15420 // hidden declaration so that we don't get ambiguity errors when using a
15421 // type declared by an elaborated-type-specifier. In C that is not correct
15422 // and we should instead merge compatible types found by lookup.
15423 if (getLangOpts().CPlusPlus) {
15424 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15425 LookupQualifiedName(Previous, SearchDC);
15426 } else {
15427 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15428 LookupName(Previous, S);
15429 }
15430 }
15431
15432 // If we have a known previous declaration to use, then use it.
15433 if (Previous.empty() && SkipBody && SkipBody->Previous)
15434 Previous.addDecl(SkipBody->Previous);
15435
15436 if (!Previous.empty()) {
15437 NamedDecl *PrevDecl = Previous.getFoundDecl();
15438 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15439
15440 // It's okay to have a tag decl in the same scope as a typedef
15441 // which hides a tag decl in the same scope. Finding this
15442 // insanity with a redeclaration lookup can only actually happen
15443 // in C++.
15444 //
15445 // This is also okay for elaborated-type-specifiers, which is
15446 // technically forbidden by the current standard but which is
15447 // okay according to the likely resolution of an open issue;
15448 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15449 if (getLangOpts().CPlusPlus) {
15450 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15451 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15452 TagDecl *Tag = TT->getDecl();
15453 if (Tag->getDeclName() == Name &&
15454 Tag->getDeclContext()->getRedeclContext()
15455 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15456 PrevDecl = Tag;
15457 Previous.clear();
15458 Previous.addDecl(Tag);
15459 Previous.resolveKind();
15460 }
15461 }
15462 }
15463 }
15464
15465 // If this is a redeclaration of a using shadow declaration, it must
15466 // declare a tag in the same context. In MSVC mode, we allow a
15467 // redefinition if either context is within the other.
15468 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15469 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15470 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15471 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15472 !(OldTag && isAcceptableTagRedeclContext(
15473 *this, OldTag->getDeclContext(), SearchDC))) {
15474 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15475 Diag(Shadow->getTargetDecl()->getLocation(),
15476 diag::note_using_decl_target);
15477 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15478 << 0;
15479 // Recover by ignoring the old declaration.
15480 Previous.clear();
15481 goto CreateNewDecl;
15482 }
15483 }
15484
15485 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15486 // If this is a use of a previous tag, or if the tag is already declared
15487 // in the same scope (so that the definition/declaration completes or
15488 // rementions the tag), reuse the decl.
15489 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15490 isDeclInScope(DirectPrevDecl, SearchDC, S,
15491 SS.isNotEmpty() || isMemberSpecialization)) {
15492 // Make sure that this wasn't declared as an enum and now used as a
15493 // struct or something similar.
15494 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15495 TUK == TUK_Definition, KWLoc,
15496 Name)) {
15497 bool SafeToContinue
15498 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15499 Kind != TTK_Enum);
15500 if (SafeToContinue)
15501 Diag(KWLoc, diag::err_use_with_wrong_tag)
15502 << Name
15503 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15504 PrevTagDecl->getKindName());
15505 else
15506 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15507 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15508
15509 if (SafeToContinue)
15510 Kind = PrevTagDecl->getTagKind();
15511 else {
15512 // Recover by making this an anonymous redefinition.
15513 Name = nullptr;
15514 Previous.clear();
15515 Invalid = true;
15516 }
15517 }
15518
15519 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15520 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15521
15522 // If this is an elaborated-type-specifier for a scoped enumeration,
15523 // the 'class' keyword is not necessary and not permitted.
15524 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15525 if (ScopedEnum)
15526 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15527 << PrevEnum->isScoped()
15528 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15529 return PrevTagDecl;
15530 }
15531
15532 QualType EnumUnderlyingTy;
15533 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15534 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15535 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15536 EnumUnderlyingTy = QualType(T, 0);
15537
15538 // All conflicts with previous declarations are recovered by
15539 // returning the previous declaration, unless this is a definition,
15540 // in which case we want the caller to bail out.
15541 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15542 ScopedEnum, EnumUnderlyingTy,
15543 IsFixed, PrevEnum))
15544 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15545 }
15546
15547 // C++11 [class.mem]p1:
15548 // A member shall not be declared twice in the member-specification,
15549 // except that a nested class or member class template can be declared
15550 // and then later defined.
15551 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15552 S->isDeclScope(PrevDecl)) {
15553 Diag(NameLoc, diag::ext_member_redeclared);
15554 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15555 }
15556
15557 if (!Invalid) {
15558 // If this is a use, just return the declaration we found, unless
15559 // we have attributes.
15560 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15561 if (!Attrs.empty()) {
15562 // FIXME: Diagnose these attributes. For now, we create a new
15563 // declaration to hold them.
15564 } else if (TUK == TUK_Reference &&
15565 (PrevTagDecl->getFriendObjectKind() ==
15566 Decl::FOK_Undeclared ||
15567 PrevDecl->getOwningModule() != getCurrentModule()) &&
15568 SS.isEmpty()) {
15569 // This declaration is a reference to an existing entity, but
15570 // has different visibility from that entity: it either makes
15571 // a friend visible or it makes a type visible in a new module.
15572 // In either case, create a new declaration. We only do this if
15573 // the declaration would have meant the same thing if no prior
15574 // declaration were found, that is, if it was found in the same
15575 // scope where we would have injected a declaration.
15576 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15577 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15578 return PrevTagDecl;
15579 // This is in the injected scope, create a new declaration in
15580 // that scope.
15581 S = getTagInjectionScope(S, getLangOpts());
15582 } else {
15583 return PrevTagDecl;
15584 }
15585 }
15586
15587 // Diagnose attempts to redefine a tag.
15588 if (TUK == TUK_Definition) {
15589 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15590 // If we're defining a specialization and the previous definition
15591 // is from an implicit instantiation, don't emit an error
15592 // here; we'll catch this in the general case below.
15593 bool IsExplicitSpecializationAfterInstantiation = false;
15594 if (isMemberSpecialization) {
15595 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15596 IsExplicitSpecializationAfterInstantiation =
15597 RD->getTemplateSpecializationKind() !=
15598 TSK_ExplicitSpecialization;
15599 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15600 IsExplicitSpecializationAfterInstantiation =
15601 ED->getTemplateSpecializationKind() !=
15602 TSK_ExplicitSpecialization;
15603 }
15604
15605 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15606 // not keep more that one definition around (merge them). However,
15607 // ensure the decl passes the structural compatibility check in
15608 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15609 NamedDecl *Hidden = nullptr;
15610 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15611 // There is a definition of this tag, but it is not visible. We
15612 // explicitly make use of C++'s one definition rule here, and
15613 // assume that this definition is identical to the hidden one
15614 // we already have. Make the existing definition visible and
15615 // use it in place of this one.
15616 if (!getLangOpts().CPlusPlus) {
15617 // Postpone making the old definition visible until after we
15618 // complete parsing the new one and do the structural
15619 // comparison.
15620 SkipBody->CheckSameAsPrevious = true;
15621 SkipBody->New = createTagFromNewDecl();
15622 SkipBody->Previous = Def;
15623 return Def;
15624 } else {
15625 SkipBody->ShouldSkip = true;
15626 SkipBody->Previous = Def;
15627 makeMergedDefinitionVisible(Hidden);
15628 // Carry on and handle it like a normal definition. We'll
15629 // skip starting the definitiion later.
15630 }
15631 } else if (!IsExplicitSpecializationAfterInstantiation) {
15632 // A redeclaration in function prototype scope in C isn't
15633 // visible elsewhere, so merely issue a warning.
15634 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15635 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15636 else
15637 Diag(NameLoc, diag::err_redefinition) << Name;
15638 notePreviousDefinition(Def,
15639 NameLoc.isValid() ? NameLoc : KWLoc);
15640 // If this is a redefinition, recover by making this
15641 // struct be anonymous, which will make any later
15642 // references get the previous definition.
15643 Name = nullptr;
15644 Previous.clear();
15645 Invalid = true;
15646 }
15647 } else {
15648 // If the type is currently being defined, complain
15649 // about a nested redefinition.
15650 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15651 if (TD->isBeingDefined()) {
15652 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15653 Diag(PrevTagDecl->getLocation(),
15654 diag::note_previous_definition);
15655 Name = nullptr;
15656 Previous.clear();
15657 Invalid = true;
15658 }
15659 }
15660
15661 // Okay, this is definition of a previously declared or referenced
15662 // tag. We're going to create a new Decl for it.
15663 }
15664
15665 // Okay, we're going to make a redeclaration. If this is some kind
15666 // of reference, make sure we build the redeclaration in the same DC
15667 // as the original, and ignore the current access specifier.
15668 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15669 SearchDC = PrevTagDecl->getDeclContext();
15670 AS = AS_none;
15671 }
15672 }
15673 // If we get here we have (another) forward declaration or we
15674 // have a definition. Just create a new decl.
15675
15676 } else {
15677 // If we get here, this is a definition of a new tag type in a nested
15678 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15679 // new decl/type. We set PrevDecl to NULL so that the entities
15680 // have distinct types.
15681 Previous.clear();
15682 }
15683 // If we get here, we're going to create a new Decl. If PrevDecl
15684 // is non-NULL, it's a definition of the tag declared by
15685 // PrevDecl. If it's NULL, we have a new definition.
15686
15687 // Otherwise, PrevDecl is not a tag, but was found with tag
15688 // lookup. This is only actually possible in C++, where a few
15689 // things like templates still live in the tag namespace.
15690 } else {
15691 // Use a better diagnostic if an elaborated-type-specifier
15692 // found the wrong kind of type on the first
15693 // (non-redeclaration) lookup.
15694 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15695 !Previous.isForRedeclaration()) {
15696 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15697 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15698 << Kind;
15699 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15700 Invalid = true;
15701
15702 // Otherwise, only diagnose if the declaration is in scope.
15703 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15704 SS.isNotEmpty() || isMemberSpecialization)) {
15705 // do nothing
15706
15707 // Diagnose implicit declarations introduced by elaborated types.
15708 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15709 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15710 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15711 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15712 Invalid = true;
15713
15714 // Otherwise it's a declaration. Call out a particularly common
15715 // case here.
15716 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15717 unsigned Kind = 0;
15718 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15719 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15720 << Name << Kind << TND->getUnderlyingType();
15721 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15722 Invalid = true;
15723
15724 // Otherwise, diagnose.
15725 } else {
15726 // The tag name clashes with something else in the target scope,
15727 // issue an error and recover by making this tag be anonymous.
15728 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15729 notePreviousDefinition(PrevDecl, NameLoc);
15730 Name = nullptr;
15731 Invalid = true;
15732 }
15733
15734 // The existing declaration isn't relevant to us; we're in a
15735 // new scope, so clear out the previous declaration.
15736 Previous.clear();
15737 }
15738 }
15739
15740CreateNewDecl:
15741
15742 TagDecl *PrevDecl = nullptr;
15743 if (Previous.isSingleResult())
15744 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15745
15746 // If there is an identifier, use the location of the identifier as the
15747 // location of the decl, otherwise use the location of the struct/union
15748 // keyword.
15749 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15750
15751 // Otherwise, create a new declaration. If there is a previous
15752 // declaration of the same entity, the two will be linked via
15753 // PrevDecl.
15754 TagDecl *New;
15755
15756 if (Kind == TTK_Enum) {
15757 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15758 // enum X { A, B, C } D; D should chain to X.
15759 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15760 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15761 ScopedEnumUsesClassTag, IsFixed);
15762
15763 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15764 StdAlignValT = cast<EnumDecl>(New);
15765
15766 // If this is an undefined enum, warn.
15767 if (TUK != TUK_Definition && !Invalid) {
15768 TagDecl *Def;
15769 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15770 // C++0x: 7.2p2: opaque-enum-declaration.
15771 // Conflicts are diagnosed above. Do nothing.
15772 }
15773 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15774 Diag(Loc, diag::ext_forward_ref_enum_def)
15775 << New;
15776 Diag(Def->getLocation(), diag::note_previous_definition);
15777 } else {
15778 unsigned DiagID = diag::ext_forward_ref_enum;
15779 if (getLangOpts().MSVCCompat)
15780 DiagID = diag::ext_ms_forward_ref_enum;
15781 else if (getLangOpts().CPlusPlus)
15782 DiagID = diag::err_forward_ref_enum;
15783 Diag(Loc, DiagID);
15784 }
15785 }
15786
15787 if (EnumUnderlying) {
15788 EnumDecl *ED = cast<EnumDecl>(New);
15789 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15790 ED->setIntegerTypeSourceInfo(TI);
15791 else
15792 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15793 ED->setPromotionType(ED->getIntegerType());
15794 assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete"
) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 15794, __PRETTY_FUNCTION__))
;
15795 }
15796 } else {
15797 // struct/union/class
15798
15799 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15800 // struct X { int A; } D; D should chain to X.
15801 if (getLangOpts().CPlusPlus) {
15802 // FIXME: Look for a way to use RecordDecl for simple structs.
15803 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15804 cast_or_null<CXXRecordDecl>(PrevDecl));
15805
15806 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15807 StdBadAlloc = cast<CXXRecordDecl>(New);
15808 } else
15809 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15810 cast_or_null<RecordDecl>(PrevDecl));
15811 }
15812
15813 // C++11 [dcl.type]p3:
15814 // A type-specifier-seq shall not define a class or enumeration [...].
15815 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15816 TUK == TUK_Definition) {
15817 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15818 << Context.getTagDeclType(New);
15819 Invalid = true;
15820 }
15821
15822 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15823 DC->getDeclKind() == Decl::Enum) {
15824 Diag(New->getLocation(), diag::err_type_defined_in_enum)
15825 << Context.getTagDeclType(New);
15826 Invalid = true;
15827 }
15828
15829 // Maybe add qualifier info.
15830 if (SS.isNotEmpty()) {
15831 if (SS.isSet()) {
15832 // If this is either a declaration or a definition, check the
15833 // nested-name-specifier against the current context.
15834 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15835 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15836 isMemberSpecialization))
15837 Invalid = true;
15838
15839 New->setQualifierInfo(SS.getWithLocInContext(Context));
15840 if (TemplateParameterLists.size() > 0) {
15841 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15842 }
15843 }
15844 else
15845 Invalid = true;
15846 }
15847
15848 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15849 // Add alignment attributes if necessary; these attributes are checked when
15850 // the ASTContext lays out the structure.
15851 //
15852 // It is important for implementing the correct semantics that this
15853 // happen here (in ActOnTag). The #pragma pack stack is
15854 // maintained as a result of parser callbacks which can occur at
15855 // many points during the parsing of a struct declaration (because
15856 // the #pragma tokens are effectively skipped over during the
15857 // parsing of the struct).
15858 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15859 AddAlignmentAttributesForRecord(RD);
15860 AddMsStructLayoutForRecord(RD);
15861 }
15862 }
15863
15864 if (ModulePrivateLoc.isValid()) {
15865 if (isMemberSpecialization)
15866 Diag(New->getLocation(), diag::err_module_private_specialization)
15867 << 2
15868 << FixItHint::CreateRemoval(ModulePrivateLoc);
15869 // __module_private__ does not apply to local classes. However, we only
15870 // diagnose this as an error when the declaration specifiers are
15871 // freestanding. Here, we just ignore the __module_private__.
15872 else if (!SearchDC->isFunctionOrMethod())
15873 New->setModulePrivate();
15874 }
15875
15876 // If this is a specialization of a member class (of a class template),
15877 // check the specialization.
15878 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15879 Invalid = true;
15880
15881 // If we're declaring or defining a tag in function prototype scope in C,
15882 // note that this type can only be used within the function and add it to
15883 // the list of decls to inject into the function definition scope.
15884 if ((Name || Kind == TTK_Enum) &&
15885 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15886 if (getLangOpts().CPlusPlus) {
15887 // C++ [dcl.fct]p6:
15888 // Types shall not be defined in return or parameter types.
15889 if (TUK == TUK_Definition && !IsTypeSpecifier) {
15890 Diag(Loc, diag::err_type_defined_in_param_type)
15891 << Name;
15892 Invalid = true;
15893 }
15894 } else if (!PrevDecl) {
15895 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15896 }
15897 }
15898
15899 if (Invalid)
15900 New->setInvalidDecl();
15901
15902 // Set the lexical context. If the tag has a C++ scope specifier, the
15903 // lexical context will be different from the semantic context.
15904 New->setLexicalDeclContext(CurContext);
15905
15906 // Mark this as a friend decl if applicable.
15907 // In Microsoft mode, a friend declaration also acts as a forward
15908 // declaration so we always pass true to setObjectOfFriendDecl to make
15909 // the tag name visible.
15910 if (TUK == TUK_Friend)
15911 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15912
15913 // Set the access specifier.
15914 if (!Invalid && SearchDC->isRecord())
15915 SetMemberAccessSpecifier(New, PrevDecl, AS);
15916
15917 if (PrevDecl)
15918 CheckRedeclarationModuleOwnership(New, PrevDecl);
15919
15920 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15921 New->startDefinition();
15922
15923 ProcessDeclAttributeList(S, New, Attrs);
15924 AddPragmaAttributes(S, New);
15925
15926 // If this has an identifier, add it to the scope stack.
15927 if (TUK == TUK_Friend) {
15928 // We might be replacing an existing declaration in the lookup tables;
15929 // if so, borrow its access specifier.
15930 if (PrevDecl)
15931 New->setAccess(PrevDecl->getAccess());
15932
15933 DeclContext *DC = New->getDeclContext()->getRedeclContext();
15934 DC->makeDeclVisibleInContext(New);
15935 if (Name) // can be null along some error paths
15936 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15937 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15938 } else if (Name) {
15939 S = getNonFieldDeclScope(S);
15940 PushOnScopeChains(New, S, true);
15941 } else {
15942 CurContext->addDecl(New);
15943 }
15944
15945 // If this is the C FILE type, notify the AST context.
15946 if (IdentifierInfo *II = New->getIdentifier())
15947 if (!New->isInvalidDecl() &&
15948 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15949 II->isStr("FILE"))
15950 Context.setFILEDecl(New);
15951
15952 if (PrevDecl)
15953 mergeDeclAttributes(New, PrevDecl);
15954
15955 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15956 inferGslOwnerPointerAttribute(CXXRD);
15957
15958 // If there's a #pragma GCC visibility in scope, set the visibility of this
15959 // record.
15960 AddPushedVisibilityAttribute(New);
15961
15962 if (isMemberSpecialization && !New->isInvalidDecl())
15963 CompleteMemberSpecialization(New, Previous);
15964
15965 OwnedDecl = true;
15966 // In C++, don't return an invalid declaration. We can't recover well from
15967 // the cases where we make the type anonymous.
15968 if (Invalid && getLangOpts().CPlusPlus) {
15969 if (New->isBeingDefined())
15970 if (auto RD = dyn_cast<RecordDecl>(New))
15971 RD->completeDefinition();
15972 return nullptr;
15973 } else if (SkipBody && SkipBody->ShouldSkip) {
15974 return SkipBody->Previous;
15975 } else {
15976 return New;
15977 }
15978}
15979
15980void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15981 AdjustDeclIfTemplate(TagD);
15982 TagDecl *Tag = cast<TagDecl>(TagD);
15983
15984 // Enter the tag context.
15985 PushDeclContext(S, Tag);
15986
15987 ActOnDocumentableDecl(TagD);
15988
15989 // If there's a #pragma GCC visibility in scope, set the visibility of this
15990 // record.
15991 AddPushedVisibilityAttribute(Tag);
15992}
15993
15994bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15995 SkipBodyInfo &SkipBody) {
15996 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15997 return false;
15998
15999 // Make the previous decl visible.
16000 makeMergedDefinitionVisible(SkipBody.Previous);
16001 return true;
16002}
16003
16004Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16005 assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16006, __PRETTY_FUNCTION__))
16006 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16006, __PRETTY_FUNCTION__))
;
16007 DeclContext *OCD = cast<DeclContext>(IDecl);
16008 assert(getContainingDC(OCD) == CurContext &&((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16009, __PRETTY_FUNCTION__))
16009 "The next DeclContext should be lexically contained in the current one.")((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16009, __PRETTY_FUNCTION__))
;
16010 CurContext = OCD;
16011 return IDecl;
16012}
16013
16014void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16015 SourceLocation FinalLoc,
16016 bool IsFinalSpelledSealed,
16017 SourceLocation LBraceLoc) {
16018 AdjustDeclIfTemplate(TagD);
16019 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16020
16021 FieldCollector->StartClass();
16022
16023 if (!Record->getIdentifier())
16024 return;
16025
16026 if (FinalLoc.isValid())
16027 Record->addAttr(FinalAttr::Create(
16028 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16029 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16030
16031 // C++ [class]p2:
16032 // [...] The class-name is also inserted into the scope of the
16033 // class itself; this is known as the injected-class-name. For
16034 // purposes of access checking, the injected-class-name is treated
16035 // as if it were a public member name.
16036 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16037 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16038 Record->getLocation(), Record->getIdentifier(),
16039 /*PrevDecl=*/nullptr,
16040 /*DelayTypeCreation=*/true);
16041 Context.getTypeDeclType(InjectedClassName, Record);
16042 InjectedClassName->setImplicit();
16043 InjectedClassName->setAccess(AS_public);
16044 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16045 InjectedClassName->setDescribedClassTemplate(Template);
16046 PushOnScopeChains(InjectedClassName, S);
16047 assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16048, __PRETTY_FUNCTION__))
16048 "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16048, __PRETTY_FUNCTION__))
;
16049}
16050
16051void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16052 SourceRange BraceRange) {
16053 AdjustDeclIfTemplate(TagD);
16054 TagDecl *Tag = cast<TagDecl>(TagD);
16055 Tag->setBraceRange(BraceRange);
16056
16057 // Make sure we "complete" the definition even it is invalid.
16058 if (Tag->isBeingDefined()) {
16059 assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it"
) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16059, __PRETTY_FUNCTION__))
;
16060 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16061 RD->completeDefinition();
16062 }
16063
16064 if (isa<CXXRecordDecl>(Tag)) {
16065 FieldCollector->FinishClass();
16066 }
16067
16068 // Exit this scope of this tag's definition.
16069 PopDeclContext();
16070
16071 if (getCurLexicalContext()->isObjCContainer() &&
16072 Tag->getDeclContext()->isFileContext())
16073 Tag->setTopLevelDeclInObjCContainer();
16074
16075 // Notify the consumer that we've defined a tag.
16076 if (!Tag->isInvalidDecl())
16077 Consumer.HandleTagDeclDefinition(Tag);
16078}
16079
16080void Sema::ActOnObjCContainerFinishDefinition() {
16081 // Exit this scope of this interface definition.
16082 PopDeclContext();
16083}
16084
16085void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16086 assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts"
) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16086, __PRETTY_FUNCTION__))
;
16087 OriginalLexicalContext = DC;
16088 ActOnObjCContainerFinishDefinition();
16089}
16090
16091void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16092 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16093 OriginalLexicalContext = nullptr;
16094}
16095
16096void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16097 AdjustDeclIfTemplate(TagD);
16098 TagDecl *Tag = cast<TagDecl>(TagD);
16099 Tag->setInvalidDecl();
16100
16101 // Make sure we "complete" the definition even it is invalid.
16102 if (Tag->isBeingDefined()) {
16103 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16104 RD->completeDefinition();
16105 }
16106
16107 // We're undoing ActOnTagStartDefinition here, not
16108 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16109 // the FieldCollector.
16110
16111 PopDeclContext();
16112}
16113
16114// Note that FieldName may be null for anonymous bitfields.
16115ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16116 IdentifierInfo *FieldName,
16117 QualType FieldTy, bool IsMsStruct,
16118 Expr *BitWidth, bool *ZeroWidth) {
16119 // Default to true; that shouldn't confuse checks for emptiness
16120 if (ZeroWidth)
16121 *ZeroWidth = true;
16122
16123 // C99 6.7.2.1p4 - verify the field type.
16124 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16125 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16126 // Handle incomplete types with specific error.
16127 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
16128 return ExprError();
16129 if (FieldName)
16130 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16131 << FieldName << FieldTy << BitWidth->getSourceRange();
16132 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16133 << FieldTy << BitWidth->getSourceRange();
16134 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16135 UPPC_BitFieldWidth))
16136 return ExprError();
16137
16138 // If the bit-width is type- or value-dependent, don't try to check
16139 // it now.
16140 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16141 return BitWidth;
16142
16143 llvm::APSInt Value;
16144 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16145 if (ICE.isInvalid())
16146 return ICE;
16147 BitWidth = ICE.get();
16148
16149 if (Value != 0 && ZeroWidth)
16150 *ZeroWidth = false;
16151
16152 // Zero-width bitfield is ok for anonymous field.
16153 if (Value == 0 && FieldName)
16154 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16155
16156 if (Value.isSigned() && Value.isNegative()) {
16157 if (FieldName)
16158 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16159 << FieldName << Value.toString(10);
16160 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16161 << Value.toString(10);
16162 }
16163
16164 if (!FieldTy->isDependentType()) {
16165 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16166 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16167 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16168
16169 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16170 // ABI.
16171 bool CStdConstraintViolation =
16172 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16173 bool MSBitfieldViolation =
16174 Value.ugt(TypeStorageSize) &&
16175 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16176 if (CStdConstraintViolation || MSBitfieldViolation) {
16177 unsigned DiagWidth =
16178 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16179 if (FieldName)
16180 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16181 << FieldName << (unsigned)Value.getZExtValue()
16182 << !CStdConstraintViolation << DiagWidth;
16183
16184 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16185 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16186 << DiagWidth;
16187 }
16188
16189 // Warn on types where the user might conceivably expect to get all
16190 // specified bits as value bits: that's all integral types other than
16191 // 'bool'.
16192 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16193 if (FieldName)
16194 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16195 << FieldName << (unsigned)Value.getZExtValue()
16196 << (unsigned)TypeWidth;
16197 else
16198 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16199 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16200 }
16201 }
16202
16203 return BitWidth;
16204}
16205
16206/// ActOnField - Each field of a C struct/union is passed into this in order
16207/// to create a FieldDecl object for it.
16208Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16209 Declarator &D, Expr *BitfieldWidth) {
16210 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16211 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16212 /*InitStyle=*/ICIS_NoInit, AS_public);
16213 return Res;
16214}
16215
16216/// HandleField - Analyze a field of a C struct or a C++ data member.
16217///
16218FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16219 SourceLocation DeclStart,
16220 Declarator &D, Expr *BitWidth,
16221 InClassInitStyle InitStyle,
16222 AccessSpecifier AS) {
16223 if (D.isDecompositionDeclarator()) {
16224 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16225 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16226 << Decomp.getSourceRange();
16227 return nullptr;
16228 }
16229
16230 IdentifierInfo *II = D.getIdentifier();
16231 SourceLocation Loc = DeclStart;
16232 if (II) Loc = D.getIdentifierLoc();
16233
16234 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16235 QualType T = TInfo->getType();
16236 if (getLangOpts().CPlusPlus) {
16237 CheckExtraCXXDefaultArguments(D);
16238
16239 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16240 UPPC_DataMemberType)) {
16241 D.setInvalidType();
16242 T = Context.IntTy;
16243 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16244 }
16245 }
16246
16247 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16248
16249 if (D.getDeclSpec().isInlineSpecified())
16250 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16251 << getLangOpts().CPlusPlus17;
16252 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16253 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16254 diag::err_invalid_thread)
16255 << DeclSpec::getSpecifierName(TSCS);
16256
16257 // Check to see if this name was declared as a member previously
16258 NamedDecl *PrevDecl = nullptr;
16259 LookupResult Previous(*this, II, Loc, LookupMemberName,
16260 ForVisibleRedeclaration);
16261 LookupName(Previous, S);
16262 switch (Previous.getResultKind()) {
16263 case LookupResult::Found:
16264 case LookupResult::FoundUnresolvedValue:
16265 PrevDecl = Previous.getAsSingle<NamedDecl>();
16266 break;
16267
16268 case LookupResult::FoundOverloaded:
16269 PrevDecl = Previous.getRepresentativeDecl();
16270 break;
16271
16272 case LookupResult::NotFound:
16273 case LookupResult::NotFoundInCurrentInstantiation:
16274 case LookupResult::Ambiguous:
16275 break;
16276 }
16277 Previous.suppressDiagnostics();
16278
16279 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16280 // Maybe we will complain about the shadowed template parameter.
16281 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16282 // Just pretend that we didn't see the previous declaration.
16283 PrevDecl = nullptr;
16284 }
16285
16286 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16287 PrevDecl = nullptr;
16288
16289 bool Mutable
16290 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16291 SourceLocation TSSL = D.getBeginLoc();
16292 FieldDecl *NewFD
16293 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16294 TSSL, AS, PrevDecl, &D);
16295
16296 if (NewFD->isInvalidDecl())
16297 Record->setInvalidDecl();
16298
16299 if (D.getDeclSpec().isModulePrivateSpecified())
16300 NewFD->setModulePrivate();
16301
16302 if (NewFD->isInvalidDecl() && PrevDecl) {
16303 // Don't introduce NewFD into scope; there's already something
16304 // with the same name in the same scope.
16305 } else if (II) {
16306 PushOnScopeChains(NewFD, S);
16307 } else
16308 Record->addDecl(NewFD);
16309
16310 return NewFD;
16311}
16312
16313/// Build a new FieldDecl and check its well-formedness.
16314///
16315/// This routine builds a new FieldDecl given the fields name, type,
16316/// record, etc. \p PrevDecl should refer to any previous declaration
16317/// with the same name and in the same scope as the field to be
16318/// created.
16319///
16320/// \returns a new FieldDecl.
16321///
16322/// \todo The Declarator argument is a hack. It will be removed once
16323FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16324 TypeSourceInfo *TInfo,
16325 RecordDecl *Record, SourceLocation Loc,
16326 bool Mutable, Expr *BitWidth,
16327 InClassInitStyle InitStyle,
16328 SourceLocation TSSL,
16329 AccessSpecifier AS, NamedDecl *PrevDecl,
16330 Declarator *D) {
16331 IdentifierInfo *II = Name.getAsIdentifierInfo();
16332 bool InvalidDecl = false;
16333 if (D) InvalidDecl = D->isInvalidType();
16334
16335 // If we receive a broken type, recover by assuming 'int' and
16336 // marking this declaration as invalid.
16337 if (T.isNull()) {
16338 InvalidDecl = true;
16339 T = Context.IntTy;
16340 }
16341
16342 QualType EltTy = Context.getBaseElementType(T);
16343 if (!EltTy->isDependentType()) {
16344 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16345 // Fields of incomplete type force their record to be invalid.
16346 Record->setInvalidDecl();
16347 InvalidDecl = true;
16348 } else {
16349 NamedDecl *Def;
16350 EltTy->isIncompleteType(&Def);
16351 if (Def && Def->isInvalidDecl()) {
16352 Record->setInvalidDecl();
16353 InvalidDecl = true;
16354 }
16355 }
16356 }
16357
16358 // TR 18037 does not allow fields to be declared with address space
16359 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16360 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16361 Diag(Loc, diag::err_field_with_address_space);
16362 Record->setInvalidDecl();
16363 InvalidDecl = true;
16364 }
16365
16366 if (LangOpts.OpenCL) {
16367 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16368 // used as structure or union field: image, sampler, event or block types.
16369 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16370 T->isBlockPointerType()) {
16371 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16372 Record->setInvalidDecl();
16373 InvalidDecl = true;
16374 }
16375 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16376 if (BitWidth) {
16377 Diag(Loc, diag::err_opencl_bitfields);
16378 InvalidDecl = true;
16379 }
16380 }
16381
16382 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16383 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16384 T.hasQualifiers()) {
16385 InvalidDecl = true;
16386 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16387 }
16388
16389 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16390 // than a variably modified type.
16391 if (!InvalidDecl && T->isVariablyModifiedType()) {
16392 bool SizeIsNegative;
16393 llvm::APSInt Oversized;
16394
16395 TypeSourceInfo *FixedTInfo =
16396 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16397 SizeIsNegative,
16398 Oversized);
16399 if (FixedTInfo) {
16400 Diag(Loc, diag::warn_illegal_constant_array_size);
16401 TInfo = FixedTInfo;
16402 T = FixedTInfo->getType();
16403 } else {
16404 if (SizeIsNegative)
16405 Diag(Loc, diag::err_typecheck_negative_array_size);
16406 else if (Oversized.getBoolValue())
16407 Diag(Loc, diag::err_array_too_large)
16408 << Oversized.toString(10);
16409 else
16410 Diag(Loc, diag::err_typecheck_field_variable_size);
16411 InvalidDecl = true;
16412 }
16413 }
16414
16415 // Fields can not have abstract class types
16416 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16417 diag::err_abstract_type_in_decl,
16418 AbstractFieldType))
16419 InvalidDecl = true;
16420
16421 bool ZeroWidth = false;
16422 if (InvalidDecl)
16423 BitWidth = nullptr;
16424 // If this is declared as a bit-field, check the bit-field.
16425 if (BitWidth) {
16426 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16427 &ZeroWidth).get();
16428 if (!BitWidth) {
16429 InvalidDecl = true;
16430 BitWidth = nullptr;
16431 ZeroWidth = false;
16432 }
16433 }
16434
16435 // Check that 'mutable' is consistent with the type of the declaration.
16436 if (!InvalidDecl && Mutable) {
16437 unsigned DiagID = 0;
16438 if (T->isReferenceType())
16439 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16440 : diag::err_mutable_reference;
16441 else if (T.isConstQualified())
16442 DiagID = diag::err_mutable_const;
16443
16444 if (DiagID) {
16445 SourceLocation ErrLoc = Loc;
16446 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16447 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16448 Diag(ErrLoc, DiagID);
16449 if (DiagID != diag::ext_mutable_reference) {
16450 Mutable = false;
16451 InvalidDecl = true;
16452 }
16453 }
16454 }
16455
16456 // C++11 [class.union]p8 (DR1460):
16457 // At most one variant member of a union may have a
16458 // brace-or-equal-initializer.
16459 if (InitStyle != ICIS_NoInit)
16460 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16461
16462 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16463 BitWidth, Mutable, InitStyle);
16464 if (InvalidDecl)
16465 NewFD->setInvalidDecl();
16466
16467 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16468 Diag(Loc, diag::err_duplicate_member) << II;
16469 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16470 NewFD->setInvalidDecl();
16471 }
16472
16473 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16474 if (Record->isUnion()) {
16475 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16476 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16477 if (RDecl->getDefinition()) {
16478 // C++ [class.union]p1: An object of a class with a non-trivial
16479 // constructor, a non-trivial copy constructor, a non-trivial
16480 // destructor, or a non-trivial copy assignment operator
16481 // cannot be a member of a union, nor can an array of such
16482 // objects.
16483 if (CheckNontrivialField(NewFD))
16484 NewFD->setInvalidDecl();
16485 }
16486 }
16487
16488 // C++ [class.union]p1: If a union contains a member of reference type,
16489 // the program is ill-formed, except when compiling with MSVC extensions
16490 // enabled.
16491 if (EltTy->isReferenceType()) {
16492 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16493 diag::ext_union_member_of_reference_type :
16494 diag::err_union_member_of_reference_type)
16495 << NewFD->getDeclName() << EltTy;
16496 if (!getLangOpts().MicrosoftExt)
16497 NewFD->setInvalidDecl();
16498 }
16499 }
16500 }
16501
16502 // FIXME: We need to pass in the attributes given an AST
16503 // representation, not a parser representation.
16504 if (D) {
16505 // FIXME: The current scope is almost... but not entirely... correct here.
16506 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16507
16508 if (NewFD->hasAttrs())
16509 CheckAlignasUnderalignment(NewFD);
16510 }
16511
16512 // In auto-retain/release, infer strong retension for fields of
16513 // retainable type.
16514 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16515 NewFD->setInvalidDecl();
16516
16517 if (T.isObjCGCWeak())
16518 Diag(Loc, diag::warn_attribute_weak_on_field);
16519
16520 NewFD->setAccess(AS);
16521 return NewFD;
16522}
16523
16524bool Sema::CheckNontrivialField(FieldDecl *FD) {
16525 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16525, __PRETTY_FUNCTION__))
;
16526 assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16526, __PRETTY_FUNCTION__))
;
16527
16528 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16529 return false;
16530
16531 QualType EltTy = Context.getBaseElementType(FD->getType());
16532 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16533 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16534 if (RDecl->getDefinition()) {
16535 // We check for copy constructors before constructors
16536 // because otherwise we'll never get complaints about
16537 // copy constructors.
16538
16539 CXXSpecialMember member = CXXInvalid;
16540 // We're required to check for any non-trivial constructors. Since the
16541 // implicit default constructor is suppressed if there are any
16542 // user-declared constructors, we just need to check that there is a
16543 // trivial default constructor and a trivial copy constructor. (We don't
16544 // worry about move constructors here, since this is a C++98 check.)
16545 if (RDecl->hasNonTrivialCopyConstructor())
16546 member = CXXCopyConstructor;
16547 else if (!RDecl->hasTrivialDefaultConstructor())
16548 member = CXXDefaultConstructor;
16549 else if (RDecl->hasNonTrivialCopyAssignment())
16550 member = CXXCopyAssignment;
16551 else if (RDecl->hasNonTrivialDestructor())
16552 member = CXXDestructor;
16553
16554 if (member != CXXInvalid) {
16555 if (!getLangOpts().CPlusPlus11 &&
16556 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16557 // Objective-C++ ARC: it is an error to have a non-trivial field of
16558 // a union. However, system headers in Objective-C programs
16559 // occasionally have Objective-C lifetime objects within unions,
16560 // and rather than cause the program to fail, we make those
16561 // members unavailable.
16562 SourceLocation Loc = FD->getLocation();
16563 if (getSourceManager().isInSystemHeader(Loc)) {
16564 if (!FD->hasAttr<UnavailableAttr>())
16565 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16566 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16567 return false;
16568 }
16569 }
16570
16571 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16572 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16573 diag::err_illegal_union_or_anon_struct_member)
16574 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16575 DiagnoseNontrivial(RDecl, member);
16576 return !getLangOpts().CPlusPlus11;
16577 }
16578 }
16579 }
16580
16581 return false;
16582}
16583
16584/// TranslateIvarVisibility - Translate visibility from a token ID to an
16585/// AST enum value.
16586static ObjCIvarDecl::AccessControl
16587TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16588 switch (ivarVisibility) {
16589 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16589)
;
16590 case tok::objc_private: return ObjCIvarDecl::Private;
16591 case tok::objc_public: return ObjCIvarDecl::Public;
16592 case tok::objc_protected: return ObjCIvarDecl::Protected;
16593 case tok::objc_package: return ObjCIvarDecl::Package;
16594 }
16595}
16596
16597/// ActOnIvar - Each ivar field of an objective-c class is passed into this
16598/// in order to create an IvarDecl object for it.
16599Decl *Sema::ActOnIvar(Scope *S,
16600 SourceLocation DeclStart,
16601 Declarator &D, Expr *BitfieldWidth,
16602 tok::ObjCKeywordKind Visibility) {
16603
16604 IdentifierInfo *II = D.getIdentifier();
16605 Expr *BitWidth = (Expr*)BitfieldWidth;
16606 SourceLocation Loc = DeclStart;
16607 if (II) Loc = D.getIdentifierLoc();
16608
16609 // FIXME: Unnamed fields can be handled in various different ways, for
16610 // example, unnamed unions inject all members into the struct namespace!
16611
16612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16613 QualType T = TInfo->getType();
16614
16615 if (BitWidth) {
16616 // 6.7.2.1p3, 6.7.2.1p4
16617 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16618 if (!BitWidth)
16619 D.setInvalidType();
16620 } else {
16621 // Not a bitfield.
16622
16623 // validate II.
16624
16625 }
16626 if (T->isReferenceType()) {
16627 Diag(Loc, diag::err_ivar_reference_type);
16628 D.setInvalidType();
16629 }
16630 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16631 // than a variably modified type.
16632 else if (T->isVariablyModifiedType()) {
16633 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16634 D.setInvalidType();
16635 }
16636
16637 // Get the visibility (access control) for this ivar.
16638 ObjCIvarDecl::AccessControl ac =
16639 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16640 : ObjCIvarDecl::None;
16641 // Must set ivar's DeclContext to its enclosing interface.
16642 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16643 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16644 return nullptr;
16645 ObjCContainerDecl *EnclosingContext;
16646 if (ObjCImplementationDecl *IMPDecl =
16647 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16648 if (LangOpts.ObjCRuntime.isFragile()) {
16649 // Case of ivar declared in an implementation. Context is that of its class.
16650 EnclosingContext = IMPDecl->getClassInterface();
16651 assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!"
) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16651, __PRETTY_FUNCTION__))
;
16652 }
16653 else
16654 EnclosingContext = EnclosingDecl;
16655 } else {
16656 if (ObjCCategoryDecl *CDecl =
16657 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16658 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16659 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16660 return nullptr;
16661 }
16662 }
16663 EnclosingContext = EnclosingDecl;
16664 }
16665
16666 // Construct the decl.
16667 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16668 DeclStart, Loc, II, T,
16669 TInfo, ac, (Expr *)BitfieldWidth);
16670
16671 if (II) {
16672 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16673 ForVisibleRedeclaration);
16674 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16675 && !isa<TagDecl>(PrevDecl)) {
16676 Diag(Loc, diag::err_duplicate_member) << II;
16677 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16678 NewID->setInvalidDecl();
16679 }
16680 }
16681
16682 // Process attributes attached to the ivar.
16683 ProcessDeclAttributes(S, NewID, D);
16684
16685 if (D.isInvalidType())
16686 NewID->setInvalidDecl();
16687
16688 // In ARC, infer 'retaining' for ivars of retainable type.
16689 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16690 NewID->setInvalidDecl();
16691
16692 if (D.getDeclSpec().isModulePrivateSpecified())
16693 NewID->setModulePrivate();
16694
16695 if (II) {
16696 // FIXME: When interfaces are DeclContexts, we'll need to add
16697 // these to the interface.
16698 S->AddDecl(NewID);
16699 IdResolver.AddDecl(NewID);
16700 }
16701
16702 if (LangOpts.ObjCRuntime.isNonFragile() &&
16703 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16704 Diag(Loc, diag::warn_ivars_in_interface);
16705
16706 return NewID;
16707}
16708
16709/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16710/// class and class extensions. For every class \@interface and class
16711/// extension \@interface, if the last ivar is a bitfield of any type,
16712/// then add an implicit `char :0` ivar to the end of that interface.
16713void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16714 SmallVectorImpl<Decl *> &AllIvarDecls) {
16715 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16716 return;
16717
16718 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16719 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16720
16721 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16722 return;
16723 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16724 if (!ID) {
16725 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16726 if (!CD->IsClassExtension())
16727 return;
16728 }
16729 // No need to add this to end of @implementation.
16730 else
16731 return;
16732 }
16733 // All conditions are met. Add a new bitfield to the tail end of ivars.
16734 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16735 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16736
16737 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16738 DeclLoc, DeclLoc, nullptr,
16739 Context.CharTy,
16740 Context.getTrivialTypeSourceInfo(Context.CharTy,
16741 DeclLoc),
16742 ObjCIvarDecl::Private, BW,
16743 true);
16744 AllIvarDecls.push_back(Ivar);
16745}
16746
16747void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16748 ArrayRef<Decl *> Fields, SourceLocation LBrac,
16749 SourceLocation RBrac,
16750 const ParsedAttributesView &Attrs) {
16751 assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl"
) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 16751, __PRETTY_FUNCTION__))
;
16752
16753 // If this is an Objective-C @implementation or category and we have
16754 // new fields here we should reset the layout of the interface since
16755 // it will now change.
16756 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16757 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16758 switch (DC->getKind()) {
16759 default: break;
16760 case Decl::ObjCCategory:
16761 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16762 break;
16763 case Decl::ObjCImplementation:
16764 Context.
16765 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16766 break;
16767 }
16768 }
16769
16770 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16771 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16772
16773 // Start counting up the number of named members; make sure to include
16774 // members of anonymous structs and unions in the total.
16775 unsigned NumNamedMembers = 0;
16776 if (Record) {
16777 for (const auto *I : Record->decls()) {
16778 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16779 if (IFD->getDeclName())
16780 ++NumNamedMembers;
16781 }
16782 }
16783
16784 // Verify that all the fields are okay.
16785 SmallVector<FieldDecl*, 32> RecFields;
16786
16787 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16788 i != end; ++i) {
16789 FieldDecl *FD = cast<FieldDecl>(*i);
16790
16791 // Get the type for the field.
16792 const Type *FDTy = FD->getType().getTypePtr();
16793
16794 if (!FD->isAnonymousStructOrUnion()) {
16795 // Remember all fields written by the user.
16796 RecFields.push_back(FD);
16797 }
16798
16799 // If the field is already invalid for some reason, don't emit more
16800 // diagnostics about it.
16801 if (FD->isInvalidDecl()) {
16802 EnclosingDecl->setInvalidDecl();
16803 continue;
16804 }
16805
16806 // C99 6.7.2.1p2:
16807 // A structure or union shall not contain a member with
16808 // incomplete or function type (hence, a structure shall not
16809 // contain an instance of itself, but may contain a pointer to
16810 // an instance of itself), except that the last member of a
16811 // structure with more than one named member may have incomplete
16812 // array type; such a structure (and any union containing,
16813 // possibly recursively, a member that is such a structure)
16814 // shall not be a member of a structure or an element of an
16815 // array.
16816 bool IsLastField = (i + 1 == Fields.end());
16817 if (FDTy->isFunctionType()) {
16818 // Field declared as a function.
16819 Diag(FD->getLocation(), diag::err_field_declared_as_function)
16820 << FD->getDeclName();
16821 FD->setInvalidDecl();
16822 EnclosingDecl->setInvalidDecl();
16823 continue;
16824 } else if (FDTy->isIncompleteArrayType() &&
16825 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16826 if (Record) {
16827 // Flexible array member.
16828 // Microsoft and g++ is more permissive regarding flexible array.
16829 // It will accept flexible array in union and also
16830 // as the sole element of a struct/class.
16831 unsigned DiagID = 0;
16832 if (!Record->isUnion() && !IsLastField) {
16833 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16834 << FD->getDeclName() << FD->getType() << Record->getTagKind();
16835 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16836 FD->setInvalidDecl();
16837 EnclosingDecl->setInvalidDecl();
16838 continue;
16839 } else if (Record->isUnion())
16840 DiagID = getLangOpts().MicrosoftExt
16841 ? diag::ext_flexible_array_union_ms
16842 : getLangOpts().CPlusPlus
16843 ? diag::ext_flexible_array_union_gnu
16844 : diag::err_flexible_array_union;
16845 else if (NumNamedMembers < 1)
16846 DiagID = getLangOpts().MicrosoftExt
16847 ? diag::ext_flexible_array_empty_aggregate_ms
16848 : getLangOpts().CPlusPlus
16849 ? diag::ext_flexible_array_empty_aggregate_gnu
16850 : diag::err_flexible_array_empty_aggregate;
16851
16852 if (DiagID)
16853 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16854 << Record->getTagKind();
16855 // While the layout of types that contain virtual bases is not specified
16856 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16857 // virtual bases after the derived members. This would make a flexible
16858 // array member declared at the end of an object not adjacent to the end
16859 // of the type.
16860 if (CXXRecord && CXXRecord->getNumVBases() != 0)
16861 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16862 << FD->getDeclName() << Record->getTagKind();
16863 if (!getLangOpts().C99)
16864 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16865 << FD->getDeclName() << Record->getTagKind();
16866
16867 // If the element type has a non-trivial destructor, we would not
16868 // implicitly destroy the elements, so disallow it for now.
16869 //
16870 // FIXME: GCC allows this. We should probably either implicitly delete
16871 // the destructor of the containing class, or just allow this.
16872 QualType BaseElem = Context.getBaseElementType(FD->getType());
16873 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16874 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16875 << FD->getDeclName() << FD->getType();
16876 FD->setInvalidDecl();
16877 EnclosingDecl->setInvalidDecl();
16878 continue;
16879 }
16880 // Okay, we have a legal flexible array member at the end of the struct.
16881 Record->setHasFlexibleArrayMember(true);
16882 } else {
16883 // In ObjCContainerDecl ivars with incomplete array type are accepted,
16884 // unless they are followed by another ivar. That check is done
16885 // elsewhere, after synthesized ivars are known.
16886 }
16887 } else if (!FDTy->isDependentType() &&
16888 RequireCompleteType(FD->getLocation(), FD->getType(),
16889 diag::err_field_incomplete)) {
16890 // Incomplete type
16891 FD->setInvalidDecl();
16892 EnclosingDecl->setInvalidDecl();
16893 continue;
16894 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16895 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16896 // A type which contains a flexible array member is considered to be a
16897 // flexible array member.
16898 Record->setHasFlexibleArrayMember(true);
16899 if (!Record->isUnion()) {
16900 // If this is a struct/class and this is not the last element, reject
16901 // it. Note that GCC supports variable sized arrays in the middle of
16902 // structures.
16903 if (!IsLastField)
16904 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16905 << FD->getDeclName() << FD->getType();
16906 else {
16907 // We support flexible arrays at the end of structs in
16908 // other structs as an extension.
16909 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16910 << FD->getDeclName();
16911 }
16912 }
16913 }
16914 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16915 RequireNonAbstractType(FD->getLocation(), FD->getType(),
16916 diag::err_abstract_type_in_decl,
16917 AbstractIvarType)) {
16918 // Ivars can not have abstract class types
16919 FD->setInvalidDecl();
16920 }
16921 if (Record && FDTTy->getDecl()->hasObjectMember())
16922 Record->setHasObjectMember(true);
16923 if (Record && FDTTy->getDecl()->hasVolatileMember())
16924 Record->setHasVolatileMember(true);
16925 } else if (FDTy->isObjCObjectType()) {
16926 /// A field cannot be an Objective-c object
16927 Diag(FD->getLocation(), diag::err_statically_allocated_object)
16928 << FixItHint::CreateInsertion(FD->getLocation(), "*");
16929 QualType T = Context.getObjCObjectPointerType(FD->getType());
16930 FD->setType(T);
16931 } else if (Record && Record->isUnion() &&
16932 FD->getType().hasNonTrivialObjCLifetime() &&
16933 getSourceManager().isInSystemHeader(FD->getLocation()) &&
16934 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16935 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16936 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16937 // For backward compatibility, fields of C unions declared in system
16938 // headers that have non-trivial ObjC ownership qualifications are marked
16939 // as unavailable unless the qualifier is explicit and __strong. This can
16940 // break ABI compatibility between programs compiled with ARC and MRR, but
16941 // is a better option than rejecting programs using those unions under
16942 // ARC.
16943 FD->addAttr(UnavailableAttr::CreateImplicit(
16944 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16945 FD->getLocation()));
16946 } else if (getLangOpts().ObjC &&
16947 getLangOpts().getGC() != LangOptions::NonGC &&
16948 Record && !Record->hasObjectMember()) {
16949 if (FD->getType()->isObjCObjectPointerType() ||
16950 FD->getType().isObjCGCStrong())
16951 Record->setHasObjectMember(true);
16952 else if (Context.getAsArrayType(FD->getType())) {
16953 QualType BaseType = Context.getBaseElementType(FD->getType());
16954 if (BaseType->isRecordType() &&
16955 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16956 Record->setHasObjectMember(true);
16957 else if (BaseType->isObjCObjectPointerType() ||
16958 BaseType.isObjCGCStrong())
16959 Record->setHasObjectMember(true);
16960 }
16961 }
16962
16963 if (Record && !getLangOpts().CPlusPlus &&
16964 !shouldIgnoreForRecordTriviality(FD)) {
16965 QualType FT = FD->getType();
16966 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16967 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16968 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16969 Record->isUnion())
16970 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16971 }
16972 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16973 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16974 Record->setNonTrivialToPrimitiveCopy(true);
16975 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16976 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16977 }
16978 if (FT.isDestructedType()) {
16979 Record->setNonTrivialToPrimitiveDestroy(true);
16980 Record->setParamDestroyedInCallee(true);
16981 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16982 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16983 }
16984
16985 if (const auto *RT = FT->getAs<RecordType>()) {
16986 if (RT->getDecl()->getArgPassingRestrictions() ==
16987 RecordDecl::APK_CanNeverPassInRegs)
16988 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16989 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16990 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16991 }
16992
16993 if (Record && FD->getType().isVolatileQualified())
16994 Record->setHasVolatileMember(true);
16995 // Keep track of the number of named members.
16996 if (FD->getIdentifier())
16997 ++NumNamedMembers;
16998 }
16999
17000 // Okay, we successfully defined 'Record'.
17001 if (Record) {
17002 bool Completed = false;
17003 if (CXXRecord) {
17004 if (!CXXRecord->isInvalidDecl()) {
17005 // Set access bits correctly on the directly-declared conversions.
17006 for (CXXRecordDecl::conversion_iterator
17007 I = CXXRecord->conversion_begin(),
17008 E = CXXRecord->conversion_end(); I != E; ++I)
17009 I.setAccess((*I)->getAccess());
17010 }
17011
17012 if (!CXXRecord->isDependentType()) {
17013 // Add any implicitly-declared members to this class.
17014 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17015
17016 if (!CXXRecord->isInvalidDecl()) {
17017 // If we have virtual base classes, we may end up finding multiple
17018 // final overriders for a given virtual function. Check for this
17019 // problem now.
17020 if (CXXRecord->getNumVBases()) {
17021 CXXFinalOverriderMap FinalOverriders;
17022 CXXRecord->getFinalOverriders(FinalOverriders);
17023
17024 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17025 MEnd = FinalOverriders.end();
17026 M != MEnd; ++M) {
17027 for (OverridingMethods::iterator SO = M->second.begin(),
17028 SOEnd = M->second.end();
17029 SO != SOEnd; ++SO) {
17030 assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17031, __PRETTY_FUNCTION__))
17031 "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17031, __PRETTY_FUNCTION__))
;
17032 if (SO->second.size() == 1)
17033 continue;
17034
17035 // C++ [class.virtual]p2:
17036 // In a derived class, if a virtual member function of a base
17037 // class subobject has more than one final overrider the
17038 // program is ill-formed.
17039 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17040 << (const NamedDecl *)M->first << Record;
17041 Diag(M->first->getLocation(),
17042 diag::note_overridden_virtual_function);
17043 for (OverridingMethods::overriding_iterator
17044 OM = SO->second.begin(),
17045 OMEnd = SO->second.end();
17046 OM != OMEnd; ++OM)
17047 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17048 << (const NamedDecl *)M->first << OM->Method->getParent();
17049
17050 Record->setInvalidDecl();
17051 }
17052 }
17053 CXXRecord->completeDefinition(&FinalOverriders);
17054 Completed = true;
17055 }
17056 }
17057 }
17058 }
17059
17060 if (!Completed)
17061 Record->completeDefinition();
17062
17063 // Handle attributes before checking the layout.
17064 ProcessDeclAttributeList(S, Record, Attrs);
17065
17066 // We may have deferred checking for a deleted destructor. Check now.
17067 if (CXXRecord) {
17068 auto *Dtor = CXXRecord->getDestructor();
17069 if (Dtor && Dtor->isImplicit() &&
17070 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17071 CXXRecord->setImplicitDestructorIsDeleted();
17072 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17073 }
17074 }
17075
17076 if (Record->hasAttrs()) {
17077 CheckAlignasUnderalignment(Record);
17078
17079 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17080 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17081 IA->getRange(), IA->getBestCase(),
17082 IA->getInheritanceModel());
17083 }
17084
17085 // Check if the structure/union declaration is a type that can have zero
17086 // size in C. For C this is a language extension, for C++ it may cause
17087 // compatibility problems.
17088 bool CheckForZeroSize;
17089 if (!getLangOpts().CPlusPlus) {
17090 CheckForZeroSize = true;
17091 } else {
17092 // For C++ filter out types that cannot be referenced in C code.
17093 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17094 CheckForZeroSize =
17095 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17096 !CXXRecord->isDependentType() &&
17097 CXXRecord->isCLike();
17098 }
17099 if (CheckForZeroSize) {
17100 bool ZeroSize = true;
17101 bool IsEmpty = true;
17102 unsigned NonBitFields = 0;
17103 for (RecordDecl::field_iterator I = Record->field_begin(),
17104 E = Record->field_end();
17105 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17106 IsEmpty = false;
17107 if (I->isUnnamedBitfield()) {
17108 if (!I->isZeroLengthBitField(Context))
17109 ZeroSize = false;
17110 } else {
17111 ++NonBitFields;
17112 QualType FieldType = I->getType();
17113 if (FieldType->isIncompleteType() ||
17114 !Context.getTypeSizeInChars(FieldType).isZero())
17115 ZeroSize = false;
17116 }
17117 }
17118
17119 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17120 // allowed in C++, but warn if its declaration is inside
17121 // extern "C" block.
17122 if (ZeroSize) {
17123 Diag(RecLoc, getLangOpts().CPlusPlus ?
17124 diag::warn_zero_size_struct_union_in_extern_c :
17125 diag::warn_zero_size_struct_union_compat)
17126 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17127 }
17128
17129 // Structs without named members are extension in C (C99 6.7.2.1p7),
17130 // but are accepted by GCC.
17131 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17132 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17133 diag::ext_no_named_members_in_struct_union)
17134 << Record->isUnion();
17135 }
17136 }
17137 } else {
17138 ObjCIvarDecl **ClsFields =
17139 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17140 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17141 ID->setEndOfDefinitionLoc(RBrac);
17142 // Add ivar's to class's DeclContext.
17143 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17144 ClsFields[i]->setLexicalDeclContext(ID);
17145 ID->addDecl(ClsFields[i]);
17146 }
17147 // Must enforce the rule that ivars in the base classes may not be
17148 // duplicates.
17149 if (ID->getSuperClass())
17150 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17151 } else if (ObjCImplementationDecl *IMPDecl =
17152 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17153 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17153, __PRETTY_FUNCTION__))
;
17154 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17155 // Ivar declared in @implementation never belongs to the implementation.
17156 // Only it is in implementation's lexical context.
17157 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17158 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17159 IMPDecl->setIvarLBraceLoc(LBrac);
17160 IMPDecl->setIvarRBraceLoc(RBrac);
17161 } else if (ObjCCategoryDecl *CDecl =
17162 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17163 // case of ivars in class extension; all other cases have been
17164 // reported as errors elsewhere.
17165 // FIXME. Class extension does not have a LocEnd field.
17166 // CDecl->setLocEnd(RBrac);
17167 // Add ivar's to class extension's DeclContext.
17168 // Diagnose redeclaration of private ivars.
17169 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17170 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17171 if (IDecl) {
17172 if (const ObjCIvarDecl *ClsIvar =
17173 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17174 Diag(ClsFields[i]->getLocation(),
17175 diag::err_duplicate_ivar_declaration);
17176 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17177 continue;
17178 }
17179 for (const auto *Ext : IDecl->known_extensions()) {
17180 if (const ObjCIvarDecl *ClsExtIvar
17181 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17182 Diag(ClsFields[i]->getLocation(),
17183 diag::err_duplicate_ivar_declaration);
17184 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17185 continue;
17186 }
17187 }
17188 }
17189 ClsFields[i]->setLexicalDeclContext(CDecl);
17190 CDecl->addDecl(ClsFields[i]);
17191 }
17192 CDecl->setIvarLBraceLoc(LBrac);
17193 CDecl->setIvarRBraceLoc(RBrac);
17194 }
17195 }
17196}
17197
17198/// Determine whether the given integral value is representable within
17199/// the given type T.
17200static bool isRepresentableIntegerValue(ASTContext &Context,
17201 llvm::APSInt &Value,
17202 QualType T) {
17203 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17204, __PRETTY_FUNCTION__))
17204 "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17204, __PRETTY_FUNCTION__))
;
17205 unsigned BitWidth = Context.getIntWidth(T);
17206
17207 if (Value.isUnsigned() || Value.isNonNegative()) {
17208 if (T->isSignedIntegerOrEnumerationType())
17209 --BitWidth;
17210 return Value.getActiveBits() <= BitWidth;
17211 }
17212 return Value.getMinSignedBits() <= BitWidth;
17213}
17214
17215// Given an integral type, return the next larger integral type
17216// (or a NULL type of no such type exists).
17217static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17218 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17219 // enum checking below.
17220 assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17221, __PRETTY_FUNCTION__))
17221 T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17221, __PRETTY_FUNCTION__))
;
17222 const unsigned NumTypes = 4;
17223 QualType SignedIntegralTypes[NumTypes] = {
17224 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17225 };
17226 QualType UnsignedIntegralTypes[NumTypes] = {
17227 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17228 Context.UnsignedLongLongTy
17229 };
17230
17231 unsigned BitWidth = Context.getTypeSize(T);
17232 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17233 : UnsignedIntegralTypes;
17234 for (unsigned I = 0; I != NumTypes; ++I)
17235 if (Context.getTypeSize(Types[I]) > BitWidth)
17236 return Types[I];
17237
17238 return QualType();
17239}
17240
17241EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17242 EnumConstantDecl *LastEnumConst,
17243 SourceLocation IdLoc,
17244 IdentifierInfo *Id,
17245 Expr *Val) {
17246 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17247 llvm::APSInt EnumVal(IntWidth);
17248 QualType EltTy;
17249
17250 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17251 Val = nullptr;
17252
17253 if (Val)
17254 Val = DefaultLvalueConversion(Val).get();
17255
17256 if (Val) {
17257 if (Enum->isDependentType() || Val->isTypeDependent())
17258 EltTy = Context.DependentTy;
17259 else {
17260 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17261 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17262 // constant-expression in the enumerator-definition shall be a converted
17263 // constant expression of the underlying type.
17264 EltTy = Enum->getIntegerType();
17265 ExprResult Converted =
17266 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17267 CCEK_Enumerator);
17268 if (Converted.isInvalid())
17269 Val = nullptr;
17270 else
17271 Val = Converted.get();
17272 } else if (!Val->isValueDependent() &&
17273 !(Val = VerifyIntegerConstantExpression(Val,
17274 &EnumVal).get())) {
17275 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17276 } else {
17277 if (Enum->isComplete()) {
17278 EltTy = Enum->getIntegerType();
17279
17280 // In Obj-C and Microsoft mode, require the enumeration value to be
17281 // representable in the underlying type of the enumeration. In C++11,
17282 // we perform a non-narrowing conversion as part of converted constant
17283 // expression checking.
17284 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17285 if (Context.getTargetInfo()
17286 .getTriple()
17287 .isWindowsMSVCEnvironment()) {
17288 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17289 } else {
17290 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17291 }
17292 }
17293
17294 // Cast to the underlying type.
17295 Val = ImpCastExprToType(Val, EltTy,
17296 EltTy->isBooleanType() ? CK_IntegralToBoolean
17297 : CK_IntegralCast)
17298 .get();
17299 } else if (getLangOpts().CPlusPlus) {
17300 // C++11 [dcl.enum]p5:
17301 // If the underlying type is not fixed, the type of each enumerator
17302 // is the type of its initializing value:
17303 // - If an initializer is specified for an enumerator, the
17304 // initializing value has the same type as the expression.
17305 EltTy = Val->getType();
17306 } else {
17307 // C99 6.7.2.2p2:
17308 // The expression that defines the value of an enumeration constant
17309 // shall be an integer constant expression that has a value
17310 // representable as an int.
17311
17312 // Complain if the value is not representable in an int.
17313 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17314 Diag(IdLoc, diag::ext_enum_value_not_int)
17315 << EnumVal.toString(10) << Val->getSourceRange()
17316 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17317 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17318 // Force the type of the expression to 'int'.
17319 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17320 }
17321 EltTy = Val->getType();
17322 }
17323 }
17324 }
17325 }
17326
17327 if (!Val) {
17328 if (Enum->isDependentType())
17329 EltTy = Context.DependentTy;
17330 else if (!LastEnumConst) {
17331 // C++0x [dcl.enum]p5:
17332 // If the underlying type is not fixed, the type of each enumerator
17333 // is the type of its initializing value:
17334 // - If no initializer is specified for the first enumerator, the
17335 // initializing value has an unspecified integral type.
17336 //
17337 // GCC uses 'int' for its unspecified integral type, as does
17338 // C99 6.7.2.2p3.
17339 if (Enum->isFixed()) {
17340 EltTy = Enum->getIntegerType();
17341 }
17342 else {
17343 EltTy = Context.IntTy;
17344 }
17345 } else {
17346 // Assign the last value + 1.
17347 EnumVal = LastEnumConst->getInitVal();
17348 ++EnumVal;
17349 EltTy = LastEnumConst->getType();
17350
17351 // Check for overflow on increment.
17352 if (EnumVal < LastEnumConst->getInitVal()) {
17353 // C++0x [dcl.enum]p5:
17354 // If the underlying type is not fixed, the type of each enumerator
17355 // is the type of its initializing value:
17356 //
17357 // - Otherwise the type of the initializing value is the same as
17358 // the type of the initializing value of the preceding enumerator
17359 // unless the incremented value is not representable in that type,
17360 // in which case the type is an unspecified integral type
17361 // sufficient to contain the incremented value. If no such type
17362 // exists, the program is ill-formed.
17363 QualType T = getNextLargerIntegralType(Context, EltTy);
17364 if (T.isNull() || Enum->isFixed()) {
17365 // There is no integral type larger enough to represent this
17366 // value. Complain, then allow the value to wrap around.
17367 EnumVal = LastEnumConst->getInitVal();
17368 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17369 ++EnumVal;
17370 if (Enum->isFixed())
17371 // When the underlying type is fixed, this is ill-formed.
17372 Diag(IdLoc, diag::err_enumerator_wrapped)
17373 << EnumVal.toString(10)
17374 << EltTy;
17375 else
17376 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17377 << EnumVal.toString(10);
17378 } else {
17379 EltTy = T;
17380 }
17381
17382 // Retrieve the last enumerator's value, extent that type to the
17383 // type that is supposed to be large enough to represent the incremented
17384 // value, then increment.
17385 EnumVal = LastEnumConst->getInitVal();
17386 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17387 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17388 ++EnumVal;
17389
17390 // If we're not in C++, diagnose the overflow of enumerator values,
17391 // which in C99 means that the enumerator value is not representable in
17392 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17393 // permits enumerator values that are representable in some larger
17394 // integral type.
17395 if (!getLangOpts().CPlusPlus && !T.isNull())
17396 Diag(IdLoc, diag::warn_enum_value_overflow);
17397 } else if (!getLangOpts().CPlusPlus &&
17398 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17399 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17400 Diag(IdLoc, diag::ext_enum_value_not_int)
17401 << EnumVal.toString(10) << 1;
17402 }
17403 }
17404 }
17405
17406 if (!EltTy->isDependentType()) {
17407 // Make the enumerator value match the signedness and size of the
17408 // enumerator's type.
17409 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17410 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17411 }
17412
17413 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17414 Val, EnumVal);
17415}
17416
17417Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17418 SourceLocation IILoc) {
17419 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17420 !getLangOpts().CPlusPlus)
17421 return SkipBodyInfo();
17422
17423 // We have an anonymous enum definition. Look up the first enumerator to
17424 // determine if we should merge the definition with an existing one and
17425 // skip the body.
17426 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17427 forRedeclarationInCurContext());
17428 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17429 if (!PrevECD)
17430 return SkipBodyInfo();
17431
17432 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17433 NamedDecl *Hidden;
17434 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17435 SkipBodyInfo Skip;
17436 Skip.Previous = Hidden;
17437 return Skip;
17438 }
17439
17440 return SkipBodyInfo();
17441}
17442
17443Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17444 SourceLocation IdLoc, IdentifierInfo *Id,
17445 const ParsedAttributesView &Attrs,
17446 SourceLocation EqualLoc, Expr *Val) {
17447 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17448 EnumConstantDecl *LastEnumConst =
17449 cast_or_null<EnumConstantDecl>(lastEnumConst);
17450
17451 // The scope passed in may not be a decl scope. Zip up the scope tree until
17452 // we find one that is.
17453 S = getNonFieldDeclScope(S);
17454
17455 // Verify that there isn't already something declared with this name in this
17456 // scope.
17457 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17458 LookupName(R, S);
17459 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17460
17461 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17462 // Maybe we will complain about the shadowed template parameter.
17463 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17464 // Just pretend that we didn't see the previous declaration.
17465 PrevDecl = nullptr;
17466 }
17467
17468 // C++ [class.mem]p15:
17469 // If T is the name of a class, then each of the following shall have a name
17470 // different from T:
17471 // - every enumerator of every member of class T that is an unscoped
17472 // enumerated type
17473 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17474 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17475 DeclarationNameInfo(Id, IdLoc));
17476
17477 EnumConstantDecl *New =
17478 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17479 if (!New)
17480 return nullptr;
17481
17482 if (PrevDecl) {
17483 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17484 // Check for other kinds of shadowing not already handled.
17485 CheckShadow(New, PrevDecl, R);
17486 }
17487
17488 // When in C++, we may get a TagDecl with the same name; in this case the
17489 // enum constant will 'hide' the tag.
17490 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17491, __PRETTY_FUNCTION__))
17491 "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17491, __PRETTY_FUNCTION__))
;
17492 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17493 if (isa<EnumConstantDecl>(PrevDecl))
17494 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17495 else
17496 Diag(IdLoc, diag::err_redefinition) << Id;
17497 notePreviousDefinition(PrevDecl, IdLoc);
17498 return nullptr;
17499 }
17500 }
17501
17502 // Process attributes.
17503 ProcessDeclAttributeList(S, New, Attrs);
17504 AddPragmaAttributes(S, New);
17505
17506 // Register this decl in the current scope stack.
17507 New->setAccess(TheEnumDecl->getAccess());
17508 PushOnScopeChains(New, S);
17509
17510 ActOnDocumentableDecl(New);
17511
17512 return New;
17513}
17514
17515// Returns true when the enum initial expression does not trigger the
17516// duplicate enum warning. A few common cases are exempted as follows:
17517// Element2 = Element1
17518// Element2 = Element1 + 1
17519// Element2 = Element1 - 1
17520// Where Element2 and Element1 are from the same enum.
17521static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17522 Expr *InitExpr = ECD->getInitExpr();
17523 if (!InitExpr)
17524 return true;
17525 InitExpr = InitExpr->IgnoreImpCasts();
17526
17527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17528 if (!BO->isAdditiveOp())
17529 return true;
17530 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17531 if (!IL)
17532 return true;
17533 if (IL->getValue() != 1)
17534 return true;
17535
17536 InitExpr = BO->getLHS();
17537 }
17538
17539 // This checks if the elements are from the same enum.
17540 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17541 if (!DRE)
17542 return true;
17543
17544 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17545 if (!EnumConstant)
17546 return true;
17547
17548 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17549 Enum)
17550 return true;
17551
17552 return false;
17553}
17554
17555// Emits a warning when an element is implicitly set a value that
17556// a previous element has already been set to.
17557static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17558 EnumDecl *Enum, QualType EnumType) {
17559 // Avoid anonymous enums
17560 if (!Enum->getIdentifier())
17561 return;
17562
17563 // Only check for small enums.
17564 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17565 return;
17566
17567 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17568 return;
17569
17570 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17571 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17572
17573 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17574
17575 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17576 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17577
17578 // Use int64_t as a key to avoid needing special handling for map keys.
17579 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17580 llvm::APSInt Val = D->getInitVal();
17581 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17582 };
17583
17584 DuplicatesVector DupVector;
17585 ValueToVectorMap EnumMap;
17586
17587 // Populate the EnumMap with all values represented by enum constants without
17588 // an initializer.
17589 for (auto *Element : Elements) {
17590 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17591
17592 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17593 // this constant. Skip this enum since it may be ill-formed.
17594 if (!ECD) {
17595 return;
17596 }
17597
17598 // Constants with initalizers are handled in the next loop.
17599 if (ECD->getInitExpr())
17600 continue;
17601
17602 // Duplicate values are handled in the next loop.
17603 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17604 }
17605
17606 if (EnumMap.size() == 0)
17607 return;
17608
17609 // Create vectors for any values that has duplicates.
17610 for (auto *Element : Elements) {
17611 // The last loop returned if any constant was null.
17612 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17613 if (!ValidDuplicateEnum(ECD, Enum))
17614 continue;
17615
17616 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17617 if (Iter == EnumMap.end())
17618 continue;
17619
17620 DeclOrVector& Entry = Iter->second;
17621 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17622 // Ensure constants are different.
17623 if (D == ECD)
17624 continue;
17625
17626 // Create new vector and push values onto it.
17627 auto Vec = std::make_unique<ECDVector>();
17628 Vec->push_back(D);
17629 Vec->push_back(ECD);
17630
17631 // Update entry to point to the duplicates vector.
17632 Entry = Vec.get();
17633
17634 // Store the vector somewhere we can consult later for quick emission of
17635 // diagnostics.
17636 DupVector.emplace_back(std::move(Vec));
17637 continue;
17638 }
17639
17640 ECDVector *Vec = Entry.get<ECDVector*>();
17641 // Make sure constants are not added more than once.
17642 if (*Vec->begin() == ECD)
17643 continue;
17644
17645 Vec->push_back(ECD);
17646 }
17647
17648 // Emit diagnostics.
17649 for (const auto &Vec : DupVector) {
17650 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17650, __PRETTY_FUNCTION__))
;
17651
17652 // Emit warning for one enum constant.
17653 auto *FirstECD = Vec->front();
17654 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17655 << FirstECD << FirstECD->getInitVal().toString(10)
17656 << FirstECD->getSourceRange();
17657
17658 // Emit one note for each of the remaining enum constants with
17659 // the same value.
17660 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17661 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17662 << ECD << ECD->getInitVal().toString(10)
17663 << ECD->getSourceRange();
17664 }
17665}
17666
17667bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17668 bool AllowMask) const {
17669 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17669, __PRETTY_FUNCTION__))
;
17670 assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition"
) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17670, __PRETTY_FUNCTION__))
;
17671
17672 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17673 llvm::APInt &FlagBits = R.first->second;
17674
17675 if (R.second) {
17676 for (auto *E : ED->enumerators()) {
17677 const auto &EVal = E->getInitVal();
17678 // Only single-bit enumerators introduce new flag values.
17679 if (EVal.isPowerOf2())
17680 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17681 }
17682 }
17683
17684 // A value is in a flag enum if either its bits are a subset of the enum's
17685 // flag bits (the first condition) or we are allowing masks and the same is
17686 // true of its complement (the second condition). When masks are allowed, we
17687 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17688 //
17689 // While it's true that any value could be used as a mask, the assumption is
17690 // that a mask will have all of the insignificant bits set. Anything else is
17691 // likely a logic error.
17692 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17693 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17694}
17695
17696void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17697 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17698 const ParsedAttributesView &Attrs) {
17699 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17700 QualType EnumType = Context.getTypeDeclType(Enum);
17701
17702 ProcessDeclAttributeList(S, Enum, Attrs);
17703
17704 if (Enum->isDependentType()) {
17705 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17706 EnumConstantDecl *ECD =
17707 cast_or_null<EnumConstantDecl>(Elements[i]);
17708 if (!ECD) continue;
17709
17710 ECD->setType(EnumType);
17711 }
17712
17713 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17714 return;
17715 }
17716
17717 // TODO: If the result value doesn't fit in an int, it must be a long or long
17718 // long value. ISO C does not support this, but GCC does as an extension,
17719 // emit a warning.
17720 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17721 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17722 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17723
17724 // Verify that all the values are okay, compute the size of the values, and
17725 // reverse the list.
17726 unsigned NumNegativeBits = 0;
17727 unsigned NumPositiveBits = 0;
17728
17729 // Keep track of whether all elements have type int.
17730 bool AllElementsInt = true;
17731
17732 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17733 EnumConstantDecl *ECD =
17734 cast_or_null<EnumConstantDecl>(Elements[i]);
17735 if (!ECD) continue; // Already issued a diagnostic.
17736
17737 const llvm::APSInt &InitVal = ECD->getInitVal();
17738
17739 // Keep track of the size of positive and negative values.
17740 if (InitVal.isUnsigned() || InitVal.isNonNegative())
17741 NumPositiveBits = std::max(NumPositiveBits,
17742 (unsigned)InitVal.getActiveBits());
17743 else
17744 NumNegativeBits = std::max(NumNegativeBits,
17745 (unsigned)InitVal.getMinSignedBits());
17746
17747 // Keep track of whether every enum element has type int (very common).
17748 if (AllElementsInt)
17749 AllElementsInt = ECD->getType() == Context.IntTy;
17750 }
17751
17752 // Figure out the type that should be used for this enum.
17753 QualType BestType;
17754 unsigned BestWidth;
17755
17756 // C++0x N3000 [conv.prom]p3:
17757 // An rvalue of an unscoped enumeration type whose underlying
17758 // type is not fixed can be converted to an rvalue of the first
17759 // of the following types that can represent all the values of
17760 // the enumeration: int, unsigned int, long int, unsigned long
17761 // int, long long int, or unsigned long long int.
17762 // C99 6.4.4.3p2:
17763 // An identifier declared as an enumeration constant has type int.
17764 // The C99 rule is modified by a gcc extension
17765 QualType BestPromotionType;
17766
17767 bool Packed = Enum->hasAttr<PackedAttr>();
17768 // -fshort-enums is the equivalent to specifying the packed attribute on all
17769 // enum definitions.
17770 if (LangOpts.ShortEnums)
17771 Packed = true;
17772
17773 // If the enum already has a type because it is fixed or dictated by the
17774 // target, promote that type instead of analyzing the enumerators.
17775 if (Enum->isComplete()) {
17776 BestType = Enum->getIntegerType();
17777 if (BestType->isPromotableIntegerType())
17778 BestPromotionType = Context.getPromotedIntegerType(BestType);
17779 else
17780 BestPromotionType = BestType;
17781
17782 BestWidth = Context.getIntWidth(BestType);
17783 }
17784 else if (NumNegativeBits) {
17785 // If there is a negative value, figure out the smallest integer type (of
17786 // int/long/longlong) that fits.
17787 // If it's packed, check also if it fits a char or a short.
17788 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17789 BestType = Context.SignedCharTy;
17790 BestWidth = CharWidth;
17791 } else if (Packed && NumNegativeBits <= ShortWidth &&
17792 NumPositiveBits < ShortWidth) {
17793 BestType = Context.ShortTy;
17794 BestWidth = ShortWidth;
17795 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17796 BestType = Context.IntTy;
17797 BestWidth = IntWidth;
17798 } else {
17799 BestWidth = Context.getTargetInfo().getLongWidth();
17800
17801 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17802 BestType = Context.LongTy;
17803 } else {
17804 BestWidth = Context.getTargetInfo().getLongLongWidth();
17805
17806 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17807 Diag(Enum->getLocation(), diag::ext_enum_too_large);
17808 BestType = Context.LongLongTy;
17809 }
17810 }
17811 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17812 } else {
17813 // If there is no negative value, figure out the smallest type that fits
17814 // all of the enumerator values.
17815 // If it's packed, check also if it fits a char or a short.
17816 if (Packed && NumPositiveBits <= CharWidth) {
17817 BestType = Context.UnsignedCharTy;
17818 BestPromotionType = Context.IntTy;
17819 BestWidth = CharWidth;
17820 } else if (Packed && NumPositiveBits <= ShortWidth) {
17821 BestType = Context.UnsignedShortTy;
17822 BestPromotionType = Context.IntTy;
17823 BestWidth = ShortWidth;
17824 } else if (NumPositiveBits <= IntWidth) {
17825 BestType = Context.UnsignedIntTy;
17826 BestWidth = IntWidth;
17827 BestPromotionType
17828 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17829 ? Context.UnsignedIntTy : Context.IntTy;
17830 } else if (NumPositiveBits <=
17831 (BestWidth = Context.getTargetInfo().getLongWidth())) {
17832 BestType = Context.UnsignedLongTy;
17833 BestPromotionType
17834 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17835 ? Context.UnsignedLongTy : Context.LongTy;
17836 } else {
17837 BestWidth = Context.getTargetInfo().getLongLongWidth();
17838 assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17839, __PRETTY_FUNCTION__))
17839 "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp"
, 17839, __PRETTY_FUNCTION__))
;
17840 BestType = Context.UnsignedLongLongTy;
17841 BestPromotionType
17842 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17843 ? Context.UnsignedLongLongTy : Context.LongLongTy;
17844 }
17845 }
17846
17847 // Loop over all of the enumerator constants, changing their types to match
17848 // the type of the enum if needed.
17849 for (auto *D : Elements) {
17850 auto *ECD = cast_or_null<EnumConstantDecl>(D);
17851 if (!ECD) continue; // Already issued a diagnostic.
17852
17853 // Standard C says the enumerators have int type, but we allow, as an
17854 // extension, the enumerators to be larger than int size. If each
17855 // enumerator value fits in an int, type it as an int, otherwise type it the
17856 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
17857 // that X has type 'int', not 'unsigned'.
17858
17859 // Determine whether the value fits into an int.
17860 llvm::APSInt InitVal = ECD->getInitVal();
17861
17862 // If it fits into an integer type, force it. Otherwise force it to match
17863 // the enum decl type.
17864 QualType NewTy;
17865 unsigned NewWidth;
17866 bool NewSign;
17867 if (!getLangOpts().CPlusPlus &&
17868 !Enum->isFixed() &&
17869 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17870 NewTy = Context.IntTy;
17871 NewWidth = IntWidth;
17872 NewSign = true;
17873 } else if (ECD->getType() == BestType) {
17874 // Already the right type!
17875 if (getLangOpts().CPlusPlus)
17876 // C++ [dcl.enum]p4: Following the closing brace of an
17877 // enum-specifier, each enumerator has the type of its
17878 // enumeration.
17879 ECD->setType(EnumType);
17880 continue;
17881 } else {
17882 NewTy = BestType;
17883 NewWidth = BestWidth;
17884 NewSign = BestType->isSignedIntegerOrEnumerationType();
17885 }
17886
17887 // Adjust the APSInt value.
17888 InitVal = InitVal.extOrTrunc(NewWidth);
17889 InitVal.setIsSigned(NewSign);
17890 ECD->setInitVal(InitVal);
17891
17892 // Adjust the Expr initializer and type.
17893 if (ECD->getInitExpr() &&
17894 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17895 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17896 CK_IntegralCast,
17897 ECD->getInitExpr(),
17898 /*base paths*/ nullptr,
17899 VK_RValue));
17900 if (getLangOpts().CPlusPlus)
17901 // C++ [dcl.enum]p4: Following the closing brace of an
17902 // enum-specifier, each enumerator has the type of its
17903 // enumeration.
17904 ECD->setType(EnumType);
17905 else
17906 ECD->setType(NewTy);
17907 }
17908
17909 Enum->completeDefinition(BestType, BestPromotionType,
17910 NumPositiveBits, NumNegativeBits);
17911
17912 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17913
17914 if (Enum->isClosedFlag()) {
17915 for (Decl *D : Elements) {
17916 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17917 if (!ECD) continue; // Already issued a diagnostic.
17918
17919 llvm::APSInt InitVal = ECD->getInitVal();
17920 if (InitVal != 0 && !InitVal.isPowerOf2() &&
17921 !IsValueInFlagEnum(Enum, InitVal, true))
17922 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17923 << ECD << Enum;
17924 }
17925 }
17926
17927 // Now that the enum type is defined, ensure it's not been underaligned.
17928 if (Enum->hasAttrs())
17929 CheckAlignasUnderalignment(Enum);
17930}
17931
17932Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17933 SourceLocation StartLoc,
17934 SourceLocation EndLoc) {
17935 StringLiteral *AsmString = cast<StringLiteral>(expr);
17936
17937 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17938 AsmString, StartLoc,
17939 EndLoc);
17940 CurContext->addDecl(New);
17941 return New;
17942}
17943
17944void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17945 IdentifierInfo* AliasName,
17946 SourceLocation PragmaLoc,
17947 SourceLocation NameLoc,
17948 SourceLocation AliasNameLoc) {
17949 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17950 LookupOrdinaryName);
17951 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17952 AttributeCommonInfo::AS_Pragma);
17953 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17954 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17955
17956 // If a declaration that:
17957 // 1) declares a function or a variable
17958 // 2) has external linkage
17959 // already exists, add a label attribute to it.
17960 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17961 if (isDeclExternC(PrevDecl))
17962 PrevDecl->addAttr(Attr);
17963 else
17964 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17965 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17966 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17967 } else
17968 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17969}
17970
17971void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17972 SourceLocation PragmaLoc,
17973 SourceLocation NameLoc) {
17974 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17975
17976 if (PrevDecl) {
17977 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17978 } else {
17979 (void)WeakUndeclaredIdentifiers.insert(
17980 std::pair<IdentifierInfo*,WeakInfo>
17981 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17982 }
17983}
17984
17985void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17986 IdentifierInfo* AliasName,
17987 SourceLocation PragmaLoc,
17988 SourceLocation NameLoc,
17989 SourceLocation AliasNameLoc) {
17990 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17991 LookupOrdinaryName);
17992 WeakInfo W = WeakInfo(Name, NameLoc);
17993
17994 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17995 if (!PrevDecl->hasAttr<AliasAttr>())
17996 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17997 DeclApplyPragmaWeak(TUScope, ND, W);
17998 } else {
17999 (void)WeakUndeclaredIdentifiers.insert(
18000 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18001 }
18002}
18003
18004Decl *Sema::getObjCDeclContext() const {
18005 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18006}
18007
18008Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
18009 // Templates are emitted when they're instantiated.
18010 if (FD->isDependentContext())
18011 return FunctionEmissionStatus::TemplateDiscarded;
18012
18013 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18014 if (LangOpts.OpenMPIsDevice) {
18015 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18016 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18017 if (DevTy.hasValue()) {
18018 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18019 OMPES = FunctionEmissionStatus::OMPDiscarded;
18020 else if (DeviceKnownEmittedFns.count(FD) > 0)
18021 OMPES = FunctionEmissionStatus::Emitted;
18022 }
18023 } else if (LangOpts.OpenMP) {
18024 // In OpenMP 4.5 all the functions are host functions.
18025 if (LangOpts.OpenMP <= 45) {
18026 OMPES = FunctionEmissionStatus::Emitted;
18027 } else {
18028 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18029 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18030 // In OpenMP 5.0 or above, DevTy may be changed later by
18031 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18032 // having no value does not imply host. The emission status will be
18033 // checked again at the end of compilation unit.
18034 if (DevTy.hasValue()) {
18035 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18036 OMPES = FunctionEmissionStatus::OMPDiscarded;
18037 } else if (DeviceKnownEmittedFns.count(FD) > 0) {
18038 OMPES = FunctionEmissionStatus::Emitted;
18039 }
18040 }
18041 }
18042 }
18043 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18044 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18045 return OMPES;
18046
18047 if (LangOpts.CUDA) {
18048 // When compiling for device, host functions are never emitted. Similarly,
18049 // when compiling for host, device and global functions are never emitted.
18050 // (Technically, we do emit a host-side stub for global functions, but this
18051 // doesn't count for our purposes here.)
18052 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18053 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18054 return FunctionEmissionStatus::CUDADiscarded;
18055 if (!LangOpts.CUDAIsDevice &&
18056 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18057 return FunctionEmissionStatus::CUDADiscarded;
18058
18059 // Check whether this function is externally visible -- if so, it's
18060 // known-emitted.
18061 //
18062 // We have to check the GVA linkage of the function's *definition* -- if we
18063 // only have a declaration, we don't know whether or not the function will
18064 // be emitted, because (say) the definition could include "inline".
18065 FunctionDecl *Def = FD->getDefinition();
18066
18067 if (Def &&
18068 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18069 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18070 return FunctionEmissionStatus::Emitted;
18071 }
18072
18073 // Otherwise, the function is known-emitted if it's in our set of
18074 // known-emitted functions.
18075 return (DeviceKnownEmittedFns.count(FD) > 0)
18076 ? FunctionEmissionStatus::Emitted
18077 : FunctionEmissionStatus::Unknown;
18078}
18079
18080bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18081 // Host-side references to a __global__ function refer to the stub, so the
18082 // function itself is never emitted and therefore should not be marked.
18083 // If we have host fn calls kernel fn calls host+device, the HD function
18084 // does not get instantiated on the host. We model this by omitting at the
18085 // call to the kernel from the callgraph. This ensures that, when compiling
18086 // for host, only HD functions actually called from the host get marked as
18087 // known-emitted.
18088 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18089 IdentifyCUDATarget(Callee) == CFT_Global;
18090}

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base 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 and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TranslationUnitDecl;
70class UsingDirectiveDecl;
71
72/// Captures the result of checking the availability of a
73/// declaration.
74enum AvailabilityResult {
75 AR_Available = 0,
76 AR_NotYetIntroduced,
77 AR_Deprecated,
78 AR_Unavailable
79};
80
81/// Decl - This represents one declaration (or definition), e.g. a variable,
82/// typedef, function, struct, etc.
83///
84/// Note: There are objects tacked on before the *beginning* of Decl
85/// (and its subclasses) in its Decl::operator new(). Proper alignment
86/// of all subclasses (not requiring more than the alignment of Decl) is
87/// asserted in DeclBase.cpp.
88class alignas(8) Decl {
89public:
90 /// Lists the kind of concrete classes of Decl.
91 enum Kind {
92#define DECL(DERIVED, BASE) DERIVED,
93#define ABSTRACT_DECL(DECL)
94#define DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END,
96#define LAST_DECL_RANGE(BASE, START, END) \
97 first##BASE = START, last##BASE = END
98#include "clang/AST/DeclNodes.inc"
99 };
100
101 /// A placeholder type used to construct an empty shell of a
102 /// decl-derived type that will be filled in later (e.g., by some
103 /// deserialization method).
104 struct EmptyShell {};
105
106 /// IdentifierNamespace - The different namespaces in which
107 /// declarations may appear. According to C99 6.2.3, there are
108 /// four namespaces, labels, tags, members and ordinary
109 /// identifiers. C++ describes lookup completely differently:
110 /// certain lookups merely "ignore" certain kinds of declarations,
111 /// usually based on whether the declaration is of a type, etc.
112 ///
113 /// These are meant as bitmasks, so that searches in
114 /// C++ can look into the "tag" namespace during ordinary lookup.
115 ///
116 /// Decl currently provides 15 bits of IDNS bits.
117 enum IdentifierNamespace {
118 /// Labels, declared with 'x:' and referenced with 'goto x'.
119 IDNS_Label = 0x0001,
120
121 /// Tags, declared with 'struct foo;' and referenced with
122 /// 'struct foo'. All tags are also types. This is what
123 /// elaborated-type-specifiers look for in C.
124 /// This also contains names that conflict with tags in the
125 /// same scope but that are otherwise ordinary names (non-type
126 /// template parameters and indirect field declarations).
127 IDNS_Tag = 0x0002,
128
129 /// Types, declared with 'struct foo', typedefs, etc.
130 /// This is what elaborated-type-specifiers look for in C++,
131 /// but note that it's ill-formed to find a non-tag.
132 IDNS_Type = 0x0004,
133
134 /// Members, declared with object declarations within tag
135 /// definitions. In C, these can only be found by "qualified"
136 /// lookup in member expressions. In C++, they're found by
137 /// normal lookup.
138 IDNS_Member = 0x0008,
139
140 /// Namespaces, declared with 'namespace foo {}'.
141 /// Lookup for nested-name-specifiers find these.
142 IDNS_Namespace = 0x0010,
143
144 /// Ordinary names. In C, everything that's not a label, tag,
145 /// member, or function-local extern ends up here.
146 IDNS_Ordinary = 0x0020,
147
148 /// Objective C \@protocol.
149 IDNS_ObjCProtocol = 0x0040,
150
151 /// This declaration is a friend function. A friend function
152 /// declaration is always in this namespace but may also be in
153 /// IDNS_Ordinary if it was previously declared.
154 IDNS_OrdinaryFriend = 0x0080,
155
156 /// This declaration is a friend class. A friend class
157 /// declaration is always in this namespace but may also be in
158 /// IDNS_Tag|IDNS_Type if it was previously declared.
159 IDNS_TagFriend = 0x0100,
160
161 /// This declaration is a using declaration. A using declaration
162 /// *introduces* a number of other declarations into the current
163 /// scope, and those declarations use the IDNS of their targets,
164 /// but the actual using declarations go in this namespace.
165 IDNS_Using = 0x0200,
166
167 /// This declaration is a C++ operator declared in a non-class
168 /// context. All such operators are also in IDNS_Ordinary.
169 /// C++ lexical operator lookup looks for these.
170 IDNS_NonMemberOperator = 0x0400,
171
172 /// This declaration is a function-local extern declaration of a
173 /// variable or function. This may also be IDNS_Ordinary if it
174 /// has been declared outside any function. These act mostly like
175 /// invisible friend declarations, but are also visible to unqualified
176 /// lookup within the scope of the declaring function.
177 IDNS_LocalExtern = 0x0800,
178
179 /// This declaration is an OpenMP user defined reduction construction.
180 IDNS_OMPReduction = 0x1000,
181
182 /// This declaration is an OpenMP user defined mapper.
183 IDNS_OMPMapper = 0x2000,
184 };
185
186 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
187 /// parameter types in method declarations. Other than remembering
188 /// them and mangling them into the method's signature string, these
189 /// are ignored by the compiler; they are consumed by certain
190 /// remote-messaging frameworks.
191 ///
192 /// in, inout, and out are mutually exclusive and apply only to
193 /// method parameters. bycopy and byref are mutually exclusive and
194 /// apply only to method parameters (?). oneway applies only to
195 /// results. All of these expect their corresponding parameter to
196 /// have a particular type. None of this is currently enforced by
197 /// clang.
198 ///
199 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
200 enum ObjCDeclQualifier {
201 OBJC_TQ_None = 0x0,
202 OBJC_TQ_In = 0x1,
203 OBJC_TQ_Inout = 0x2,
204 OBJC_TQ_Out = 0x4,
205 OBJC_TQ_Bycopy = 0x8,
206 OBJC_TQ_Byref = 0x10,
207 OBJC_TQ_Oneway = 0x20,
208
209 /// The nullability qualifier is set when the nullability of the
210 /// result or parameter was expressed via a context-sensitive
211 /// keyword.
212 OBJC_TQ_CSNullability = 0x40
213 };
214
215 /// The kind of ownership a declaration has, for visibility purposes.
216 /// This enumeration is designed such that higher values represent higher
217 /// levels of name hiding.
218 enum class ModuleOwnershipKind : unsigned {
219 /// This declaration is not owned by a module.
220 Unowned,
221
222 /// This declaration has an owning module, but is globally visible
223 /// (typically because its owning module is visible and we know that
224 /// modules cannot later become hidden in this compilation).
225 /// After serialization and deserialization, this will be converted
226 /// to VisibleWhenImported.
227 Visible,
228
229 /// This declaration has an owning module, and is visible when that
230 /// module is imported.
231 VisibleWhenImported,
232
233 /// This declaration has an owning module, but is only visible to
234 /// lookups that occur within that module.
235 ModulePrivate
236 };
237
238protected:
239 /// The next declaration within the same lexical
240 /// DeclContext. These pointers form the linked list that is
241 /// traversed via DeclContext's decls_begin()/decls_end().
242 ///
243 /// The extra two bits are used for the ModuleOwnershipKind.
244 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
245
246private:
247 friend class DeclContext;
248
249 struct MultipleDC {
250 DeclContext *SemanticDC;
251 DeclContext *LexicalDC;
252 };
253
254 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
255 /// For declarations that don't contain C++ scope specifiers, it contains
256 /// the DeclContext where the Decl was declared.
257 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
258 /// with the context where it semantically belongs (SemanticDC) and the
259 /// context where it was lexically declared (LexicalDC).
260 /// e.g.:
261 ///
262 /// namespace A {
263 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
264 /// }
265 /// void A::f(); // SemanticDC == namespace 'A'
266 /// // LexicalDC == global namespace
267 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
268
269 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
270 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
271
272 MultipleDC *getMultipleDC() const {
273 return DeclCtx.get<MultipleDC*>();
274 }
275
276 DeclContext *getSemanticDC() const {
277 return DeclCtx.get<DeclContext*>();
278 }
279
280 /// Loc - The location of this decl.
281 SourceLocation Loc;
282
283 /// DeclKind - This indicates which class this is.
284 unsigned DeclKind : 7;
285
286 /// InvalidDecl - This indicates a semantic error occurred.
287 unsigned InvalidDecl : 1;
288
289 /// HasAttrs - This indicates whether the decl has attributes or not.
290 unsigned HasAttrs : 1;
291
292 /// Implicit - Whether this declaration was implicitly generated by
293 /// the implementation rather than explicitly written by the user.
294 unsigned Implicit : 1;
295
296 /// Whether this declaration was "used", meaning that a definition is
297 /// required.
298 unsigned Used : 1;
299
300 /// Whether this declaration was "referenced".
301 /// The difference with 'Used' is whether the reference appears in a
302 /// evaluated context or not, e.g. functions used in uninstantiated templates
303 /// are regarded as "referenced" but not "used".
304 unsigned Referenced : 1;
305
306 /// Whether this declaration is a top-level declaration (function,
307 /// global variable, etc.) that is lexically inside an objc container
308 /// definition.
309 unsigned TopLevelDeclInObjCContainer : 1;
310
311 /// Whether statistic collection is enabled.
312 static bool StatisticsEnabled;
313
314protected:
315 friend class ASTDeclReader;
316 friend class ASTDeclWriter;
317 friend class ASTNodeImporter;
318 friend class ASTReader;
319 friend class CXXClassMemberWrapper;
320 friend class LinkageComputer;
321 template<typename decl_type> friend class Redeclarable;
322
323 /// Access - Used by C++ decls for the access specifier.
324 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
325 unsigned Access : 2;
326
327 /// Whether this declaration was loaded from an AST file.
328 unsigned FromASTFile : 1;
329
330 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
331 unsigned IdentifierNamespace : 14;
332
333 /// If 0, we have not computed the linkage of this declaration.
334 /// Otherwise, it is the linkage + 1.
335 mutable unsigned CacheValidAndLinkage : 3;
336
337 /// Allocate memory for a deserialized declaration.
338 ///
339 /// This routine must be used to allocate memory for any declaration that is
340 /// deserialized from a module file.
341 ///
342 /// \param Size The size of the allocated object.
343 /// \param Ctx The context in which we will allocate memory.
344 /// \param ID The global ID of the deserialized declaration.
345 /// \param Extra The amount of extra space to allocate after the object.
346 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
347 std::size_t Extra = 0);
348
349 /// Allocate memory for a non-deserialized declaration.
350 void *operator new(std::size_t Size, const ASTContext &Ctx,
351 DeclContext *Parent, std::size_t Extra = 0);
352
353private:
354 bool AccessDeclContextSanity() const;
355
356 /// Get the module ownership kind to use for a local lexical child of \p DC,
357 /// which may be either a local or (rarely) an imported declaration.
358 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
359 if (DC) {
360 auto *D = cast<Decl>(DC);
361 auto MOK = D->getModuleOwnershipKind();
362 if (MOK != ModuleOwnershipKind::Unowned &&
363 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
364 return MOK;
365 // If D is not local and we have no local module storage, then we don't
366 // need to track module ownership at all.
367 }
368 return ModuleOwnershipKind::Unowned;
369 }
370
371public:
372 Decl() = delete;
373 Decl(const Decl&) = delete;
374 Decl(Decl &&) = delete;
375 Decl &operator=(const Decl&) = delete;
376 Decl &operator=(Decl&&) = delete;
377
378protected:
379 Decl(Kind DK, DeclContext *DC, SourceLocation L)
380 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
381 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
382 Implicit(false), Used(false), Referenced(false),
383 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
384 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
385 CacheValidAndLinkage(0) {
386 if (StatisticsEnabled) add(DK);
387 }
388
389 Decl(Kind DK, EmptyShell Empty)
390 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
391 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
392 Access(AS_none), FromASTFile(0),
393 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
394 CacheValidAndLinkage(0) {
395 if (StatisticsEnabled) add(DK);
396 }
397
398 virtual ~Decl();
399
400 /// Update a potentially out-of-date declaration.
401 void updateOutOfDate(IdentifierInfo &II) const;
402
403 Linkage getCachedLinkage() const {
404 return Linkage(CacheValidAndLinkage - 1);
405 }
406
407 void setCachedLinkage(Linkage L) const {
408 CacheValidAndLinkage = L + 1;
409 }
410
411 bool hasCachedLinkage() const {
412 return CacheValidAndLinkage;
413 }
414
415public:
416 /// Source range that this declaration covers.
417 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
418 return SourceRange(getLocation(), getLocation());
419 }
420
421 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
422 return getSourceRange().getBegin();
423 }
424
425 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
426 return getSourceRange().getEnd();
427 }
428
429 SourceLocation getLocation() const { return Loc; }
430 void setLocation(SourceLocation L) { Loc = L; }
431
432 Kind getKind() const { return static_cast<Kind>(DeclKind); }
433 const char *getDeclKindName() const;
434
435 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
436 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
437
438 DeclContext *getDeclContext() {
439 if (isInSemaDC())
440 return getSemanticDC();
441 return getMultipleDC()->SemanticDC;
442 }
443 const DeclContext *getDeclContext() const {
444 return const_cast<Decl*>(this)->getDeclContext();
445 }
446
447 /// Find the innermost non-closure ancestor of this declaration,
448 /// walking up through blocks, lambdas, etc. If that ancestor is
449 /// not a code context (!isFunctionOrMethod()), returns null.
450 ///
451 /// A declaration may be its own non-closure context.
452 Decl *getNonClosureContext();
453 const Decl *getNonClosureContext() const {
454 return const_cast<Decl*>(this)->getNonClosureContext();
455 }
456
457 TranslationUnitDecl *getTranslationUnitDecl();
458 const TranslationUnitDecl *getTranslationUnitDecl() const {
459 return const_cast<Decl*>(this)->getTranslationUnitDecl();
460 }
461
462 bool isInAnonymousNamespace() const;
463
464 bool isInStdNamespace() const;
465
466 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
467
468 void setAccess(AccessSpecifier AS) {
469 Access = AS;
470 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 470, __PRETTY_FUNCTION__))
;
471 }
472
473 AccessSpecifier getAccess() const {
474 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 474, __PRETTY_FUNCTION__))
;
475 return AccessSpecifier(Access);
476 }
477
478 /// Retrieve the access specifier for this declaration, even though
479 /// it may not yet have been properly set.
480 AccessSpecifier getAccessUnsafe() const {
481 return AccessSpecifier(Access);
482 }
483
484 bool hasAttrs() const { return HasAttrs; }
485
486 void setAttrs(const AttrVec& Attrs) {
487 return setAttrsImpl(Attrs, getASTContext());
488 }
489
490 AttrVec &getAttrs() {
491 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
492 }
493
494 const AttrVec &getAttrs() const;
495 void dropAttrs();
496 void addAttr(Attr *A);
497
498 using attr_iterator = AttrVec::const_iterator;
499 using attr_range = llvm::iterator_range<attr_iterator>;
500
501 attr_range attrs() const {
502 return attr_range(attr_begin(), attr_end());
503 }
504
505 attr_iterator attr_begin() const {
506 return hasAttrs() ? getAttrs().begin() : nullptr;
507 }
508 attr_iterator attr_end() const {
509 return hasAttrs() ? getAttrs().end() : nullptr;
510 }
511
512 template <typename T>
513 void dropAttr() {
514 if (!HasAttrs) return;
515
516 AttrVec &Vec = getAttrs();
517 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
518
519 if (Vec.empty())
520 HasAttrs = false;
521 }
522
523 template <typename T>
524 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
525 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
526 }
527
528 template <typename T>
529 specific_attr_iterator<T> specific_attr_begin() const {
530 return specific_attr_iterator<T>(attr_begin());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_end() const {
535 return specific_attr_iterator<T>(attr_end());
536 }
537
538 template<typename T> T *getAttr() const {
539 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
540 }
541
542 template<typename T> bool hasAttr() const {
543 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
44
Assuming the condition is true
45
Returning the value 1, which participates in a condition later
544 }
545
546 /// getMaxAlignment - return the maximum alignment specified by attributes
547 /// on this decl, 0 if there are none.
548 unsigned getMaxAlignment() const;
549
550 /// setInvalidDecl - Indicates the Decl had a semantic error. This
551 /// allows for graceful error recovery.
552 void setInvalidDecl(bool Invalid = true);
553 bool isInvalidDecl() const { return (bool) InvalidDecl; }
554
555 /// isImplicit - Indicates whether the declaration was implicitly
556 /// generated by the implementation. If false, this declaration
557 /// was written explicitly in the source code.
558 bool isImplicit() const { return Implicit; }
559 void setImplicit(bool I = true) { Implicit = I; }
560
561 /// Whether *any* (re-)declaration of the entity was used, meaning that
562 /// a definition is required.
563 ///
564 /// \param CheckUsedAttr When true, also consider the "used" attribute
565 /// (in addition to the "used" bit set by \c setUsed()) when determining
566 /// whether the function is used.
567 bool isUsed(bool CheckUsedAttr = true) const;
568
569 /// Set whether the declaration is used, in the sense of odr-use.
570 ///
571 /// This should only be used immediately after creating a declaration.
572 /// It intentionally doesn't notify any listeners.
573 void setIsUsed() { getCanonicalDecl()->Used = true; }
574
575 /// Mark the declaration used, in the sense of odr-use.
576 ///
577 /// This notifies any mutation listeners in addition to setting a bit
578 /// indicating the declaration is used.
579 void markUsed(ASTContext &C);
580
581 /// Whether any declaration of this entity was referenced.
582 bool isReferenced() const;
583
584 /// Whether this declaration was referenced. This should not be relied
585 /// upon for anything other than debugging.
586 bool isThisDeclarationReferenced() const { return Referenced; }
587
588 void setReferenced(bool R = true) { Referenced = R; }
589
590 /// Whether this declaration is a top-level declaration (function,
591 /// global variable, etc.) that is lexically inside an objc container
592 /// definition.
593 bool isTopLevelDeclInObjCContainer() const {
594 return TopLevelDeclInObjCContainer;
595 }
596
597 void setTopLevelDeclInObjCContainer(bool V = true) {
598 TopLevelDeclInObjCContainer = V;
599 }
600
601 /// Looks on this and related declarations for an applicable
602 /// external source symbol attribute.
603 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
604
605 /// Whether this declaration was marked as being private to the
606 /// module in which it was defined.
607 bool isModulePrivate() const {
608 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
609 }
610
611 /// Return true if this declaration has an attribute which acts as
612 /// definition of the entity, such as 'alias' or 'ifunc'.
613 bool hasDefiningAttr() const;
614
615 /// Return this declaration's defining attribute if it has one.
616 const Attr *getDefiningAttr() const;
617
618protected:
619 /// Specify that this declaration was marked as being private
620 /// to the module in which it was defined.
621 void setModulePrivate() {
622 // The module-private specifier has no effect on unowned declarations.
623 // FIXME: We should track this in some way for source fidelity.
624 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
625 return;
626 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
627 }
628
629 /// Set the owning module ID.
630 void setOwningModuleID(unsigned ID) {
631 assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration"
) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 631, __PRETTY_FUNCTION__))
;
632 *((unsigned*)this - 2) = ID;
633 }
634
635public:
636 /// Determine the availability of the given declaration.
637 ///
638 /// This routine will determine the most restrictive availability of
639 /// the given declaration (e.g., preferring 'unavailable' to
640 /// 'deprecated').
641 ///
642 /// \param Message If non-NULL and the result is not \c
643 /// AR_Available, will be set to a (possibly empty) message
644 /// describing why the declaration has not been introduced, is
645 /// deprecated, or is unavailable.
646 ///
647 /// \param EnclosingVersion The version to compare with. If empty, assume the
648 /// deployment target version.
649 ///
650 /// \param RealizedPlatform If non-NULL and the availability result is found
651 /// in an available attribute it will set to the platform which is written in
652 /// the available attribute.
653 AvailabilityResult
654 getAvailability(std::string *Message = nullptr,
655 VersionTuple EnclosingVersion = VersionTuple(),
656 StringRef *RealizedPlatform = nullptr) const;
657
658 /// Retrieve the version of the target platform in which this
659 /// declaration was introduced.
660 ///
661 /// \returns An empty version tuple if this declaration has no 'introduced'
662 /// availability attributes, or the version tuple that's specified in the
663 /// attribute otherwise.
664 VersionTuple getVersionIntroduced() const;
665
666 /// Determine whether this declaration is marked 'deprecated'.
667 ///
668 /// \param Message If non-NULL and the declaration is deprecated,
669 /// this will be set to the message describing why the declaration
670 /// was deprecated (which may be empty).
671 bool isDeprecated(std::string *Message = nullptr) const {
672 return getAvailability(Message) == AR_Deprecated;
673 }
674
675 /// Determine whether this declaration is marked 'unavailable'.
676 ///
677 /// \param Message If non-NULL and the declaration is unavailable,
678 /// this will be set to the message describing why the declaration
679 /// was made unavailable (which may be empty).
680 bool isUnavailable(std::string *Message = nullptr) const {
681 return getAvailability(Message) == AR_Unavailable;
682 }
683
684 /// Determine whether this is a weak-imported symbol.
685 ///
686 /// Weak-imported symbols are typically marked with the
687 /// 'weak_import' attribute, but may also be marked with an
688 /// 'availability' attribute where we're targing a platform prior to
689 /// the introduction of this feature.
690 bool isWeakImported() const;
691
692 /// Determines whether this symbol can be weak-imported,
693 /// e.g., whether it would be well-formed to add the weak_import
694 /// attribute.
695 ///
696 /// \param IsDefinition Set to \c true to indicate that this
697 /// declaration cannot be weak-imported because it has a definition.
698 bool canBeWeakImported(bool &IsDefinition) const;
699
700 /// Determine whether this declaration came from an AST file (such as
701 /// a precompiled header or module) rather than having been parsed.
702 bool isFromASTFile() const { return FromASTFile; }
703
704 /// Retrieve the global declaration ID associated with this
705 /// declaration, which specifies where this Decl was loaded from.
706 unsigned getGlobalID() const {
707 if (isFromASTFile())
708 return *((const unsigned*)this - 1);
709 return 0;
710 }
711
712 /// Retrieve the global ID of the module that owns this particular
713 /// declaration.
714 unsigned getOwningModuleID() const {
715 if (isFromASTFile())
716 return *((const unsigned*)this - 2);
717 return 0;
718 }
719
720private:
721 Module *getOwningModuleSlow() const;
722
723protected:
724 bool hasLocalOwningModuleStorage() const;
725
726public:
727 /// Get the imported owning module, if this decl is from an imported
728 /// (non-local) module.
729 Module *getImportedOwningModule() const {
730 if (!isFromASTFile() || !hasOwningModule())
731 return nullptr;
732
733 return getOwningModuleSlow();
734 }
735
736 /// Get the local owning module, if known. Returns nullptr if owner is
737 /// not yet known or declaration is not from a module.
738 Module *getLocalOwningModule() const {
739 if (isFromASTFile() || !hasOwningModule())
740 return nullptr;
741
742 assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 743, __PRETTY_FUNCTION__))
743 "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 743, __PRETTY_FUNCTION__))
;
744 return reinterpret_cast<Module *const *>(this)[-1];
745 }
746 void setLocalOwningModule(Module *M) {
747 assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
748 hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
749 "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
;
750 reinterpret_cast<Module **>(this)[-1] = M;
751 }
752
753 /// Is this declaration owned by some module?
754 bool hasOwningModule() const {
755 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
756 }
757
758 /// Get the module that owns this declaration (for visibility purposes).
759 Module *getOwningModule() const {
760 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
761 }
762
763 /// Get the module that owns this declaration for linkage purposes.
764 /// There only ever is such a module under the C++ Modules TS.
765 ///
766 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
767 /// all declarations in a global module fragment are unowned.
768 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
769
770 /// Determine whether this declaration might be hidden from name
771 /// lookup. Note that the declaration might be visible even if this returns
772 /// \c false, if the owning module is visible within the query context.
773 // FIXME: Rename this to make it clearer what it does.
774 bool isHidden() const {
775 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
776 }
777
778 /// Set that this declaration is globally visible, even if it came from a
779 /// module that is not visible.
780 void setVisibleDespiteOwningModule() {
781 if (isHidden())
782 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
783 }
784
785 /// Get the kind of module ownership for this declaration.
786 ModuleOwnershipKind getModuleOwnershipKind() const {
787 return NextInContextAndBits.getInt();
788 }
789
790 /// Set whether this declaration is hidden from name lookup.
791 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
792 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
793 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
794 !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
795 "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
;
796 NextInContextAndBits.setInt(MOK);
797 }
798
799 unsigned getIdentifierNamespace() const {
800 return IdentifierNamespace;
801 }
802
803 bool isInIdentifierNamespace(unsigned NS) const {
804 return getIdentifierNamespace() & NS;
805 }
806
807 static unsigned getIdentifierNamespaceForKind(Kind DK);
808
809 bool hasTagIdentifierNamespace() const {
810 return isTagIdentifierNamespace(getIdentifierNamespace());
811 }
812
813 static bool isTagIdentifierNamespace(unsigned NS) {
814 // TagDecls have Tag and Type set and may also have TagFriend.
815 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
816 }
817
818 /// getLexicalDeclContext - The declaration context where this Decl was
819 /// lexically declared (LexicalDC). May be different from
820 /// getDeclContext() (SemanticDC).
821 /// e.g.:
822 ///
823 /// namespace A {
824 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
825 /// }
826 /// void A::f(); // SemanticDC == namespace 'A'
827 /// // LexicalDC == global namespace
828 DeclContext *getLexicalDeclContext() {
829 if (isInSemaDC())
830 return getSemanticDC();
831 return getMultipleDC()->LexicalDC;
832 }
833 const DeclContext *getLexicalDeclContext() const {
834 return const_cast<Decl*>(this)->getLexicalDeclContext();
835 }
836
837 /// Determine whether this declaration is declared out of line (outside its
838 /// semantic context).
839 virtual bool isOutOfLine() const;
840
841 /// setDeclContext - Set both the semantic and lexical DeclContext
842 /// to DC.
843 void setDeclContext(DeclContext *DC);
844
845 void setLexicalDeclContext(DeclContext *DC);
846
847 /// Determine whether this declaration is a templated entity (whether it is
848 // within the scope of a template parameter).
849 bool isTemplated() const;
850
851 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
852 /// scoped decl is defined outside the current function or method. This is
853 /// roughly global variables and functions, but also handles enums (which
854 /// could be defined inside or outside a function etc).
855 bool isDefinedOutsideFunctionOrMethod() const {
856 return getParentFunctionOrMethod() == nullptr;
857 }
858
859 /// Returns true if this declaration lexically is inside a function.
860 /// It recognizes non-defining declarations as well as members of local
861 /// classes:
862 /// \code
863 /// void foo() { void bar(); }
864 /// void foo2() { class ABC { void bar(); }; }
865 /// \endcode
866 bool isLexicallyWithinFunctionOrMethod() const;
867
868 /// If this decl is defined inside a function/method/block it returns
869 /// the corresponding DeclContext, otherwise it returns null.
870 const DeclContext *getParentFunctionOrMethod() const;
871 DeclContext *getParentFunctionOrMethod() {
872 return const_cast<DeclContext*>(
873 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
874 }
875
876 /// Retrieves the "canonical" declaration of the given declaration.
877 virtual Decl *getCanonicalDecl() { return this; }
878 const Decl *getCanonicalDecl() const {
879 return const_cast<Decl*>(this)->getCanonicalDecl();
880 }
881
882 /// Whether this particular Decl is a canonical one.
883 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
884
885protected:
886 /// Returns the next redeclaration or itself if this is the only decl.
887 ///
888 /// Decl subclasses that can be redeclared should override this method so that
889 /// Decl::redecl_iterator can iterate over them.
890 virtual Decl *getNextRedeclarationImpl() { return this; }
891
892 /// Implementation of getPreviousDecl(), to be overridden by any
893 /// subclass that has a redeclaration chain.
894 virtual Decl *getPreviousDeclImpl() { return nullptr; }
895
896 /// Implementation of getMostRecentDecl(), to be overridden by any
897 /// subclass that has a redeclaration chain.
898 virtual Decl *getMostRecentDeclImpl() { return this; }
899
900public:
901 /// Iterates through all the redeclarations of the same decl.
902 class redecl_iterator {
903 /// Current - The current declaration.
904 Decl *Current = nullptr;
905 Decl *Starter;
906
907 public:
908 using value_type = Decl *;
909 using reference = const value_type &;
910 using pointer = const value_type *;
911 using iterator_category = std::forward_iterator_tag;
912 using difference_type = std::ptrdiff_t;
913
914 redecl_iterator() = default;
915 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
916
917 reference operator*() const { return Current; }
918 value_type operator->() const { return Current; }
919
920 redecl_iterator& operator++() {
921 assert(Current && "Advancing while iterator has reached end")((Current && "Advancing while iterator has reached end"
) ? static_cast<void> (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 921, __PRETTY_FUNCTION__))
;
922 // Get either previous decl or latest decl.
923 Decl *Next = Current->getNextRedeclarationImpl();
924 assert(Next && "Should return next redeclaration or itself, never null!")((Next && "Should return next redeclaration or itself, never null!"
) ? static_cast<void> (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 924, __PRETTY_FUNCTION__))
;
925 Current = (Next != Starter) ? Next : nullptr;
926 return *this;
927 }
928
929 redecl_iterator operator++(int) {
930 redecl_iterator tmp(*this);
931 ++(*this);
932 return tmp;
933 }
934
935 friend bool operator==(redecl_iterator x, redecl_iterator y) {
936 return x.Current == y.Current;
937 }
938
939 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
940 return x.Current != y.Current;
941 }
942 };
943
944 using redecl_range = llvm::iterator_range<redecl_iterator>;
945
946 /// Returns an iterator range for all the redeclarations of the same
947 /// decl. It will iterate at least once (when this decl is the only one).
948 redecl_range redecls() const {
949 return redecl_range(redecls_begin(), redecls_end());
950 }
951
952 redecl_iterator redecls_begin() const {
953 return redecl_iterator(const_cast<Decl *>(this));
954 }
955
956 redecl_iterator redecls_end() const { return redecl_iterator(); }
957
958 /// Retrieve the previous declaration that declares the same entity
959 /// as this declaration, or NULL if there is no previous declaration.
960 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
961
962 /// Retrieve the previous declaration that declares the same entity
963 /// as this declaration, or NULL if there is no previous declaration.
964 const Decl *getPreviousDecl() const {
965 return const_cast<Decl *>(this)->getPreviousDeclImpl();
966 }
967
968 /// True if this is the first declaration in its redeclaration chain.
969 bool isFirstDecl() const {
970 return getPreviousDecl() == nullptr;
971 }
972
973 /// Retrieve the most recent declaration that declares the same entity
974 /// as this declaration (which may be this declaration).
975 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
976
977 /// Retrieve the most recent declaration that declares the same entity
978 /// as this declaration (which may be this declaration).
979 const Decl *getMostRecentDecl() const {
980 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
981 }
982
983 /// getBody - If this Decl represents a declaration for a body of code,
984 /// such as a function or method definition, this method returns the
985 /// top-level Stmt* of that body. Otherwise this method returns null.
986 virtual Stmt* getBody() const { return nullptr; }
987
988 /// Returns true if this \c Decl represents a declaration for a body of
989 /// code, such as a function or method definition.
990 /// Note that \c hasBody can also return true if any redeclaration of this
991 /// \c Decl represents a declaration for a body of code.
992 virtual bool hasBody() const { return getBody() != nullptr; }
993
994 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
995 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
996 SourceLocation getBodyRBrace() const;
997
998 // global temp stats (until we have a per-module visitor)
999 static void add(Kind k);
1000 static void EnableStatistics();
1001 static void PrintStats();
1002
1003 /// isTemplateParameter - Determines whether this declaration is a
1004 /// template parameter.
1005 bool isTemplateParameter() const;
1006
1007 /// isTemplateParameter - Determines whether this declaration is a
1008 /// template parameter pack.
1009 bool isTemplateParameterPack() const;
1010
1011 /// Whether this declaration is a parameter pack.
1012 bool isParameterPack() const;
1013
1014 /// returns true if this declaration is a template
1015 bool isTemplateDecl() const;
1016
1017 /// Whether this declaration is a function or function template.
1018 bool isFunctionOrFunctionTemplate() const {
1019 return (DeclKind >= Decl::firstFunction &&
1020 DeclKind <= Decl::lastFunction) ||
1021 DeclKind == FunctionTemplate;
1022 }
1023
1024 /// If this is a declaration that describes some template, this
1025 /// method returns that template declaration.
1026 TemplateDecl *getDescribedTemplate() const;
1027
1028 /// Returns the function itself, or the templated function if this is a
1029 /// function template.
1030 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1031
1032 const FunctionDecl *getAsFunction() const {
1033 return const_cast<Decl *>(this)->getAsFunction();
1034 }
1035
1036 /// Changes the namespace of this declaration to reflect that it's
1037 /// a function-local extern declaration.
1038 ///
1039 /// These declarations appear in the lexical context of the extern
1040 /// declaration, but in the semantic context of the enclosing namespace
1041 /// scope.
1042 void setLocalExternDecl() {
1043 Decl *Prev = getPreviousDecl();
1044 IdentifierNamespace &= ~IDNS_Ordinary;
1045
1046 // It's OK for the declaration to still have the "invisible friend" flag or
1047 // the "conflicts with tag declarations in this scope" flag for the outer
1048 // scope.
1049 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1050, __PRETTY_FUNCTION__))
1050 "namespace is not ordinary")(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1050, __PRETTY_FUNCTION__))
;
1051
1052 IdentifierNamespace |= IDNS_LocalExtern;
1053 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1054 IdentifierNamespace |= IDNS_Ordinary;
1055 }
1056
1057 /// Determine whether this is a block-scope declaration with linkage.
1058 /// This will either be a local variable declaration declared 'extern', or a
1059 /// local function declaration.
1060 bool isLocalExternDecl() {
1061 return IdentifierNamespace & IDNS_LocalExtern;
1062 }
1063
1064 /// Changes the namespace of this declaration to reflect that it's
1065 /// the object of a friend declaration.
1066 ///
1067 /// These declarations appear in the lexical context of the friending
1068 /// class, but in the semantic context of the actual entity. This property
1069 /// applies only to a specific decl object; other redeclarations of the
1070 /// same entity may not (and probably don't) share this property.
1071 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1072 unsigned OldNS = IdentifierNamespace;
1073 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1076, __PRETTY_FUNCTION__))
1074 IDNS_TagFriend | IDNS_OrdinaryFriend |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1076, __PRETTY_FUNCTION__))
1075 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1076, __PRETTY_FUNCTION__))
1076 "namespace includes neither ordinary nor tag")(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1076, __PRETTY_FUNCTION__))
;
1077 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1080, __PRETTY_FUNCTION__))
1078 IDNS_TagFriend | IDNS_OrdinaryFriend |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1080, __PRETTY_FUNCTION__))
1079 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1080, __PRETTY_FUNCTION__))
1080 "namespace includes other than ordinary or tag")((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1080, __PRETTY_FUNCTION__))
;
1081
1082 Decl *Prev = getPreviousDecl();
1083 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1084
1085 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1086 IdentifierNamespace |= IDNS_TagFriend;
1087 if (PerformFriendInjection ||
1088 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1089 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1090 }
1091
1092 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1093 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1094 IdentifierNamespace |= IDNS_OrdinaryFriend;
1095 if (PerformFriendInjection ||
1096 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1097 IdentifierNamespace |= IDNS_Ordinary;
1098 }
1099 }
1100
1101 enum FriendObjectKind {
1102 FOK_None, ///< Not a friend object.
1103 FOK_Declared, ///< A friend of a previously-declared entity.
1104 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1105 };
1106
1107 /// Determines whether this declaration is the object of a
1108 /// friend declaration and, if so, what kind.
1109 ///
1110 /// There is currently no direct way to find the associated FriendDecl.
1111 FriendObjectKind getFriendObjectKind() const {
1112 unsigned mask =
1113 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1114 if (!mask) return FOK_None;
1115 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1116 : FOK_Undeclared);
1117 }
1118
1119 /// Specifies that this declaration is a C++ overloaded non-member.
1120 void setNonMemberOperator() {
1121 assert(getKind() == Function || getKind() == FunctionTemplate)((getKind() == Function || getKind() == FunctionTemplate) ? static_cast
<void> (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1121, __PRETTY_FUNCTION__))
;
1122 assert((IdentifierNamespace & IDNS_Ordinary) &&(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1123, __PRETTY_FUNCTION__))
1123 "visible non-member operators should be in ordinary namespace")(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 1123, __PRETTY_FUNCTION__))
;
1124 IdentifierNamespace |= IDNS_NonMemberOperator;
1125 }
1126
1127 static bool classofKind(Kind K) { return true; }
1128 static DeclContext *castToDeclContext(const Decl *);
1129 static Decl *castFromDeclContext(const DeclContext *);
1130
1131 void print(raw_ostream &Out, unsigned Indentation = 0,
1132 bool PrintInstantiation = false) const;
1133 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1134 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1135 static void printGroup(Decl** Begin, unsigned NumDecls,
1136 raw_ostream &Out, const PrintingPolicy &Policy,
1137 unsigned Indentation = 0);
1138
1139 // Debuggers don't usually respect default arguments.
1140 void dump() const;
1141
1142 // Same as dump(), but forces color printing.
1143 void dumpColor() const;
1144
1145 void dump(raw_ostream &Out, bool Deserialize = false,
1146 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1147
1148 /// \return Unique reproducible object identifier
1149 int64_t getID() const;
1150
1151 /// Looks through the Decl's underlying type to extract a FunctionType
1152 /// when possible. Will return null if the type underlying the Decl does not
1153 /// have a FunctionType.
1154 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1155
1156private:
1157 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1158 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1159 ASTContext &Ctx);
1160
1161protected:
1162 ASTMutationListener *getASTMutationListener() const;
1163};
1164
1165/// Determine whether two declarations declare the same entity.
1166inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1167 if (!D1 || !D2)
1168 return false;
1169
1170 if (D1 == D2)
1171 return true;
1172
1173 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1174}
1175
1176/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1177/// doing something to a specific decl.
1178class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1179 const Decl *TheDecl;
1180 SourceLocation Loc;
1181 SourceManager &SM;
1182 const char *Message;
1183
1184public:
1185 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1186 SourceManager &sm, const char *Msg)
1187 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1188
1189 void print(raw_ostream &OS) const override;
1190};
1191
1192/// The results of name lookup within a DeclContext. This is either a
1193/// single result (with no stable storage) or a collection of results (with
1194/// stable storage provided by the lookup table).
1195class DeclContextLookupResult {
1196 using ResultTy = ArrayRef<NamedDecl *>;
1197
1198 ResultTy Result;
1199
1200 // If there is only one lookup result, it would be invalidated by
1201 // reallocations of the name table, so store it separately.
1202 NamedDecl *Single = nullptr;
1203
1204 static NamedDecl *const SingleElementDummyList;
1205
1206public:
1207 DeclContextLookupResult() = default;
1208 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1209 : Result(Result) {}
1210 DeclContextLookupResult(NamedDecl *Single)
1211 : Result(SingleElementDummyList), Single(Single) {}
1212
1213 class iterator;
1214
1215 using IteratorBase =
1216 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1217 std::random_access_iterator_tag,
1218 NamedDecl *const>;
1219
1220 class iterator : public IteratorBase {
1221 value_type SingleElement;
1222
1223 public:
1224 explicit iterator(pointer Pos, value_type Single = nullptr)
1225 : IteratorBase(Pos), SingleElement(Single) {}
1226
1227 reference operator*() const {
1228 return SingleElement ? SingleElement : IteratorBase::operator*();
1229 }
1230 };
1231
1232 using const_iterator = iterator;
1233 using pointer = iterator::pointer;
1234 using reference = iterator::reference;
1235
1236 iterator begin() const { return iterator(Result.begin(), Single); }
1237 iterator end() const { return iterator(Result.end(), Single); }
1238
1239 bool empty() const { return Result.empty(); }
1240 pointer data() const { return Single ? &Single : Result.data(); }
1241 size_t size() const { return Single ? 1 : Result.size(); }
1242 reference front() const { return Single ? Single : Result.front(); }
1243 reference back() const { return Single ? Single : Result.back(); }
1244 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1245
1246 // FIXME: Remove this from the interface
1247 DeclContextLookupResult slice(size_t N) const {
1248 DeclContextLookupResult Sliced = Result.slice(N);
1249 Sliced.Single = Single;
1250 return Sliced;
1251 }
1252};
1253
1254/// DeclContext - This is used only as base class of specific decl types that
1255/// can act as declaration contexts. These decls are (only the top classes
1256/// that directly derive from DeclContext are mentioned, not their subclasses):
1257///
1258/// TranslationUnitDecl
1259/// ExternCContext
1260/// NamespaceDecl
1261/// TagDecl
1262/// OMPDeclareReductionDecl
1263/// OMPDeclareMapperDecl
1264/// FunctionDecl
1265/// ObjCMethodDecl
1266/// ObjCContainerDecl
1267/// LinkageSpecDecl
1268/// ExportDecl
1269/// BlockDecl
1270/// CapturedDecl
1271class DeclContext {
1272 /// For makeDeclVisibleInContextImpl
1273 friend class ASTDeclReader;
1274 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1275 /// hasNeedToReconcileExternalVisibleStorage
1276 friend class ExternalASTSource;
1277 /// For CreateStoredDeclsMap
1278 friend class DependentDiagnostic;
1279 /// For hasNeedToReconcileExternalVisibleStorage,
1280 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1281 friend class ASTWriter;
1282
1283 // We use uint64_t in the bit-fields below since some bit-fields
1284 // cross the unsigned boundary and this breaks the packing.
1285
1286 /// Stores the bits used by DeclContext.
1287 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1288 /// methods in DeclContext should be updated appropriately.
1289 class DeclContextBitfields {
1290 friend class DeclContext;
1291 /// DeclKind - This indicates which class this is.
1292 uint64_t DeclKind : 7;
1293
1294 /// Whether this declaration context also has some external
1295 /// storage that contains additional declarations that are lexically
1296 /// part of this context.
1297 mutable uint64_t ExternalLexicalStorage : 1;
1298
1299 /// Whether this declaration context also has some external
1300 /// storage that contains additional declarations that are visible
1301 /// in this context.
1302 mutable uint64_t ExternalVisibleStorage : 1;
1303
1304 /// Whether this declaration context has had externally visible
1305 /// storage added since the last lookup. In this case, \c LookupPtr's
1306 /// invariant may not hold and needs to be fixed before we perform
1307 /// another lookup.
1308 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1309
1310 /// If \c true, this context may have local lexical declarations
1311 /// that are missing from the lookup table.
1312 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1313
1314 /// If \c true, the external source may have lexical declarations
1315 /// that are missing from the lookup table.
1316 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1317
1318 /// If \c true, lookups should only return identifier from
1319 /// DeclContext scope (for example TranslationUnit). Used in
1320 /// LookupQualifiedName()
1321 mutable uint64_t UseQualifiedLookup : 1;
1322 };
1323
1324 /// Number of bits in DeclContextBitfields.
1325 enum { NumDeclContextBits = 13 };
1326
1327 /// Stores the bits used by TagDecl.
1328 /// If modified NumTagDeclBits and the accessor
1329 /// methods in TagDecl should be updated appropriately.
1330 class TagDeclBitfields {
1331 friend class TagDecl;
1332 /// For the bits in DeclContextBitfields
1333 uint64_t : NumDeclContextBits;
1334
1335 /// The TagKind enum.
1336 uint64_t TagDeclKind : 3;
1337
1338 /// True if this is a definition ("struct foo {};"), false if it is a
1339 /// declaration ("struct foo;"). It is not considered a definition
1340 /// until the definition has been fully processed.
1341 uint64_t IsCompleteDefinition : 1;
1342
1343 /// True if this is currently being defined.
1344 uint64_t IsBeingDefined : 1;
1345
1346 /// True if this tag declaration is "embedded" (i.e., defined or declared
1347 /// for the very first time) in the syntax of a declarator.
1348 uint64_t IsEmbeddedInDeclarator : 1;
1349
1350 /// True if this tag is free standing, e.g. "struct foo;".
1351 uint64_t IsFreeStanding : 1;
1352
1353 /// Indicates whether it is possible for declarations of this kind
1354 /// to have an out-of-date definition.
1355 ///
1356 /// This option is only enabled when modules are enabled.
1357 uint64_t MayHaveOutOfDateDef : 1;
1358
1359 /// Has the full definition of this type been required by a use somewhere in
1360 /// the TU.
1361 uint64_t IsCompleteDefinitionRequired : 1;
1362 };
1363
1364 /// Number of non-inherited bits in TagDeclBitfields.
1365 enum { NumTagDeclBits = 9 };
1366
1367 /// Stores the bits used by EnumDecl.
1368 /// If modified NumEnumDeclBit and the accessor
1369 /// methods in EnumDecl should be updated appropriately.
1370 class EnumDeclBitfields {
1371 friend class EnumDecl;
1372 /// For the bits in DeclContextBitfields.
1373 uint64_t : NumDeclContextBits;
1374 /// For the bits in TagDeclBitfields.
1375 uint64_t : NumTagDeclBits;
1376
1377 /// Width in bits required to store all the non-negative
1378 /// enumerators of this enum.
1379 uint64_t NumPositiveBits : 8;
1380
1381 /// Width in bits required to store all the negative
1382 /// enumerators of this enum.
1383 uint64_t NumNegativeBits : 8;
1384
1385 /// True if this tag declaration is a scoped enumeration. Only
1386 /// possible in C++11 mode.
1387 uint64_t IsScoped : 1;
1388
1389 /// If this tag declaration is a scoped enum,
1390 /// then this is true if the scoped enum was declared using the class
1391 /// tag, false if it was declared with the struct tag. No meaning is
1392 /// associated if this tag declaration is not a scoped enum.
1393 uint64_t IsScopedUsingClassTag : 1;
1394
1395 /// True if this is an enumeration with fixed underlying type. Only
1396 /// possible in C++11, Microsoft extensions, or Objective C mode.
1397 uint64_t IsFixed : 1;
1398
1399 /// True if a valid hash is stored in ODRHash.
1400 uint64_t HasODRHash : 1;
1401 };
1402
1403 /// Number of non-inherited bits in EnumDeclBitfields.
1404 enum { NumEnumDeclBits = 20 };
1405
1406 /// Stores the bits used by RecordDecl.
1407 /// If modified NumRecordDeclBits and the accessor
1408 /// methods in RecordDecl should be updated appropriately.
1409 class RecordDeclBitfields {
1410 friend class RecordDecl;
1411 /// For the bits in DeclContextBitfields.
1412 uint64_t : NumDeclContextBits;
1413 /// For the bits in TagDeclBitfields.
1414 uint64_t : NumTagDeclBits;
1415
1416 /// This is true if this struct ends with a flexible
1417 /// array member (e.g. int X[]) or if this union contains a struct that does.
1418 /// If so, this cannot be contained in arrays or other structs as a member.
1419 uint64_t HasFlexibleArrayMember : 1;
1420
1421 /// Whether this is the type of an anonymous struct or union.
1422 uint64_t AnonymousStructOrUnion : 1;
1423
1424 /// This is true if this struct has at least one member
1425 /// containing an Objective-C object pointer type.
1426 uint64_t HasObjectMember : 1;
1427
1428 /// This is true if struct has at least one member of
1429 /// 'volatile' type.
1430 uint64_t HasVolatileMember : 1;
1431
1432 /// Whether the field declarations of this record have been loaded
1433 /// from external storage. To avoid unnecessary deserialization of
1434 /// methods/nested types we allow deserialization of just the fields
1435 /// when needed.
1436 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1437
1438 /// Basic properties of non-trivial C structs.
1439 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1440 uint64_t NonTrivialToPrimitiveCopy : 1;
1441 uint64_t NonTrivialToPrimitiveDestroy : 1;
1442
1443 /// The following bits indicate whether this is or contains a C union that
1444 /// is non-trivial to default-initialize, destruct, or copy. These bits
1445 /// imply the associated basic non-triviality predicates declared above.
1446 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1447 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1448 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1449
1450 /// Indicates whether this struct is destroyed in the callee.
1451 uint64_t ParamDestroyedInCallee : 1;
1452
1453 /// Represents the way this type is passed to a function.
1454 uint64_t ArgPassingRestrictions : 2;
1455 };
1456
1457 /// Number of non-inherited bits in RecordDeclBitfields.
1458 enum { NumRecordDeclBits = 14 };
1459
1460 /// Stores the bits used by OMPDeclareReductionDecl.
1461 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1462 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1463 class OMPDeclareReductionDeclBitfields {
1464 friend class OMPDeclareReductionDecl;
1465 /// For the bits in DeclContextBitfields
1466 uint64_t : NumDeclContextBits;
1467
1468 /// Kind of initializer,
1469 /// function call or omp_priv<init_expr> initializtion.
1470 uint64_t InitializerKind : 2;
1471 };
1472
1473 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1474 enum { NumOMPDeclareReductionDeclBits = 2 };
1475
1476 /// Stores the bits used by FunctionDecl.
1477 /// If modified NumFunctionDeclBits and the accessor
1478 /// methods in FunctionDecl and CXXDeductionGuideDecl
1479 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1480 class FunctionDeclBitfields {
1481 friend class FunctionDecl;
1482 /// For IsCopyDeductionCandidate
1483 friend class CXXDeductionGuideDecl;
1484 /// For the bits in DeclContextBitfields.
1485 uint64_t : NumDeclContextBits;
1486
1487 uint64_t SClass : 3;
1488 uint64_t IsInline : 1;
1489 uint64_t IsInlineSpecified : 1;
1490
1491 uint64_t IsVirtualAsWritten : 1;
1492 uint64_t IsPure : 1;
1493 uint64_t HasInheritedPrototype : 1;
1494 uint64_t HasWrittenPrototype : 1;
1495 uint64_t IsDeleted : 1;
1496 /// Used by CXXMethodDecl
1497 uint64_t IsTrivial : 1;
1498
1499 /// This flag indicates whether this function is trivial for the purpose of
1500 /// calls. This is meaningful only when this function is a copy/move
1501 /// constructor or a destructor.
1502 uint64_t IsTrivialForCall : 1;
1503
1504 uint64_t IsDefaulted : 1;
1505 uint64_t IsExplicitlyDefaulted : 1;
1506 uint64_t HasDefaultedFunctionInfo : 1;
1507 uint64_t HasImplicitReturnZero : 1;
1508 uint64_t IsLateTemplateParsed : 1;
1509
1510 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1511 uint64_t ConstexprKind : 2;
1512 uint64_t InstantiationIsPending : 1;
1513
1514 /// Indicates if the function uses __try.
1515 uint64_t UsesSEHTry : 1;
1516
1517 /// Indicates if the function was a definition
1518 /// but its body was skipped.
1519 uint64_t HasSkippedBody : 1;
1520
1521 /// Indicates if the function declaration will
1522 /// have a body, once we're done parsing it.
1523 uint64_t WillHaveBody : 1;
1524
1525 /// Indicates that this function is a multiversioned
1526 /// function using attribute 'target'.
1527 uint64_t IsMultiVersion : 1;
1528
1529 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1530 /// the Deduction Guide is the implicitly generated 'copy
1531 /// deduction candidate' (is used during overload resolution).
1532 uint64_t IsCopyDeductionCandidate : 1;
1533
1534 /// Store the ODRHash after first calculation.
1535 uint64_t HasODRHash : 1;
1536
1537 /// Indicates if the function uses Floating Point Constrained Intrinsics
1538 uint64_t UsesFPIntrin : 1;
1539 };
1540
1541 /// Number of non-inherited bits in FunctionDeclBitfields.
1542 enum { NumFunctionDeclBits = 27 };
1543
1544 /// Stores the bits used by CXXConstructorDecl. If modified
1545 /// NumCXXConstructorDeclBits and the accessor
1546 /// methods in CXXConstructorDecl should be updated appropriately.
1547 class CXXConstructorDeclBitfields {
1548 friend class CXXConstructorDecl;
1549 /// For the bits in DeclContextBitfields.
1550 uint64_t : NumDeclContextBits;
1551 /// For the bits in FunctionDeclBitfields.
1552 uint64_t : NumFunctionDeclBits;
1553
1554 /// 24 bits to fit in the remaining available space.
1555 /// Note that this makes CXXConstructorDeclBitfields take
1556 /// exactly 64 bits and thus the width of NumCtorInitializers
1557 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1558 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1559 uint64_t NumCtorInitializers : 21;
1560 uint64_t IsInheritingConstructor : 1;
1561
1562 /// Whether this constructor has a trail-allocated explicit specifier.
1563 uint64_t HasTrailingExplicitSpecifier : 1;
1564 /// If this constructor does't have a trail-allocated explicit specifier.
1565 /// Whether this constructor is explicit specified.
1566 uint64_t IsSimpleExplicit : 1;
1567 };
1568
1569 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1570 enum {
1571 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1572 };
1573
1574 /// Stores the bits used by ObjCMethodDecl.
1575 /// If modified NumObjCMethodDeclBits and the accessor
1576 /// methods in ObjCMethodDecl should be updated appropriately.
1577 class ObjCMethodDeclBitfields {
1578 friend class ObjCMethodDecl;
1579
1580 /// For the bits in DeclContextBitfields.
1581 uint64_t : NumDeclContextBits;
1582
1583 /// The conventional meaning of this method; an ObjCMethodFamily.
1584 /// This is not serialized; instead, it is computed on demand and
1585 /// cached.
1586 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1587
1588 /// instance (true) or class (false) method.
1589 uint64_t IsInstance : 1;
1590 uint64_t IsVariadic : 1;
1591
1592 /// True if this method is the getter or setter for an explicit property.
1593 uint64_t IsPropertyAccessor : 1;
1594
1595 /// True if this method is a synthesized property accessor stub.
1596 uint64_t IsSynthesizedAccessorStub : 1;
1597
1598 /// Method has a definition.
1599 uint64_t IsDefined : 1;
1600
1601 /// Method redeclaration in the same interface.
1602 uint64_t IsRedeclaration : 1;
1603
1604 /// Is redeclared in the same interface.
1605 mutable uint64_t HasRedeclaration : 1;
1606
1607 /// \@required/\@optional
1608 uint64_t DeclImplementation : 2;
1609
1610 /// in, inout, etc.
1611 uint64_t objcDeclQualifier : 7;
1612
1613 /// Indicates whether this method has a related result type.
1614 uint64_t RelatedResultType : 1;
1615
1616 /// Whether the locations of the selector identifiers are in a
1617 /// "standard" position, a enum SelectorLocationsKind.
1618 uint64_t SelLocsKind : 2;
1619
1620 /// Whether this method overrides any other in the class hierarchy.
1621 ///
1622 /// A method is said to override any method in the class's
1623 /// base classes, its protocols, or its categories' protocols, that has
1624 /// the same selector and is of the same kind (class or instance).
1625 /// A method in an implementation is not considered as overriding the same
1626 /// method in the interface or its categories.
1627 uint64_t IsOverriding : 1;
1628
1629 /// Indicates if the method was a definition but its body was skipped.
1630 uint64_t HasSkippedBody : 1;
1631 };
1632
1633 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1634 enum { NumObjCMethodDeclBits = 24 };
1635
1636 /// Stores the bits used by ObjCContainerDecl.
1637 /// If modified NumObjCContainerDeclBits and the accessor
1638 /// methods in ObjCContainerDecl should be updated appropriately.
1639 class ObjCContainerDeclBitfields {
1640 friend class ObjCContainerDecl;
1641 /// For the bits in DeclContextBitfields
1642 uint32_t : NumDeclContextBits;
1643
1644 // Not a bitfield but this saves space.
1645 // Note that ObjCContainerDeclBitfields is full.
1646 SourceLocation AtStart;
1647 };
1648
1649 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1650 /// Note that here we rely on the fact that SourceLocation is 32 bits
1651 /// wide. We check this with the static_assert in the ctor of DeclContext.
1652 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1653
1654 /// Stores the bits used by LinkageSpecDecl.
1655 /// If modified NumLinkageSpecDeclBits and the accessor
1656 /// methods in LinkageSpecDecl should be updated appropriately.
1657 class LinkageSpecDeclBitfields {
1658 friend class LinkageSpecDecl;
1659 /// For the bits in DeclContextBitfields.
1660 uint64_t : NumDeclContextBits;
1661
1662 /// The language for this linkage specification with values
1663 /// in the enum LinkageSpecDecl::LanguageIDs.
1664 uint64_t Language : 3;
1665
1666 /// True if this linkage spec has braces.
1667 /// This is needed so that hasBraces() returns the correct result while the
1668 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1669 /// not used, so it doesn't need to be serialized.
1670 uint64_t HasBraces : 1;
1671 };
1672
1673 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1674 enum { NumLinkageSpecDeclBits = 4 };
1675
1676 /// Stores the bits used by BlockDecl.
1677 /// If modified NumBlockDeclBits and the accessor
1678 /// methods in BlockDecl should be updated appropriately.
1679 class BlockDeclBitfields {
1680 friend class BlockDecl;
1681 /// For the bits in DeclContextBitfields.
1682 uint64_t : NumDeclContextBits;
1683
1684 uint64_t IsVariadic : 1;
1685 uint64_t CapturesCXXThis : 1;
1686 uint64_t BlockMissingReturnType : 1;
1687 uint64_t IsConversionFromLambda : 1;
1688
1689 /// A bit that indicates this block is passed directly to a function as a
1690 /// non-escaping parameter.
1691 uint64_t DoesNotEscape : 1;
1692
1693 /// A bit that indicates whether it's possible to avoid coying this block to
1694 /// the heap when it initializes or is assigned to a local variable with
1695 /// automatic storage.
1696 uint64_t CanAvoidCopyToHeap : 1;
1697 };
1698
1699 /// Number of non-inherited bits in BlockDeclBitfields.
1700 enum { NumBlockDeclBits = 5 };
1701
1702 /// Pointer to the data structure used to lookup declarations
1703 /// within this context (or a DependentStoredDeclsMap if this is a
1704 /// dependent context). We maintain the invariant that, if the map
1705 /// contains an entry for a DeclarationName (and we haven't lazily
1706 /// omitted anything), then it contains all relevant entries for that
1707 /// name (modulo the hasExternalDecls() flag).
1708 mutable StoredDeclsMap *LookupPtr = nullptr;
1709
1710protected:
1711 /// This anonymous union stores the bits belonging to DeclContext and classes
1712 /// deriving from it. The goal is to use otherwise wasted
1713 /// space in DeclContext to store data belonging to derived classes.
1714 /// The space saved is especially significient when pointers are aligned
1715 /// to 8 bytes. In this case due to alignment requirements we have a
1716 /// little less than 8 bytes free in DeclContext which we can use.
1717 /// We check that none of the classes in this union is larger than
1718 /// 8 bytes with static_asserts in the ctor of DeclContext.
1719 union {
1720 DeclContextBitfields DeclContextBits;
1721 TagDeclBitfields TagDeclBits;
1722 EnumDeclBitfields EnumDeclBits;
1723 RecordDeclBitfields RecordDeclBits;
1724 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1725 FunctionDeclBitfields FunctionDeclBits;
1726 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1727 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1728 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1729 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1730 BlockDeclBitfields BlockDeclBits;
1731
1732 static_assert(sizeof(DeclContextBitfields) <= 8,
1733 "DeclContextBitfields is larger than 8 bytes!");
1734 static_assert(sizeof(TagDeclBitfields) <= 8,
1735 "TagDeclBitfields is larger than 8 bytes!");
1736 static_assert(sizeof(EnumDeclBitfields) <= 8,
1737 "EnumDeclBitfields is larger than 8 bytes!");
1738 static_assert(sizeof(RecordDeclBitfields) <= 8,
1739 "RecordDeclBitfields is larger than 8 bytes!");
1740 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1741 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1742 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1743 "FunctionDeclBitfields is larger than 8 bytes!");
1744 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1745 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1746 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1747 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1748 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1749 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1750 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1751 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1752 static_assert(sizeof(BlockDeclBitfields) <= 8,
1753 "BlockDeclBitfields is larger than 8 bytes!");
1754 };
1755
1756 /// FirstDecl - The first declaration stored within this declaration
1757 /// context.
1758 mutable Decl *FirstDecl = nullptr;
1759
1760 /// LastDecl - The last declaration stored within this declaration
1761 /// context. FIXME: We could probably cache this value somewhere
1762 /// outside of the DeclContext, to reduce the size of DeclContext by
1763 /// another pointer.
1764 mutable Decl *LastDecl = nullptr;
1765
1766 /// Build up a chain of declarations.
1767 ///
1768 /// \returns the first/last pair of declarations.
1769 static std::pair<Decl *, Decl *>
1770 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1771
1772 DeclContext(Decl::Kind K);
1773
1774public:
1775 ~DeclContext();
1776
1777 Decl::Kind getDeclKind() const {
1778 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1779 }
1780
1781 const char *getDeclKindName() const;
1782
1783 /// getParent - Returns the containing DeclContext.
1784 DeclContext *getParent() {
1785 return cast<Decl>(this)->getDeclContext();
1786 }
1787 const DeclContext *getParent() const {
1788 return const_cast<DeclContext*>(this)->getParent();
1789 }
1790
1791 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1792 /// different from getParent, e.g.:
1793 ///
1794 /// namespace A {
1795 /// struct S;
1796 /// }
1797 /// struct A::S {}; // getParent() == namespace 'A'
1798 /// // getLexicalParent() == translation unit
1799 ///
1800 DeclContext *getLexicalParent() {
1801 return cast<Decl>(this)->getLexicalDeclContext();
1802 }
1803 const DeclContext *getLexicalParent() const {
1804 return const_cast<DeclContext*>(this)->getLexicalParent();
1805 }
1806
1807 DeclContext *getLookupParent();
1808
1809 const DeclContext *getLookupParent() const {
1810 return const_cast<DeclContext*>(this)->getLookupParent();
1811 }
1812
1813 ASTContext &getParentASTContext() const {
1814 return cast<Decl>(this)->getASTContext();
1815 }
1816
1817 bool isClosure() const { return getDeclKind() == Decl::Block; }
1818
1819 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1820 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1821 const BlockDecl *getInnermostBlockDecl() const;
1822
1823 bool isObjCContainer() const {
1824 switch (getDeclKind()) {
1825 case Decl::ObjCCategory:
1826 case Decl::ObjCCategoryImpl:
1827 case Decl::ObjCImplementation:
1828 case Decl::ObjCInterface:
1829 case Decl::ObjCProtocol:
1830 return true;
1831 default:
1832 return false;
1833 }
1834 }
1835
1836 bool isFunctionOrMethod() const {
1837 switch (getDeclKind()) {
1838 case Decl::Block:
1839 case Decl::Captured:
1840 case Decl::ObjCMethod:
1841 return true;
1842 default:
1843 return getDeclKind() >= Decl::firstFunction &&
1844 getDeclKind() <= Decl::lastFunction;
1845 }
1846 }
1847
1848 /// Test whether the context supports looking up names.
1849 bool isLookupContext() const {
1850 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1851 getDeclKind() != Decl::Export;
1852 }
1853
1854 bool isFileContext() const {
1855 return getDeclKind() == Decl::TranslationUnit ||
1856 getDeclKind() == Decl::Namespace;
1857 }
1858
1859 bool isTranslationUnit() const {
1860 return getDeclKind() == Decl::TranslationUnit;
1861 }
1862
1863 bool isRecord() const {
1864 return getDeclKind() >= Decl::firstRecord &&
1865 getDeclKind() <= Decl::lastRecord;
1866 }
1867
1868 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1869
1870 bool isStdNamespace() const;
1871
1872 bool isInlineNamespace() const;
1873
1874 /// Determines whether this context is dependent on a
1875 /// template parameter.
1876 bool isDependentContext() const;
1877
1878 /// isTransparentContext - Determines whether this context is a
1879 /// "transparent" context, meaning that the members declared in this
1880 /// context are semantically declared in the nearest enclosing
1881 /// non-transparent (opaque) context but are lexically declared in
1882 /// this context. For example, consider the enumerators of an
1883 /// enumeration type:
1884 /// @code
1885 /// enum E {
1886 /// Val1
1887 /// };
1888 /// @endcode
1889 /// Here, E is a transparent context, so its enumerator (Val1) will
1890 /// appear (semantically) that it is in the same context of E.
1891 /// Examples of transparent contexts include: enumerations (except for
1892 /// C++0x scoped enums), and C++ linkage specifications.
1893 bool isTransparentContext() const;
1894
1895 /// Determines whether this context or some of its ancestors is a
1896 /// linkage specification context that specifies C linkage.
1897 bool isExternCContext() const;
1898
1899 /// Retrieve the nearest enclosing C linkage specification context.
1900 const LinkageSpecDecl *getExternCContext() const;
1901
1902 /// Determines whether this context or some of its ancestors is a
1903 /// linkage specification context that specifies C++ linkage.
1904 bool isExternCXXContext() const;
1905
1906 /// Determine whether this declaration context is equivalent
1907 /// to the declaration context DC.
1908 bool Equals(const DeclContext *DC) const {
1909 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1910 }
1911
1912 /// Determine whether this declaration context encloses the
1913 /// declaration context DC.
1914 bool Encloses(const DeclContext *DC) const;
1915
1916 /// Find the nearest non-closure ancestor of this context,
1917 /// i.e. the innermost semantic parent of this context which is not
1918 /// a closure. A context may be its own non-closure ancestor.
1919 Decl *getNonClosureAncestor();
1920 const Decl *getNonClosureAncestor() const {
1921 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1922 }
1923
1924 /// getPrimaryContext - There may be many different
1925 /// declarations of the same entity (including forward declarations
1926 /// of classes, multiple definitions of namespaces, etc.), each with
1927 /// a different set of declarations. This routine returns the
1928 /// "primary" DeclContext structure, which will contain the
1929 /// information needed to perform name lookup into this context.
1930 DeclContext *getPrimaryContext();
1931 const DeclContext *getPrimaryContext() const {
1932 return const_cast<DeclContext*>(this)->getPrimaryContext();
1933 }
1934
1935 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1936 /// other entities of the same name, or where it is a redeclaration if the
1937 /// two entities are compatible. This skips through transparent contexts.
1938 DeclContext *getRedeclContext();
1939 const DeclContext *getRedeclContext() const {
1940 return const_cast<DeclContext *>(this)->getRedeclContext();
1941 }
1942
1943 /// Retrieve the nearest enclosing namespace context.
1944 DeclContext *getEnclosingNamespaceContext();
1945 const DeclContext *getEnclosingNamespaceContext() const {
1946 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1947 }
1948
1949 /// Retrieve the outermost lexically enclosing record context.
1950 RecordDecl *getOuterLexicalRecordContext();
1951 const RecordDecl *getOuterLexicalRecordContext() const {
1952 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1953 }
1954
1955 /// Test if this context is part of the enclosing namespace set of
1956 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1957 /// isn't a namespace, this is equivalent to Equals().
1958 ///
1959 /// The enclosing namespace set of a namespace is the namespace and, if it is
1960 /// inline, its enclosing namespace, recursively.
1961 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1962
1963 /// Collects all of the declaration contexts that are semantically
1964 /// connected to this declaration context.
1965 ///
1966 /// For declaration contexts that have multiple semantically connected but
1967 /// syntactically distinct contexts, such as C++ namespaces, this routine
1968 /// retrieves the complete set of such declaration contexts in source order.
1969 /// For example, given:
1970 ///
1971 /// \code
1972 /// namespace N {
1973 /// int x;
1974 /// }
1975 /// namespace N {
1976 /// int y;
1977 /// }
1978 /// \endcode
1979 ///
1980 /// The \c Contexts parameter will contain both definitions of N.
1981 ///
1982 /// \param Contexts Will be cleared and set to the set of declaration
1983 /// contexts that are semanticaly connected to this declaration context,
1984 /// in source order, including this context (which may be the only result,
1985 /// for non-namespace contexts).
1986 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1987
1988 /// decl_iterator - Iterates through the declarations stored
1989 /// within this context.
1990 class decl_iterator {
1991 /// Current - The current declaration.
1992 Decl *Current = nullptr;
1993
1994 public:
1995 using value_type = Decl *;
1996 using reference = const value_type &;
1997 using pointer = const value_type *;
1998 using iterator_category = std::forward_iterator_tag;
1999 using difference_type = std::ptrdiff_t;
2000
2001 decl_iterator() = default;
2002 explicit decl_iterator(Decl *C) : Current(C) {}
2003
2004 reference operator*() const { return Current; }
2005
2006 // This doesn't meet the iterator requirements, but it's convenient
2007 value_type operator->() const { return Current; }
2008
2009 decl_iterator& operator++() {
2010 Current = Current->getNextDeclInContext();
2011 return *this;
2012 }
2013
2014 decl_iterator operator++(int) {
2015 decl_iterator tmp(*this);
2016 ++(*this);
2017 return tmp;
2018 }
2019
2020 friend bool operator==(decl_iterator x, decl_iterator y) {
2021 return x.Current == y.Current;
2022 }
2023
2024 friend bool operator!=(decl_iterator x, decl_iterator y) {
2025 return x.Current != y.Current;
2026 }
2027 };
2028
2029 using decl_range = llvm::iterator_range<decl_iterator>;
2030
2031 /// decls_begin/decls_end - Iterate over the declarations stored in
2032 /// this context.
2033 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2034 decl_iterator decls_begin() const;
2035 decl_iterator decls_end() const { return decl_iterator(); }
2036 bool decls_empty() const;
2037
2038 /// noload_decls_begin/end - Iterate over the declarations stored in this
2039 /// context that are currently loaded; don't attempt to retrieve anything
2040 /// from an external source.
2041 decl_range noload_decls() const {
2042 return decl_range(noload_decls_begin(), noload_decls_end());
2043 }
2044 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2045 decl_iterator noload_decls_end() const { return decl_iterator(); }
2046
2047 /// specific_decl_iterator - Iterates over a subrange of
2048 /// declarations stored in a DeclContext, providing only those that
2049 /// are of type SpecificDecl (or a class derived from it). This
2050 /// iterator is used, for example, to provide iteration over just
2051 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2052 template<typename SpecificDecl>
2053 class specific_decl_iterator {
2054 /// Current - The current, underlying declaration iterator, which
2055 /// will either be NULL or will point to a declaration of
2056 /// type SpecificDecl.
2057 DeclContext::decl_iterator Current;
2058
2059 /// SkipToNextDecl - Advances the current position up to the next
2060 /// declaration of type SpecificDecl that also meets the criteria
2061 /// required by Acceptable.
2062 void SkipToNextDecl() {
2063 while (*Current && !isa<SpecificDecl>(*Current))
2064 ++Current;
2065 }
2066
2067 public:
2068 using value_type = SpecificDecl *;
2069 // TODO: Add reference and pointer types (with some appropriate proxy type)
2070 // if we ever have a need for them.
2071 using reference = void;
2072 using pointer = void;
2073 using difference_type =
2074 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2075 using iterator_category = std::forward_iterator_tag;
2076
2077 specific_decl_iterator() = default;
2078
2079 /// specific_decl_iterator - Construct a new iterator over a
2080 /// subset of the declarations the range [C,
2081 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2082 /// member function of SpecificDecl that should return true for
2083 /// all of the SpecificDecl instances that will be in the subset
2084 /// of iterators. For example, if you want Objective-C instance
2085 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2086 /// &ObjCMethodDecl::isInstanceMethod.
2087 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2088 SkipToNextDecl();
2089 }
2090
2091 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2092
2093 // This doesn't meet the iterator requirements, but it's convenient
2094 value_type operator->() const { return **this; }
2095
2096 specific_decl_iterator& operator++() {
2097 ++Current;
2098 SkipToNextDecl();
2099 return *this;
2100 }
2101
2102 specific_decl_iterator operator++(int) {
2103 specific_decl_iterator tmp(*this);
2104 ++(*this);
2105 return tmp;
2106 }
2107
2108 friend bool operator==(const specific_decl_iterator& x,
2109 const specific_decl_iterator& y) {
2110 return x.Current == y.Current;
2111 }
2112
2113 friend bool operator!=(const specific_decl_iterator& x,
2114 const specific_decl_iterator& y) {
2115 return x.Current != y.Current;
2116 }
2117 };
2118
2119 /// Iterates over a filtered subrange of declarations stored
2120 /// in a DeclContext.
2121 ///
2122 /// This iterator visits only those declarations that are of type
2123 /// SpecificDecl (or a class derived from it) and that meet some
2124 /// additional run-time criteria. This iterator is used, for
2125 /// example, to provide access to the instance methods within an
2126 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2127 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2128 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2129 class filtered_decl_iterator {
2130 /// Current - The current, underlying declaration iterator, which
2131 /// will either be NULL or will point to a declaration of
2132 /// type SpecificDecl.
2133 DeclContext::decl_iterator Current;
2134
2135 /// SkipToNextDecl - Advances the current position up to the next
2136 /// declaration of type SpecificDecl that also meets the criteria
2137 /// required by Acceptable.
2138 void SkipToNextDecl() {
2139 while (*Current &&
2140 (!isa<SpecificDecl>(*Current) ||
2141 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2142 ++Current;
2143 }
2144
2145 public:
2146 using value_type = SpecificDecl *;
2147 // TODO: Add reference and pointer types (with some appropriate proxy type)
2148 // if we ever have a need for them.
2149 using reference = void;
2150 using pointer = void;
2151 using difference_type =
2152 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2153 using iterator_category = std::forward_iterator_tag;
2154
2155 filtered_decl_iterator() = default;
2156
2157 /// filtered_decl_iterator - Construct a new iterator over a
2158 /// subset of the declarations the range [C,
2159 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2160 /// member function of SpecificDecl that should return true for
2161 /// all of the SpecificDecl instances that will be in the subset
2162 /// of iterators. For example, if you want Objective-C instance
2163 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2164 /// &ObjCMethodDecl::isInstanceMethod.
2165 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2166 SkipToNextDecl();
2167 }
2168
2169 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2170 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2171
2172 filtered_decl_iterator& operator++() {
2173 ++Current;
2174 SkipToNextDecl();
2175 return *this;
2176 }
2177
2178 filtered_decl_iterator operator++(int) {
2179 filtered_decl_iterator tmp(*this);
2180 ++(*this);
2181 return tmp;
2182 }
2183
2184 friend bool operator==(const filtered_decl_iterator& x,
2185 const filtered_decl_iterator& y) {
2186 return x.Current == y.Current;
2187 }
2188
2189 friend bool operator!=(const filtered_decl_iterator& x,
2190 const filtered_decl_iterator& y) {
2191 return x.Current != y.Current;
2192 }
2193 };
2194
2195 /// Add the declaration D into this context.
2196 ///
2197 /// This routine should be invoked when the declaration D has first
2198 /// been declared, to place D into the context where it was
2199 /// (lexically) defined. Every declaration must be added to one
2200 /// (and only one!) context, where it can be visited via
2201 /// [decls_begin(), decls_end()). Once a declaration has been added
2202 /// to its lexical context, the corresponding DeclContext owns the
2203 /// declaration.
2204 ///
2205 /// If D is also a NamedDecl, it will be made visible within its
2206 /// semantic context via makeDeclVisibleInContext.
2207 void addDecl(Decl *D);
2208
2209 /// Add the declaration D into this context, but suppress
2210 /// searches for external declarations with the same name.
2211 ///
2212 /// Although analogous in function to addDecl, this removes an
2213 /// important check. This is only useful if the Decl is being
2214 /// added in response to an external search; in all other cases,
2215 /// addDecl() is the right function to use.
2216 /// See the ASTImporter for use cases.
2217 void addDeclInternal(Decl *D);
2218
2219 /// Add the declaration D to this context without modifying
2220 /// any lookup tables.
2221 ///
2222 /// This is useful for some operations in dependent contexts where
2223 /// the semantic context might not be dependent; this basically
2224 /// only happens with friends.
2225 void addHiddenDecl(Decl *D);
2226
2227 /// Removes a declaration from this context.
2228 void removeDecl(Decl *D);
2229
2230 /// Checks whether a declaration is in this context.
2231 bool containsDecl(Decl *D) const;
2232
2233 /// Checks whether a declaration is in this context.
2234 /// This also loads the Decls from the external source before the check.
2235 bool containsDeclAndLoad(Decl *D) const;
2236
2237 using lookup_result = DeclContextLookupResult;
2238 using lookup_iterator = lookup_result::iterator;
2239
2240 /// lookup - Find the declarations (if any) with the given Name in
2241 /// this context. Returns a range of iterators that contains all of
2242 /// the declarations with this name, with object, function, member,
2243 /// and enumerator names preceding any tag name. Note that this
2244 /// routine will not look into parent contexts.
2245 lookup_result lookup(DeclarationName Name) const;
2246
2247 /// Find the declarations with the given name that are visible
2248 /// within this context; don't attempt to retrieve anything from an
2249 /// external source.
2250 lookup_result noload_lookup(DeclarationName Name);
2251
2252 /// A simplistic name lookup mechanism that performs name lookup
2253 /// into this declaration context without consulting the external source.
2254 ///
2255 /// This function should almost never be used, because it subverts the
2256 /// usual relationship between a DeclContext and the external source.
2257 /// See the ASTImporter for the (few, but important) use cases.
2258 ///
2259 /// FIXME: This is very inefficient; replace uses of it with uses of
2260 /// noload_lookup.
2261 void localUncachedLookup(DeclarationName Name,
2262 SmallVectorImpl<NamedDecl *> &Results);
2263
2264 /// Makes a declaration visible within this context.
2265 ///
2266 /// This routine makes the declaration D visible to name lookup
2267 /// within this context and, if this is a transparent context,
2268 /// within its parent contexts up to the first enclosing
2269 /// non-transparent context. Making a declaration visible within a
2270 /// context does not transfer ownership of a declaration, and a
2271 /// declaration can be visible in many contexts that aren't its
2272 /// lexical context.
2273 ///
2274 /// If D is a redeclaration of an existing declaration that is
2275 /// visible from this context, as determined by
2276 /// NamedDecl::declarationReplaces, the previous declaration will be
2277 /// replaced with D.
2278 void makeDeclVisibleInContext(NamedDecl *D);
2279
2280 /// all_lookups_iterator - An iterator that provides a view over the results
2281 /// of looking up every possible name.
2282 class all_lookups_iterator;
2283
2284 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2285
2286 lookups_range lookups() const;
2287 // Like lookups(), but avoids loading external declarations.
2288 // If PreserveInternalState, avoids building lookup data structures too.
2289 lookups_range noload_lookups(bool PreserveInternalState) const;
2290
2291 /// Iterators over all possible lookups within this context.
2292 all_lookups_iterator lookups_begin() const;
2293 all_lookups_iterator lookups_end() const;
2294
2295 /// Iterators over all possible lookups within this context that are
2296 /// currently loaded; don't attempt to retrieve anything from an external
2297 /// source.
2298 all_lookups_iterator noload_lookups_begin() const;
2299 all_lookups_iterator noload_lookups_end() const;
2300
2301 struct udir_iterator;
2302
2303 using udir_iterator_base =
2304 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2305 std::random_access_iterator_tag,
2306 UsingDirectiveDecl *>;
2307
2308 struct udir_iterator : udir_iterator_base {
2309 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2310
2311 UsingDirectiveDecl *operator*() const;
2312 };
2313
2314 using udir_range = llvm::iterator_range<udir_iterator>;
2315
2316 udir_range using_directives() const;
2317
2318 // These are all defined in DependentDiagnostic.h.
2319 class ddiag_iterator;
2320
2321 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2322
2323 inline ddiag_range ddiags() const;
2324
2325 // Low-level accessors
2326
2327 /// Mark that there are external lexical declarations that we need
2328 /// to include in our lookup table (and that are not available as external
2329 /// visible lookups). These extra lookup results will be found by walking
2330 /// the lexical declarations of this context. This should be used only if
2331 /// setHasExternalLexicalStorage() has been called on any decl context for
2332 /// which this is the primary context.
2333 void setMustBuildLookupTable() {
2334 assert(this == getPrimaryContext() &&((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 2335, __PRETTY_FUNCTION__))
2335 "should only be called on primary context")((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclBase.h"
, 2335, __PRETTY_FUNCTION__))
;
2336 DeclContextBits.HasLazyExternalLexicalLookups = true;
2337 }
2338
2339 /// Retrieve the internal representation of the lookup structure.
2340 /// This may omit some names if we are lazily building the structure.
2341 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2342
2343 /// Ensure the lookup structure is fully-built and return it.
2344 StoredDeclsMap *buildLookup();
2345
2346 /// Whether this DeclContext has external storage containing
2347 /// additional declarations that are lexically in this context.
2348 bool hasExternalLexicalStorage() const {
2349 return DeclContextBits.ExternalLexicalStorage;
2350 }
2351
2352 /// State whether this DeclContext has external storage for
2353 /// declarations lexically in this context.
2354 void setHasExternalLexicalStorage(bool ES = true) const {
2355 DeclContextBits.ExternalLexicalStorage = ES;
2356 }
2357
2358 /// Whether this DeclContext has external storage containing
2359 /// additional declarations that are visible in this context.
2360 bool hasExternalVisibleStorage() const {
2361 return DeclContextBits.ExternalVisibleStorage;
2362 }
2363
2364 /// State whether this DeclContext has external storage for
2365 /// declarations visible in this context.
2366 void setHasExternalVisibleStorage(bool ES = true) const {
2367 DeclContextBits.ExternalVisibleStorage = ES;
2368 if (ES && LookupPtr)
2369 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2370 }
2371
2372 /// Determine whether the given declaration is stored in the list of
2373 /// declarations lexically within this context.
2374 bool isDeclInLexicalTraversal(const Decl *D) const {
2375 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2376 D == LastDecl);
2377 }
2378
2379 bool setUseQualifiedLookup(bool use = true) const {
2380 bool old_value = DeclContextBits.UseQualifiedLookup;
2381 DeclContextBits.UseQualifiedLookup = use;
2382 return old_value;
2383 }
2384
2385 bool shouldUseQualifiedLookup() const {
2386 return DeclContextBits.UseQualifiedLookup;
2387 }
2388
2389 static bool classof(const Decl *D);
2390 static bool classof(const DeclContext *D) { return true; }
2391
2392 void dumpDeclContext() const;
2393 void dumpLookups() const;
2394 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2395 bool Deserialize = false) const;
2396
2397private:
2398 /// Whether this declaration context has had externally visible
2399 /// storage added since the last lookup. In this case, \c LookupPtr's
2400 /// invariant may not hold and needs to be fixed before we perform
2401 /// another lookup.
2402 bool hasNeedToReconcileExternalVisibleStorage() const {
2403 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2404 }
2405
2406 /// State that this declaration context has had externally visible
2407 /// storage added since the last lookup. In this case, \c LookupPtr's
2408 /// invariant may not hold and needs to be fixed before we perform
2409 /// another lookup.
2410 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2411 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2412 }
2413
2414 /// If \c true, this context may have local lexical declarations
2415 /// that are missing from the lookup table.
2416 bool hasLazyLocalLexicalLookups() const {
2417 return DeclContextBits.HasLazyLocalLexicalLookups;
2418 }
2419
2420 /// If \c true, this context may have local lexical declarations
2421 /// that are missing from the lookup table.
2422 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2423 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2424 }
2425
2426 /// If \c true, the external source may have lexical declarations
2427 /// that are missing from the lookup table.
2428 bool hasLazyExternalLexicalLookups() const {
2429 return DeclContextBits.HasLazyExternalLexicalLookups;
2430 }
2431
2432 /// If \c true, the external source may have lexical declarations
2433 /// that are missing from the lookup table.
2434 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2435 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2436 }
2437
2438 void reconcileExternalVisibleStorage() const;
2439 bool LoadLexicalDeclsFromExternalStorage() const;
2440
2441 /// Makes a declaration visible within this context, but
2442 /// suppresses searches for external declarations with the same
2443 /// name.
2444 ///
2445 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2446 /// use of addDeclInternal().
2447 void makeDeclVisibleInContextInternal(NamedDecl *D);
2448
2449 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2450
2451 void loadLazyLocalLexicalLookups();
2452 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2453 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2454 bool Rediscoverable);
2455 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2456};
2457
2458inline bool Decl::isTemplateParameter() const {
2459 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2460 getKind() == TemplateTemplateParm;
2461}
2462
2463// Specialization selected when ToTy is not a known subclass of DeclContext.
2464template <class ToTy,
2465 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2466struct cast_convert_decl_context {
2467 static const ToTy *doit(const DeclContext *Val) {
2468 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2469 }
2470
2471 static ToTy *doit(DeclContext *Val) {
2472 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2473 }
2474};
2475
2476// Specialization selected when ToTy is a known subclass of DeclContext.
2477template <class ToTy>
2478struct cast_convert_decl_context<ToTy, true> {
2479 static const ToTy *doit(const DeclContext *Val) {
2480 return static_cast<const ToTy*>(Val);
2481 }
2482
2483 static ToTy *doit(DeclContext *Val) {
2484 return static_cast<ToTy*>(Val);
2485 }
2486};
2487
2488} // namespace clang
2489
2490namespace llvm {
2491
2492/// isa<T>(DeclContext*)
2493template <typename To>
2494struct isa_impl<To, ::clang::DeclContext> {
2495 static bool doit(const ::clang::DeclContext &Val) {
2496 return To::classofKind(Val.getDeclKind());
2497 }
2498};
2499
2500/// cast<T>(DeclContext*)
2501template<class ToTy>
2502struct cast_convert_val<ToTy,
2503 const ::clang::DeclContext,const ::clang::DeclContext> {
2504 static const ToTy &doit(const ::clang::DeclContext &Val) {
2505 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2506 }
2507};
2508
2509template<class ToTy>
2510struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2511 static ToTy &doit(::clang::DeclContext &Val) {
2512 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2513 }
2514};
2515
2516template<class ToTy>
2517struct cast_convert_val<ToTy,
2518 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2519 static const ToTy *doit(const ::clang::DeclContext *Val) {
2520 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2521 }
2522};
2523
2524template<class ToTy>
2525struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2526 static ToTy *doit(::clang::DeclContext *Val) {
2527 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2528 }
2529};
2530
2531/// Implement cast_convert_val for Decl -> DeclContext conversions.
2532template<class FromTy>
2533struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2534 static ::clang::DeclContext &doit(const FromTy &Val) {
2535 return *FromTy::castToDeclContext(&Val);
2536 }
2537};
2538
2539template<class FromTy>
2540struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2541 static ::clang::DeclContext *doit(const FromTy *Val) {
2542 return FromTy::castToDeclContext(Val);
2543 }
2544};
2545
2546template<class FromTy>
2547struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2548 static const ::clang::DeclContext &doit(const FromTy &Val) {
2549 return *FromTy::castToDeclContext(&Val);
2550 }
2551};
2552
2553template<class FromTy>
2554struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2555 static const ::clang::DeclContext *doit(const FromTy *Val) {
2556 return FromTy::castToDeclContext(Val);
2557 }
2558};
2559
2560} // namespace llvm
2561
2562#endif // LLVM_CLANG_AST_DECLBASE_H